Python Logo

1. Data Types

Built-in Data Types

Text Type

Keyword Usage Description
str x = 'Hello World' A String is a sequence of characters and can contain letters, numbers, symbols, and even spaces. (Strings are surrounded by either single or double quotation marks.)

Numeric Types

Keyword Usage Description
int x = 20 Integer is a whole number, positive or negative, without decimals, of unlimited length.
float x = 20.5 Float is a number, positive or negative, containing one or more decimals. Floats can also be scientific numbers with an 'e' to indicate the power of 10.
complex x = 1j Complex numbers are written with a 'j' as the imaginary part.

Sequence Types

Keyword Usage Description
list x = ['apple', 'banana', 'cherry'] Lists are used to store multiple items in a single variable. Lists are created using square brackets.
tuple x = ('apple', 'banana', 'cherry') A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.
range x = range(6) The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

Mapping Type

Keyword Usage Description
dict x = {'name' : 'John', 'age' : 36} A dictionary is a collection which is ordered, changeable and do not allow duplicates. Dictionaries are written with curly brackets, and have keys and values.

Set Types

Keyword Usage Description
set x = {'apple', 'banana', 'cherry'} A set is a collection which is unordered and unindexed. Sets are written with curly brackets.
frozenset x = frozenset({'apple', 'banana', 'cherry'}) The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable).

Boolean Type

Keyword Usage Description
bool x = True Booleans represent one of two values: True or False. In programming you often need to know if an expression is True or False.

Binary Types

Keyword Usage Description
bytes x = b'Hello' The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size. Object cannot be modified.
bytearray x = bytearray(5) The bytearray() function returns a bytearray object. It can convert objects into bytes objects, or create empty bytes object of the specified size. Object can be modified.
memoryview x = memoryview(bytes(5)) The memoryview() function allows direct read and write access to an object's byte-oriented data without needing to copy it first.

None Type

Keyword Usage Description
NoneType x = None NoneType is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.

Setting the Specific Data Type

Keyword Usage
str x = str("Hello World")
int x = int(20)
float x = float(20.5)
complex x = complex(1j)
list x = list(("apple", "banana", "cherry"))
tuple x = tuple(("apple", "banana", "cherry"))
range x = range(6)
dict x = dict(name="John", age=36)
set x = set(("apple", "banana", "cherry"))
frozenset x = frozenset(("apple", "banana", "cherry"))
bool x = bool(5)
bytes x = bytes(5)
bytearray x = bytearray(5)
memoryview x = memoryview(bytes(5))

2. Built in Functions

Keyword Usage
abs() Returns the absolute value of a number.
all() Returns True if all items in an iterable object are true.
any() Returns True if any item in an iterable object is true.
ascii() Returns a readable version of an object. Replaces none-ascii characters with escape character.
bin() Returns the binary version of a number.
bool() Returns the boolean value of the specified object.
bytearray() Returns an array of bytes.
bytes() Returns a bytes object.
callable() Returns True if the specified object is callable, otherwise False.
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method.
compile() Returns the specified source as an object, ready to be executed.
complex() Returns a complex number.
delattr() Deletes the specified attribute (property or method) from the specified object.
dict() Returns a dictionary (Array).
dir() Returns a list of the specified object's properties and methods.
divmod() Returns the quotient and the remainder when argument1 is divided by argument2.
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object.
eval() Evaluates and executes an expression.
exec() Executes the specified code (or object).
filter() Use a filter function to exclude items in an iterable object.
float() Returns a floating point number.
format() Formats a specified value.
frozenset() Returns a frozenset object.
getattr() Returns the value of the specified attribute (property or method).
globals() Returns the current global symbol table as a dictionary.
hasattr() Returns True if the specified object has the specified attribute (property/method).
hash() Returns the hash value of a specified object.
help() Executes the built-in help system.
hex() Converts a number into a hexadecimal value.
id() Returns the id of an object.
input() Allowing user input.
int() Returns an integer number.
isinstance() Returns True if a specified object is an instance of a specified object.
issubclass() Returns True if a specified class is a subclass of a specified object.
iter() Returns an iterator object.
len() Returns the length of an object.
list() Returns a list.
locals() Returns an updated dictionary of the current local symbol table.
map() Returns the specified iterator with the specified function applied to each item.
max() Returns the largest item in an iterable.
memoryview() Returns a memory view object.
min() Returns the smallest item in an iterable.
next() Returns the next item in an iterable.
object() Returns a new object.
oct() Converts a number into an octal.
open() Opens a file and returns a file object.
ord() Convert an integer representing the Unicode of the specified character.
pow() Returns the value of x to the power of y.
print() Prints to the standard output device.
property() Gets, sets, deletes a property.
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default).
repr() Returns a readable version of an object.
reversed() Returns a reversed iterator.
round() Rounds a numbers.
set() Returns a new set object.
setattr() Sets an attribute (property/method) of an object.
slice() Returns a slice object.
sorted() Returns a sorted list.
staticmethod() Converts a method into a static method.
str() Returns a string object.
sum() Sums the items of an iterator.
super() Returns an object that represents the parent class.
tuple() Returns a tuple.
type() Returns the type of an object.
vars() Returns the __dict__ property of an object.
zip() Returns an iterator, from two or more iterators.

3. Strings

Definition

A sequence of characters and can contain letters, numbers, symbols and even spaces.

String Length

    phrase = "Hello, World"
    print(len((phrase))
    returns 13
        

String Concatenation

    a = 'Hello'
    b = 'World'
    phrase = a + " " + b
    print(phrase)
    returns "Hello World"
        

Format Strings or f-String

F-string allows you to format selected parts of a string.
To specify a string as an f-string, simply put an f in front of the string literal, like this:

    txt = f"The price is 49 dollars"
    print(txt)
        

Placeholders and Modifiers

• To format values in an f-string, add placeholders {} , a placeholder can contain variables, operations, functions, and modifiers to format the value.

    price = 59
    txt = f"The price is {price} dollars"
    print(txt)
    returns "The price is 59 dollars"
        

• A placeholder can also include a modifier to format the value. A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed point number with 2 decimals:

    price = 59
    txt = f"The price is {price:.2f} dollars"
    print(txt)
    returns "The price is 59.00 dollars"
        

• You can also format a value directly without keeping it in a variable:

    txt = f"The price is {95:.2f} dollars"
    print(txt)
    returns "The price is 59.00 dollars"
        

Perform Operations in F-Strings

You can perform Python operations inside the placeholders.
• Perform a math operation in the placeholder, and return the result:

    txt = f"The price is {20 * 59} dollars"
    print(txt)
    returns "The price is 1180 dollars"
        

• Add taxes before displaying the price:

    price = 59
    tax = 0.25
    txt = f"The price is {price + (price * tax)} dollars"
    print(txt)
    returns "The price is 73.75 dollars"
        

• You can perform if...else statements inside the placeholders:

    price = 49
    txt = f"It is very {'Expensive' if price>50 else 'Cheap'}"
    print(txt)
    returns "It is very Cheap"
        

Execute Functions in F-Strings

You can execute functions inside the placeholder.
• Use the string method upper()to convert a value into upper case letters:

    fruit = "apples"
    txt = f"I love {fruit.upper()}"
    print(txt)
    returns "I love APPLES"
        

• The function does not have to be a built-in Python method, you can create your own functions and use them:

    def myconverter(x):
        return x * 0.3048

    txt = f"The plane is flying at a {myconverter(30000)} meter altitude"
    print(txt)
    returns "The plane is flying at a 9144.0 meter altitude"
        

Formatting Types

There are several modifiers that can be used to format values.

Operator Description Usage Output

Modify Strings

Keyword Usage Example Output Note
Upper Case print(phrase.upper()) phrase = "Hello, World" returns "HELLO, WORLD" You can also specify the first letter(s) only
Lower Case print(phrase.lower()) phrase = "Hello, World" returns "hello, world" You can also specify the first letter(s) only
Remove Whitespace print(phrase.strip()) phrase = " Hello, World " returns "Hello, World"
Replace String print(phrase.replace('H', 'J')) phrase = "Hello, World" returns "Jello, World" You can also replace word(s)
Split String print(phrase.split('', '')) phrase = "Hello, World" returns ['Hello', 'World']

String Methods

Keyword Usage
capitalize() Converts the first character to upper case.
casefold() Converts string into lower case.
center() Returns a centered string.
count() Returns the number of times a specified value occurs in a string.
encode() Returns an encoded version of the string.
endswith() Returns true if the string ends with the specified value.
expandtabs() Sets the tab size of the string.
find() Searches the string for a specified value and returns the position of where it was found.
format() Formats specified values in a string.
format_map() Formats specified values in a string.
index() Searches the string for a specified value and returns the position of where it was found.
isalnum() Returns True if all characters in the string are alphanumeric.
isalpha() Returns True if all characters in the string are in the alphabet.
isascii() Returns True if all characters in the string are ascii characters.
isdecimal() Returns True if all characters in the string are decimals.
isdigit() Returns True if all characters in the string are digits.
isidentifier() Returns True if the string is an identifier.
islower() Returns True if all characters in the string are lower case.
isnumeric() Returns True if all characters in the string are numeric.
isprintable() Returns True if all characters in the string are printable.
isspace() Returns True if all characters in the string are whitespaces.
istitle() Returns True if the string follows the rules of a title.
isupper() Returns True if all characters in the string are upper case.
join() Converts the elements of an iterable into a string.
ljust() Returns a left justified version of the string.
lower() Converts a string into lower case.
lstrip() Returns a left trim version of the string.
maketrans() Returns a translation table to be used in translations.
partition() Returns a tuple where the string is parted into three parts.
replace() Returns a string where a specified value is replaced with a specified value.
rfind() Searches the string for a specified value and returns the last position of where it was found.
rindex() Searches the string for a specified value and returns the last position of where it was found.
rjust() Returns a right justified version of the string.
rpartition() Returns a tuple where the string is parted into three parts.
rsplit() Splits the string at the specified separator, and returns a list.
rstrip() Returns a right trim version of the string.
split() Splits the string at the specified separator, and returns a list.
splitlines() Splits the string at line breaks and returns a list.
startswith() Returns true if the string starts with the specified value.
strip() Returns a trimmed version of the string.
swapcase() Swaps cases, lower case becomes upper case and vice versa.
title() Converts the first character of each word to upper case.
translate() Returns a translated string.
upper() Converts a string into upper case.
zfill() Fills the string with a specified number of 0 values at the beginning.

Escape Characters

Character Name Usage Example Output
' Single Quote txt = 'It's alright.' eg.print(txt) returns 'It's alright.'
\\ Backslash txt = 'Make your drive C:\' eg.print(txt)) returns 'Make your drive C:'
\n New Line txt = 'Hello\nWorld' eg.print(txt)) returns 'Hello<br>World
\r Carriage Return txt = 'Hello\rWorld' eg.print (txt)) returns 'Hello<br>World'
\t Tab txt = 'Hello\rWorld' eg.print (txt)) returns 'Hello&nbsp;&nbsp;&nbsp;&nbsp;World'
 Backspace txt = 'HelloWorld' eg.print (txt)) returns 'HelloWorld'
\f Form Feed
\ooo Octal value txt = 'Hello' eg.print (txt)) returns 'Hello'
\xhh Hex value txt = 'Hello' eg.print (txt)) returns 'Hello'

4. Variables

Definition

Variables are containers for storing data values.

Creating Variables

A variable is created the moment you first assign a value to it. (Note: Python has no command for declaring a variable.)
eg. x = 5

Variable Names

• A variable name must start with a letter or the underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.

examples

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Python Keywords

Keyword Description
and A logical operator.
as To create an alias.
assert For debugging.
break To break out of a loop.
class To define a class.
continue To continue to the next iteration of a loop.
def To define a function.
del To delete an object.
elif Used in conditional statements, same as else if.
else Used in conditional statements.
except Used with exceptions, what to do when an exception occurs.
False Boolean value, result of comparison operations.
finally Used with exceptions, a block of code that will be executed no matter if there is an exception or not.
for To create a for loop.
from To import specific parts of a module.
global To declare a global variable.
if To make a conditional statement.
import To import a module.
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal.
lambda To create an anonymous function.
None Represents a null value.
nonlocal To declare a non-local variable.
not A logical operator.
or A logical operator.
pass A null statement, a statement that will do nothing.
raise To raise an exception.
return To exit a function and return a value.
True Boolean value, result of comparison operations.
try To make a try...except statement.
while To create a while loop.
with Used to simplify exception handling.
yield To return a list of values from a generator.

Variable techniques

class="python_heading3">Camel Case

• Each word, except the first, starts with a capital letter. eg. myVariableName = "John"

class="python_heading3">Pascal Case

• Each word starts with a capital letter. eg. MyVariableName = "John"

class="python_heading3">Snake Case

• Each word is separated by an underscore character. e.g. my_variable_name = "John"

Assign Multiple Values

• Python allows you to assign values to multiple variables in one line. eg. x, y, z = "Orange", "Banana", "Cherry"
• Assign the same value to multiple variables in one line. eg. x = y = z = "Orange"
• If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables.

    fruits = ["apple", "banana", "cherry"]
    x, y, z = fruits
        

Output Variables

• The Python print() function is often used to output variables.

    x = "Python is awesome"
    print(x)
        

• In the print() function, you output multiple variables, separated by a comma.

    x = "Python"
    y= "is"
    z = "awesome"
    print(x, y, z)
        

• You can also use the + operator to output multiple variables.

    x = "Python"
    y= "is"
    z = "awesome"
    print(x + y + z)
        

(Note: Notice the space character after "Python " and "is ", without them the result would be "Pythonisawesome".)
• For numbers, the + character works as a mathematical operator.

    x = 5
    y = 10
    print(x + y)
        

Note: In the print() function, when you try to combine a string and a number with the + operator, Python will give you an error

Note: The best way to output multiple variables in the print() function is to separate them with commas, which even support different data types.

    x = 5
    y = "John"
    print(x, y)
        

Global and Local Variables

class="python_heading3">Global

Variables that are created outside of a function are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

    x = "awesome"

    def myfunc():
        print("Python is " + x)

    myfunc()
        

class="python_heading3">Local

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

    x = "awesome"

    def myfunc():
        x = "fantastic"
        print("Python is " + x)  # returns "Python is fantastic"

    myfunc()

    print("Python is " + x)  

    => returns "Python is awesome"
        

class="python_heading3">Global Keyword

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
• If you use the global keyword, the variable belongs to the global scope.

    def myfunc():
        global x
        x = "fantastic"

    myfunc()

    print("Python is " + x) 
        

Note: Also, use the global keyword if you want to change a global variable inside a function.

• To change the value of a global variable inside a function, refer to the variable by using the global keyword.

    x = "awesome"

    def myfunc():
        global x
    x = "fantastic"

    myfunc()

    print("Python is " + x)
        

5. Operators

Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations.

Operator Name Usage Example Output Note
+ Addition x + y eg. x = 5, y = 3 print(x + y)
- Subtraction x - y eg. x = 5, y = 3 print(x - y)
* Multiplication x * y eg. x = 5, y = 3 print(x * y)
/ Division x / y eg. x = 15, y = 3 print(x / y)
% Modulus x % y eg. x = 5, y = 2 print(x % y) returns the remainder or signed remainder of a division
** Exponentiation x ** y eg. x = 2, y = 5 print(x ** y) same as 2*2*2*2*2
// Floor division x // y eg. x = 15, y = 2 print(x // y) rounds the result down to the nearest whole number

Assignment Operators

Assignment operators are used to assign values to variables.

Operator Usage Same As Example Output
= x = 5 x = 5 eg. x = 5 print(x)
+= x += 3 x = x + 3 eg. x = 5, x += 3 print(x)
-= x -= 3 x = x - 3 eg. x = 5, x -= 3 print(x)
*= x *= 3 x = x * 3 eg. x = 5, x *= 3 print(x)
/= x /= 3 x = x / 3 eg. x = 15, x /= 3 print(x)
%= x %= 3 x = x % 3 eg. x = 5, x %= 3 print(x)
//= x //= 3 x = x // 3 eg. x = 5, x //= 3 print(x)
**= x **= 3 x = x ** 3 eg. x = 5, x **= 3 print(x)
&= x &= 3 x = x & 3 eg. x = 5, x &= 3 print(x)
|= x |= 3 x = x | 3 eg. x = 5, x |= 3 print(x)
^= x ^= 3 x = x ^ 3 eg. x = 5, x ^= 3 print(x)
>>= x >>= 3 x = x >> 3 eg. x = 5, x >>= 3 print(x)
<<= x <<= 3 x = x << 3 eg. x = 5, x <<= 3 print(x)
:= print(x := 3) x = 3 print(x) eg. print(x := 3)
>

Comparison Operators

Comparison operators are used to compare two values.

Operator Name Usage Example Output Note
== Equal x == y eg. x = 5, y = 3 print(x == y) 5 is not equal to 3
!= Not equal x != y eg. x = 5, y = 3 print(x != y) 5 is not equal to 3
> Greater than x > y eg. x = 5, y = 3 print(x > y) 5 is greater than to 3
< Less than x < y eg. x = 5, y = 3 print(x > y) 5 is not less than to 3
>= Greater than or equal to x >= y eg. x = 5, y = 3 print(x >= y) 5 is greater or equal to to 3
<= Less than or equal to x <= y eg. x = 5, y = 3 print(x >= y) 5 is neither less or equal to to 3
>

Logical Operators

Logical operators are used to combine conditional statements.

Operator Description Usage
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.

Operator Description Example Output Explanation Note
is Returns True if both variables are the same object eg. list1 = ['Cars', 'Bikes'], list2 = ['Cars', 'Bikes'], x = list2 print(x is list1) returns FALSE Note: list1 == list2 will return TRUE, because the lists have the same content
is not Returns True if both variables are not the same object eg. list1 = ['Cars', 'Bikes'], list2 = ['Cars', 'Bikes'], x = list2 print(x is not list1) returns TRUE

Membership Operators

Membership operators are used to test if a sequence is presented in an object.

Operator Description Example Output
in Returns True if a sequence with the specified value is present in the object eg. list1 = ['Cars', 'Bikes'] print('Bikes' in list1) returns TRUE
not in Returns True if a sequence with the specified value is not present in the object eg. list1 = ['Cars', 'Bikes'] print('Boats' not in list1) returns TRUE

Bitwise Operators

Bitwise operators are used to compare (binary) numbers.

Operator Name Description Usage
& AND Sets each bit to 1 if both bits are 1 x & y
| OR Sets each bit to 1 if one of two bits is 1 x | y
^ XOR Sets each bit to 1 if only one of two bits is 1 x ^ y
~ NOT Inverts all the bits ~x
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off x << 2
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off x >> 2

Operator Precedence

Operator precedence describes the order in which operations are performed.

The precedence order is described in the table below, starting with the highest precedence at the top:

Operator Name Example Output Explanation
() Parentheses eg. print((6 + 3) - (6 + 3)) returns 0 9 - 9
** Exponentiation eg. print(100 - 3 ** 3) returns 73 100 - 27
+x -x ~x Unary plus, unary minus, and bitwise NOT eg. print(100 + ~3) returns 96 100 + -4
* / // % Multiplication, division, floor division, and modulus eg. print(100 + 5 * 3) returns 115 100 + 15
+ - Addition and subtraction eg. print(100 - 5 * 3) returns 85 100 - 15
<< >> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is not in not in Comparisons, identity, and membership operators eg. print(5 == 4 + 1)) returns TRUE 5 == 5 = True
not Logical NOT eg. print(not 5 == 5) returns FALSE not True = False
and AND eg. print(1 or 2 and 3) returns 1 1 or 3 = 1 because and is higher than or eg. 3 is higher than 2
or OR eg. print(4 or 5 + 10 or 8) returns 4 4 or 15 or 8 = 4)

Note: If two operators have the same precedence, the expression is evaluated from left to right.

    print(5 + 4 - 7 + 3)
    returns 5
    (5 + 4 = 9, 9 - 7 = 2, 2 + 3 = 5)
        

6. Collection Types (Arrays)

Python does not have built-in support for Arrays, but Collections can be used instead.

There are four collection data types in the Python programming language:
List is a collection which is indexed, ordered and changeable. Allows duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Dictionary is a collection which is ordered and changeable. No duplicate members.
Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.

7. Lists

Definition

Lists are used to store multiple items in a single variable. Lists are created using square brackets.

List Items (Indexed)

List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list.

Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.

Allow Duplicates

Since lists are indexed, lists can have items with the same value. e.g. this_list = ["apple", "banana", "cherry", "apple", "cherry"]

List Methods

Keyword Usage
append() Adds an element at the end of the list.
clear() Removes all the elements from the list.
copy() Returns a copy of the lis.t
count() Returns the number of elements with the specified value.
extend() Add the elements of a list (or any iterable), to the end of the current list.
index() Returns the index of the first element with the specified value.
insert() Adds an element at the specified position.
pop() Removes the element at the specified position.
remove() Removes the item with the specified value.
reverse() Reverses the order of the list.
sort() Sorts the list.

List length

To determine how many items a list has, use the len() function.

    this_list = ["apple", "banana", "cherry"]
    print(len((thislist))
    returns 3
        

List Data Type

• String e.g. list1 = ["apple", "banana", "cherry"]
• Integer eg. list2 = [1, 5, 7, 9, 3]
• Boolean eg. list3 = [True, False, False]

Note: A list can contain different data types. e.g. this_list = ["abc", 34, True, 40, "male"]

type()

From Python's perspective, lists are defined as objects with the data type 'list'.

    mytuple = ("apple", "banana", "cherry")
    print(type(mytuple))
    returns class 'list'
        

The list() Constructor

It is also possible to use the list() constructor when creating a new list.
e.g. this_list = list(("apple", "banana", "cherry")) ** note the double round-brackets.

Access List

1. Accessing

List items are indexed and you can access them by referring to the index number.

    this_list = ["apple", "banana", "cherry"]
    print(this_list[1])
    returns "banana"
        

2. Negative Indexing

Negative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item etc.

    thislist = ["apple", "banana", "cherry"]
    print(thislist[-1])
    returns "cherry"
        

3. Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new list with the specified items.

    thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
    print(thislist[2:5])
    returns ['cherry', 'orange', 'kiwi']
        
Note The search will start at index 2 (included) and end at index 5 (not included).

• By leaving out the start value, the range will start at the first item.

    thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
    print(thislist[:4])
    returns ['apple', 'banana', 'cherry', 'orange'] 
        

• By leaving out the end value, the range will go on to the end of the list.

    thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
    print(thislist[2:])
    returns ['cherry', 'orange', 'kiwi', 'melon', 'mango'] 
        

• Specify negative indexes if you want to start the search from the end of the list.

    thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
    print(thislist[-4:-1])
    returns ['orange', 'kiwi', 'melon'] 
        

4. Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

    thislist = ["apple", "banana", "cherry"]
    if "apple" in thislist:
        print("Yes, 'apple' is in the fruits list")
        

Change List Items

1. Change Value

To change the value of a specific item, refer to the index number.

    thislist = ["apple", "banana", "cherry"]
    thislist[1] = "blackcurrant"
    print(thislist)
    returns ['apple', 'blackcurrant', 'cherry'] 
        

2. Change a Range of Item Values

• To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values.

    thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
    thislist[1:3] = ["blackcurrant", "watermelon"]
    print(thislist)
    returns ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango'] 
        

• If you insert more items than you replace, the new items will be inserted where you specified, and the remaining items will move accordingly.

    thislist = ["apple", "banana", "cherry"]
    thislist[1:2] = ["blackcurrant", "watermelon"]
    print(thislist)
    returns ['apple', 'blackcurrant', 'watermelon', 'cherry'] 
        

Note The length of the list will change when the number of items inserted does not match the number of items replaced.

Add List Items

1. Insert Items

To insert a new list item, without replacing any of the existing values, we can use the insert() method.

    thislist = ["apple", "banana", "cherry"]
    thislist.insert(2, "watermelon")
    print(thislist)
    returns ['apple', 'banana', 'watermelon', 'cherry'] 
        

2. Append List

To add an item to the end of the list, use the append() method.

    thislist = ["apple", "banana", "cherry"]
    thislist.append("orange")
    print(thislist)
    returns ['apple', 'banana', 'cherry', 'orange'] 
        

3. Extend List

• To append elements from another list to the current list, use the extend() method.

    thislist = ["apple", "banana", "cherry"]
    tropical = ["mango", "pineapple", "papaya"]
    thislist.extend(tropical)
    print(thislist)
    returns ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya'] 
    

• The extend() method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries etc.).

    thislist = ["apple", "banana", "cherry"]
    thistuple = ("kiwi", "orange")
    thislist.extend(thistuple)
    print(thislist)
    returns ['apple', 'banana', 'cherry', 'kiwi', 'orange'] 
        

Remove List Items

1. Remove item

The remove() method removes the specified item.

    thislist = ["apple", "banana", "cherry"]
    thislist.remove("banana")
    print(thislist)
    returns ['apple', 'cherry'] 
        

Note If there are more than one item with the specified value, the remove() method removes the first occurrence.

2. Remove Specified Index

• The pop() method removes the specified index.

    thislist = ["apple", "banana", "cherry"]
    thislist.pop(1)
    print(thislist)
    returns ['apple', 'cherry'] 
        

Note If you do not specify the index, the pop() method removes the last item.

▸ The del keyword also removes the specified index.

    thislist = ["apple", "banana", "cherry"]
    del thislist[0]
    print(thislist)
    returns ['banana', 'cherry'] 
    

▸ The del keyword can also delete the list completely.

    thislist = ["apple", "banana", "cherry"]
    del thislist
        

3. Clear List

The clear() method empties the list.

    thislist = ["apple", "banana", "cherry"]
    thislist.clear()
    print(thislist)
    returns [] 
        

List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. (See Loop Section for details on Loops in Python).

⮕ Without list comprehension you will have to write a for statement with a conditional test inside:

    fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
    newlist = []

    for x in fruits:
    if "a" in x:
        newlist.append(x)

    print(newlist)
        

⮕ With list comprehension you can do all that with only one line of code:

    fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
    newlist = [x for x in fruits if "a" in x]
    print(newlist)
        

1. Syntax

newlist = [expression for item in iterable if condition == True]

Note The condition is like a filter that only accepts the items that valuate to True.
e.g. newlist = [x for x in fruits if x != "apple"]
the condition if x != "apple" will return True for all elements other than "apple", making the new list contain all fruits except "apple".

Condition

The condition is optional and can be omitted e.g. newlist = [x for x in fruits]


Iterable

The iterable can be any iterable object, like a list, tuple, set etc.
e.g. newlist = [x for x in range(10)] ** You can use the range() function to create an iterable. **


Expression

The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list.
eg. newlist = [x.upper() for x in fruits]

• You can set the outcome to whatever you like.
e.g. newlist = ['hello' for x in fruits]

• The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome.
e.g. newlist = [x if x != "banana" else "orange" for x in fruits] => "Return the item if it is not banana, if it is banana return orange".

Sort Lists

Sort List Alphanumerically

List objects have a sort() method that will sort the list alphanumerically, ascending, by default.

• Sort the list alphabetically:

    thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
    thislist.sort()
    print(thislist)
    returns ['banana', 'kiwi', 'mango', 'orange', 'pineapple'] 
        

• Sort the list numerically:

    thislist = [100, 50, 65, 82, 23]
    thislist.sort()
    print(thislist)
    returns [23, 50, 65, 82, 100] 
        

Sort Descending

To sort descending, use the keyword argument reverse = True.

• Sort the list alphabetically:

    thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
    thislist.sort(reverse = True)
    print(thislist)
    returns ['pineapple', 'orange', 'mango', 'kiwi', 'banana'] 
        

• Sort the list numerically:

    thislist = [100, 50, 65, 82, 23]
    thislist.(reverse = True)
    print(thislist)
    returns [100, 82, 65, 50, 23] 
        

Case Insensitive Sort

By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters.

• Case sensitive sorting can give an unexpected result:

    thislist = ["banana", "Orange", "Kiwi", "cherry"]
    thislist.()
    print(thislist)
    returns ['Kiwi', 'Orange', 'banana', 'cherry'] 
        

⮕ Luckily we can use built-in functions as key functions when sorting a list.
So if you want a case-insensitive sort function, use str.lower as a key function.

• Perform a case-insensitive sort of the list:

    thislist = ["banana", "Orange", "Kiwi", "cherry"]
    thislist.(key = str.lower)
    print(thislist)
    returns ['banana', 'cherry', 'Kiwi', 'Orange'] 
        

Reverse Order

What if you want to reverse the order of a list, regardless of the alphabet?
The reverse() method reverses the current sorting order of the elements.

• Reverse the order of the list items:

    thislist = ["banana", "Orange", "Kiwi", "cherry"]
    thislist.reverse()
    print(thislist)
    returns ['cherry', 'Kiwi', 'Orange', 'banana'] 
        

Copy Lists

You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
You can use the built-in List method copy() to copy a list.

Copy Method

• Make a copy of a list with the the built-in copy() method:

    thislist = ["apple", "banana", "cherry"]
    mylist = thislist.copy()
    print(mylist)
    returns ['apple', 'banana', 'cherry'] 
        

List Method

Make a copy of a list with the built-in list() method:

    thislist = ["apple", "banana", "cherry"]
    mylist = list(thislist)
    print(mylist)
    returns ['apple', 'banana', 'cherry'] 
        

Use the slice Operator

Make a copy of a list with the : (slice) operator:

    thislist = ["apple", "banana", "cherry"]
    mylist = thislist[:]
    print(mylist)
    returns ['apple', 'banana', 'cherry'] 
        

Join Lists

There are several ways to join, or concatenate, two or more lists in Python.

+ (plus) Operator

• Join two list:

    list1 = ["a", "b", "c"]
    list2 = [1, 2, 3]
    list3 = list1 + list2
    print(list3)
    returns ['a', 'b', 'c', 1, 2, 3] 
        

Append & Extend

• Append list2 into list1:

    list1 = ["a", "b" , "c"]
    list2 = [1, 2, 3]

    for x in list2:
    list1.append(x)

    print(list1)
    returns  ['a', 'b', 'c', 1, 2, 3]
        

• Use the extend() method to add list2 at the end of list1:

    list1 = ["a", "b" , "c"]
    list2 = [1, 2, 3]
    list1.extend(list2)
    print(list1)
    returns ['a', 'b', 'c', 1, 2, 3] 
        

8. Tuples

Definition

Tuples are used to store multiple items in a single variable. Tuples are written with round brackets.

Tuple Items (Indexed)

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.

Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value. e.g. thistuple = ("apple", "banana", "cherry", "apple", "cherry")

Tuple Methods

Keyword Usage
count() Returns the number of times a specified value occurs in a tuple.
index() Searches the tuple for a specified value and returns the position of where it was found.

Tuple length

To determine how many items a tuple has, use the len() function.

    this_tuple = ["apple", "banana", "cherry"]
    print(len(this_tuple))
    returns 3 
        

Tuple Data Type

• String e.g. tuple1 = ["apple", "banana", "cherry"]
• Integer eg. tuple2 = [1, 5, 7, 9, 3]
• Boolean eg. tuple3 = [True, False, False]

Note: A tuple can contain different data types. eg. this_tuple = ["abc", 34, True, 40, "male"]

type()

From Python's perspective, tuples are defined as objects with the data type 'tuple'.

    mytuple = ("apple", "banana", "cherry")
    print(type(mytuple))
    returns class 'tuple' 
        

The tuple() Constructor

It is also possible to use the tuple() constructor when creating a new tuple.
e.g. this_tuple = tuple(("apple", "banana", "cherry")) ** note the double round-brackets.

Create Tuple With One Item

To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.

    thistuple = ("apple",)
    print(type(thistuple))
    returns class 'tuple' 
        
** NOT a tuple **
    thistuple = ("apple")
    print(type(thistuple))
    return class 'str'
        

Access Tuple

1. Accessing

Tuple items are indexed and you can access them by referring to the index number.

    this_tuple = ("apple", "banana", "cherry")
    print(thistuple[1])
    returns "banana"
        

2. Negative Indexing

Negative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item etc.

    thistuple = ("apple", "banana", "cherry")
    print(thistuple[-1])
    returns "cherry" 
        

3. Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new tuple with the specified items.

    thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
    print(thistuple[2:5])
    returns ('cherry', 'orange', 'kiwi') 
        

Note The search will start at index 2 (included) and end at index 5 (not included).

• By leaving out the start value, the range will start at the first item.

    thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
    print(thistuple[:4])
    returns ('apple', 'banana', 'cherry', 'orange') 
        

• By leaving out the end value, the range will go on to the end of the tuple.

    thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
    print(thistuple[2:])
    returns ('cherry', 'orange', 'kiwi', 'melon', 'mango') 
        

• Specify negative indexes if you want to start the search from the end of the tuple.

    thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
    print(thistuple[-4:-1])
    returns ('orange', 'kiwi', 'melon') 
        

4. Check if Item Exists

To determine if a specified item is present in a tuple use the in keyword:

    thistuple = ("apple", "banana", "cherry")
    if "apple" in thistuple:
    print("Yes, 'apple' is in the fruits tuple")
        

Update Tuples

Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.
But there are some workarounds.

Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

    x = ("apple", "banana", "cherry")
    y = list(x)
    y[1] = "kiwi"
    x = tuple(y)

    print(x)
    returns ("apple", "kiwi", "cherry") 
        

Add Items

Since tuples are immutable, they do not have a built-in append() method, but there are other ways to add items to a tuple.
Convert into a list.Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple.

    thistuple = ("apple", "banana", "cherry")
    y = list(thistuple)
    y.append("orange")
    thistuple = tuple(y)
    returns ('apple', 'banana', 'cherry', 'orange') 
        

Add tuple to a tuple.ou are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple.

    thistuple = ("apple", "banana", "cherry")
    y = ("orange",)
    thistuple += y

    print(thistuple)
    returns ('apple', 'banana', 'cherry', 'orange') 
        

Note: When creating a tuple with only one item, remember to include a comma after the item, otherwise it will not be identified as a tuple.

Remove Items

Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items

    thistuple = ("apple", "banana", "cherry")
    y = list(thistuple)
    y.remove("apple")
    thistuple = tuple(y)
    returns ('banana', 'cherry')    
        

Or you can delete the tuple completely using the del key.

    thistuple = ("apple", "banana", "cherry")
    del thistuple
    print(thistuple) #this will raise an error because the tuple no longer exists
        

Unpack Tuples

Unpacking a Tuple

When we create a tuple, we normally assign values to it. This is called "packing" a tuple.

    fruits = ("apple", "banana", "cherry")
        

But, in Python, we are also allowed to extract the values back into variables. This is called "unpacking".

    fruits = ("apple", "banana", "cherry")
    (green, yellow, red) = fruits

    print(green)
    print(yellow)
    print(red)
    returns:
    apple
    banana
    cherry
        

Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.

Using Asterisk *

• If the number of variables is less than the number of values, you can add an * to the variable name and the values will be assigned to the variable as a list.

    fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
    (green, yellow, *red) = fruits

    print(green)
    print(yellow)
    print(red)
    returns:
    apple
    banana
    ['cherry', 'strawberry', 'raspberry']
        

• If the asterisk is added to another variable name than the last, Python will assign values to the variable until the number of values left matches the number of variables left.

    fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

    (green, *tropic, red) = fruits

    print(green)
    print(tropic)
    print(red)
    returns:
    apple
    ['mango', 'papaya', 'pineapple']
        cherry
        

Join Tuples

To join two or more tuples you can use the + operator.

+ (plus) Operator

• Join two tuples:

    tuple1 = ["a", "b", "c"]
    tuple2 = [1, 2, 3]
    tuple3 = tuple1 + tuple2
    print(tuple3)
    returns ['a', 'b', 'c', 1, 2, 3] 
        

Multiply Tuples

If you want to multiply the content of a tuple a given number of times, you can use the * operator

* (multiply) Operator

• Multiply the fruits tuple by 2:

    fruits = ("apple", "banana", "cherry")
    mytuple = fruits * 2
    print(mytuple)
    returns ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry') 
        

9. Dictionaries

Definition

Dictionaries are used to store data values in key:value pairs. Dictionaries are written with curly brackets.

Dictionary Items

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

    thisdict = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    print(thisdict["brand"])
    returns "Ford"
        

Ordered

When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key.

    thisdict = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964,
        "year": 2020
    }
    print(thisdict)
    returns {'brand': 'Ford', 'model': 'Mustang', 'year': 2020} 
        

Note: Duplicate values will overwrite existing values

Dictionary Methods

Keyword Usage
clear() Removes all the elements from the dictionary.
copy() Returns a copy of the dictionary.
fromkeys() Returns a dictionary with the specified keys and value.
get() Returns the value of the specified key.
items() Returns a list containing a tuple for each key value pair.
keys() Returns a list containing the dictionary's keys.
pop() Removes the element with the specified key.
popitem() Removes the last inserted key-value pair.
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value.
update() Updates the dictionary with the specified key-value pairs.
values() Returns a list of all the values in the dictionary.

Dictionary length

To determine how many items a dictionary has, use the len() function.

    thisdict = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964,
        "year": 2020
    }
    print(len(thisdict))
    returns 3
        

Dictionary Data Type

A dictionary can contain different data types: e.g. String, int, boolean, and list.

    thisdict = {
        "brand": "Ford",
        "electric": False,
        "year": 1964,
    "colors": ["red", "white", "blue"]
        }
        

type()

From Python's perspective, dictionaries are defined as objects with the data type 'dict'.

    mydict = {"brand": "Ford", "year": "1964"}
    print(type(mydict))
    returns class 'dict' 
        

The dict() Constructor

It is also possible to use the dict() constructor when creating a new dictionary.
e.g. this_dictionary = dict(name = "John", age = 36, country = "Norway")

Acces Dictionary Items

1. Accessing

• You can access the items of a dictionary by referring to its key name, inside square brackets.

    thisdict = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    x = thisdict["model"]
    returns "Mustang" 
        

• There is also a method called get() that will give you the same result. e.g. x = thisdict.get("model")

2. Get Keys

The keys() method will return a list of all the keys in the dictionary.

    x = thisdict.keys()
    returns dict_keys(['brand', 'model', 'year']) 
        

• The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.

    car = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    x = car.keys()
    print(x) #before the change
    returns dict_keys(['brand', 'model', 'year']) 

    car["color"] = "white"
    print(x) #after the change
    returns dict_keys(['brand', 'model', 'year', 'color']) 
        

3. Get Values

The values() method will return a list of all the values in the dictionary.

    x = thisdict.values()
    returns dict_values(['Ford', 'Mustang', 1964]) 
        

• The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the values list.

    car = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    x = car.values()

    print(x) #before the change
    returns dict_values(['Ford', 'Mustang', 1964]) 

    car["year"] = 2020
    print(x) #after the change
    returns dict_values(['Ford', 'Mustang', 2020]) 
        

•Add a new item to the original dictionary, and see that the values list gets updated as well.

    car = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    x = car.values()

    print(x) #before the change
    returns dict_values(['Ford', 'Mustang', 1964]) 

    car["color"] = "red"
    print(x) #after the change
    returns dict_values(['Ford', 'Mustang', 1964, 'red']) 
        

4. Get Items

The items() method will return each item in a dictionary, as tuples in a list.

    x = thisdict.items()
    returns dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]) 
        

• The returned list is a view of the items of the dictionary, meaning that any changes done to the dictionary will be reflected in the items list.

    car = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }

    x = car.items()

    print(x) #before the change
    returns dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]) 

    car["year"] = 2020

    print(x) #after the change
    returns dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2020)]) 
        

•Add a new item to the original dictionary, and see that the values list gets updated as well.

    car = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }

    x = car.items()
    print(x) #before the change
    returns dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)]) 

    car["color"] = "red"
    print(x) #after the change
    returns dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964), ('color', 'red')]) 
        

5. Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword.

    thisdict = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    if "model" in thisdict:
    print("Yes, 'model' is one of the keys in the thisdict dictionary")
        

Change Dictionary Items

1. Change Values

You can change the value of a specific item by referring to its key name.

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    thisdict["year"] = 2018
    print(thisdict)
    returns {'brand': 'Ford', 'model': 'Mustang', 'year': 2018} 
        

2. Update Dictionary

The update() method will update the dictionary with the items from the given argument. The argument must be a dictionary, or an iterable object with key:value pairs.

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    thisdict.update({"year": 2020})
    print(thisdict) 
    returns {'brand': 'Ford', 'model': 'Mustang', 'year': 2020} 
        

Add Dictionary Items

1. Add Items

Adding an item to the dictionary is done by using a new index key and assigning a value to it.

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    thisdict["color"] = "red"
    print(thisdict)
    returns {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'} 
        

2. Update Dictionary

The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added. The argument must be a dictionary, or an iterable object with key:value pairs.

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    thisdict.update({"color": "red"})
    returns {'brand': 'Ford', 'model': 'Mustang', 'year': 2020} 
    returns {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'} 
        

Remove Dictionary Items

There are several methods to remove items from a dictionary.
• The pop() method removes the item with the specified key name.

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    thisdict.pop("model")
    print(thisdict) 
    returns {'brand': 'Ford', 'year': 1964} 
        

• The popitem() method removes the last inserted item.

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    thisdict.popitem()
    print(thisdict)
    returns {'brand': 'Ford', 'model': 'Mustang'} 
        

• The del keyword removes the item with the specified key name.

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    del thisdict["model"]
    print(thisdict)
    returns {'brand': 'Ford', 'year': '1964'} 
        

• The del keyword can also delete the dictionary completely.

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    del thisdict
    print(thisdict) #this will cause an error because "thisdict" no longer exists.
        

• The clear() method empties the dictionary.

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    thisdict.clear()
    print(thisdict)
    returns {}
        

Copy Dictionaries

You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2. • here are ways to make a copy, one way is to use the built-in Dictionary method copy().

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    mydict = thisdict.copy()
    print(mydict)
    returns {'brand': 'Ford', 'model': 'Mustang', 'year': 1964} 
        

• Another way to make a copy is to use the built-in function dict().

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    mydict = dict(thisdict)
    print(mydict)
    returns {'brand': 'Ford', 'model': 'Mustang', 'year': 1964} 
        

Nested Dictionaries

• A dictionary can contain dictionaries, this is called nested dictionaries.

    myfamily = {
        "child1" : {
            "name" : "Emil",
            "year" : 2004
    },
        "child2" : {
            "name" : "Tobias",
            "year" : 2007
    },
        "child3" : {
            "name" : "Linus",
            "year" : 2011
    }
    }
        

• Or, if you want to add three dictionaries into a new dictionary.

    child1 = {
        "name" : "Emil",
        "year" : 2004
    }
    child2 = {
        "name" : "Tobias",
        "year" : 2007
    }
    child3 = {
        "name" : "Linus",
        "year" : 2011
    }

    myfamily = {
        "child1" : child1,
        "child2" : child2,
        "child3" : child3
    } 
        

Access Items in Nested Dictionaries.

To access items from a nested dictionary, you use the name of the dictionaries, starting with the outer dictionary.

    print(myfamily["child2"]["name"])
    returns  "Tobias"
        

10. Sets

Definition

Sets are used to store multiple items in a single variable. Sets are created using curly brackets.

List Items (Indexed)

List items are indexed, the first item has index [0], the second item has index [1] etc.

Unordered

Unordered means that the items in a set do not have a defined order. Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been created. Once a set is created, you cannot change its items, but you can remove items and add new items.

Duplicates Not Allowed

Sets cannot have two items with the same value. Duplicate values will be ignored.

    thisset = {"apple", "banana", "cherry", "apple"}
    print(thisset)
    returns {'banana', 'cherry', 'apple'} 
        

Note: The values True and 1 are considered the same value in sets, and are treated as duplicates.

    thisset = {"apple", "banana", "cherry", True, 1, 2}
    print(thisset)
    returns {True, 2, 'banana', 'cherry', 'apple'} 
        

Note: The values False and 0 are considered the same value in sets, and are treated as duplicates.

    thisset = {"apple", "banana", "cherry", False, True, 0}
    print(thisset)
    returns {False, True, 'cherry', 'apple', 'banana'} 
    

Set Methods

Keyword Shortcut Usage
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() - Returns a set containing the difference between two or more sets
difference_update() -= Removes the items in this set that are also included in another, specified set
discard() Remove the specified item
intersection() & Returns a set, that is the intersection of two other sets
intersection_update() &= Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() <= Returns whether another set contains this set or not
< Returns whether all items in this set is present in other, specified set(s)
issuperset() >= Returns whether this set contains another set or not
> Returns whether all items in other, specified set(s) is present in this set
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() ^ Returns a set with the symmetric differences of two sets
symmetric_difference_update() ^= Inserts the symmetric differences from this set and another
union() | Return a set containing the union of sets
update() |= Update the set with the union of this set and others

Set length

To determine how many items a set has, use the len() function.

    this_set = {"apple", "banana", "cherry"}
    print(len(this_set))
    returns 3
        

Set Data Type

• String e.g. set1 = {"apple", "banana", "cherry"}
• Integer eg. set2 = {1, 5, 7, 9, 3}
• Boolean eg. set3 = {True, False, False}

Note: A set can contain different data types. e.g. this_set = {"abc", 34, True, 40, "male"}

type()

From Python's perspective, sets are defined as objects with the data type 'set'.

    myset = {"apple", "banana", "cherry"}
    print(type(myset))
    returns class 'list' 
        

The set() Constructor

It is also possible to use the set() constructor when creating a new set.
e.g. this_set = set(("apple", "banana", "cherry")) ** note the double round-brackets.

Access Set

1. Accessing

You cannot access items in a set by referring to an index or a key. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword. • Loop through the set, and print the values:

    thisset = {"apple", "banana", "cherry"}
    for x in thisset:
    print(x) 
    returns "apple" 
            "banana"
            "cherry"
        

• Check if "banana" is present in the set::

    thisset = {"apple", "banana", "cherry"}
    print("banana" in thisset)
    returns True 
        

• Check if "banana" is not present in the set::

    thisset = {"apple", "banana", "cherry"}
    print("banana" not in thisset)
    returns True 
        

Change List Items

Note: Once a set is created, you cannot change its items, but you can add new items.

Add Set Items

1. Add Items

To add one item to a set use the add() method.

    thisset = {"apple", "banana", "cherry"}
    thisset.add("orange")
    print(thisset)
    returns {'apple', 'cherry', 'orange', 'banana'} 
        

2. Add Sets

To add items from another set into the current set, use the update() method.

    thisset = {"apple", "banana", "cherry"}
    tropical = {"pineapple", "mango", "papaya"}
    thisset.update(tropical)
    print(thisset)
    returns {'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'} 
        

3. Add Any Iterable

The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries etc.).

    thisset = {"apple", "banana", "cherry"}
    mylist = ["kiwi", "orange"]
    thisset.update(mylist)
    print(thisset)
    returns {'banana', 'cherry', 'apple', 'orange', 'kiwi'}  
        

Remove Set Items

To remove an item in a set, use the remove(), or the discard() method. • Remove "banana" by using the remove() method:

    thisset = {"apple", "banana", "cherry"}
    thisset.remove("banana")
    print(thisset)
    returns {'apple', 'cherry'} 
        

Note If the item to remove does not exist, remove() will raise an error. • Remove "banana" by using the remove() method:

    thisset = {"apple", "banana", "cherry"}
    thisset.discard("banana")
    print(thisset)
    returns {'apple', 'cherry'} 
        

Note If the item to remove does not exist, discard() will not raise an error. • You can also use the pop() method to remove an item, but this method will remove a random item, so you cannot be sure what item that gets removed.

    thisset = {"apple", "banana", "cherry"}
    x = thisset.pop(1)
    print(x)  #removed item
    print(thisset)  #the set after removal
    returns "banana" 
            ['apple', 'cherry']
        

Note Sets are unordered, so when using the pop() method, you do not know which item that gets removed. • The clear() method empties the set:

    thisset = {"apple", "banana", "cherry"}
    thisset.clear()
    print(thisset)
    returns set() 
        

• The del keyword will delete the set completely.

    thisset = {"apple", "banana", "cherry"}
    del thisset
        

Join Sets

There are several ways to join two or more sets in Python.

1. Union

The union() method returns a new set with all items from both sets.

    set1 = {"a", "b", "c"}
    set2 = {1, 2, 3}
    set3 = set1.union(set2)
    print(set3)
    returns {'b', 2, 'c', 'a', 1, 3}  
        

• You can use the | operator instead of the union() method, and you will get the same result.

    set1 = {"a", "b", "c"}
    set2 = {1, 2, 3}
    set3 = set1 | set2
    print(set3)
    returns {'a', 1, 'b', 'c', 2, 3} 
        

• All the joining methods and operators can be used to join multiple sets. When using a method, just add more sets in the parentheses, separated by commas. Join multiple sets with the union() method:

    set1 = {"a", "b", "c"}
    set2 = {1, 2, 3}
    set3 = {"John", "Elena"}
    set4 = {"apple", "bananas", "cherry"}
    myset = set1.union(set2, set3, set4)
    print(myset)
    returns {Elena, 'a', John, 3, apple, 1, 'c', 2, banana, 'b', cherry} 
        

Join multiple sets with the union() method:

    set1 = {"a", "b", "c"}
    set2 = {1, 2, 3}
    set3 = {"John", "Elena"}
    set4 = {"apple", "bananas", "cherry"}
    myset = set1 | set2 | set3 |set4
    print(myset)
    returns {John, 'b', 3, Elena, 1, cherry, 'c', apple, 2, 'a', banana}  
        

• The union() method allows you to join a set with other data types, like lists or tuples. The result will be a set.

    x = {"a", "b", "c"}
    y = (1, 2, 3)
    z = x.union(y)
    print(z) 
    returns {3, 1, 'b', 'a', 'c', 2} 
        

Note: The | operator only allows you to join sets with sets, and not with other data types like you can with the union() method.

2. Update

The update() method inserts all items from one set into another. The update() changes the original set, and does not return a new set.

    set1 = {"a", "b" , "c"}
    set2 = {1, 2, 3}
    set1.update(set2)
    print(set1)
    returns {2, 'b', 'a', 1, 3, 'c'} 
        

Note: Both union() and update() will exclude any duplicate items.

3. Intersection

The intersection() method will return a new set, that only contains the items that are present in both sets.(Keep ONLY the duplicates)

    set1 = {"apple", "banana", "cherry"}
    set2 = {"google", "microsoft", "apple"}
    set3 = set1.intersection(set2)
    print(set3)
    returns {'apple'} 
        

• You can use the & operator instead of the intersection() method, and you will get the same result.

    set1 = {"apple", "banana", "cherry"}
    set2 = {"google", "microsoft", "apple"}
    set3 = set1 & set2
    print(set3)
    returns {'apple'} 
        

Note: The & operator only allows you to join sets with sets, and not with other data types like you can with the intersection() method.

• The intersection_update() method will also keep ONLY the duplicates, but it will change the original set instead of returning a new set.

    set1 = {"apple", "banana", "cherry"}
    set2 = {"google", "microsoft", "apple"}
    set1.intersection_update(set2)
    print(set1)
    returns {'apple'} 
        

• The values True and 1 are considered the same value. The same goes for False and 0.

    set1 = {"apple", 1,  "banana", 0, "cherry"}
    set2 = {False, "google", 1, "apple", 2, True}
    set3 = set1.intersection(set2)
    print(set3)
    returns {False, True, 'apple'} 
        

4. Difference

The difference() method will return a new set that will contain only the items from the first set that are not present in the other set.

    set1 = {"apple", "banana", "cherry"}
    set2 = {"google", "microsoft", "apple"}
    set3 = set1.difference(set2)
    print(set3)
    returns {'banana', 'cherry'} 
        

• You can use the - operator instead of the difference() method, and you will get the same result.

    set1 = {"apple", "banana", "cherry"}
    set2 = {"google", "microsoft", "apple"}
    set3 = set1 - set2
    print(set3) 
    returns {'banana', 'cherry'} 
        

Note: The - operator only allows you to join sets with sets, and not with other data types like you can with the difference() method.

The difference_update() method will also keep the items from the first set that are not in the other set, but it will change the original set instead of returning a new set.

    set1 = {"apple", "banana", "cherry"}
    set2 = {"google", "microsoft", "apple"}
    set1.difference_update(set2)
    print(set1) 
    returns {'banana', 'cherry'} 
        

5. Symmetric Differences

The symmetric_difference() method will keep only the elements that are NOT present in both sets.

    set1 = {"apple", "banana", "cherry"}
    set2 = {"google", "microsoft", "apple"}
    set3 = set1.symmetric_difference(set2)
    print(set3)
    returns {'google', 'banana', 'microsoft', 'cherry'} 
        

• You can use the ^ operator instead of the symmetric_difference() method, and you will get the same result.

    set1 = {"apple", "banana", "cherry"}
    set2 = {"google", "microsoft", "apple"}
    set3 = set1 ^ set2
    print(set3)
    returns {'google', 'banana', 'microsoft', 'cherry'} 
        

Note: The ^ operator only allows you to join sets with sets, and not with other data types like you can with the symmetric_difference() method.

The symmetric_difference_update() method will also keep all but the duplicates, but it will change the original set instead of returning a new set.

    set1 = {"apple", "banana", "cherry"}
    set2 = {"google", "microsoft", "apple"}
    set1.symmetric_difference_update(set2)
    print(set1)
    returns {'google', 'banana', 'microsoft', 'cherry'}  
        

11. Statements

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:
• Equals: "a == b"
• Not Equals: "a != b"
• Less than: "a < b"
• Less than or equal to: "a <=b"
• Greater than: "a> b"
• Greater than or equal to: "a >= b"
These conditions can be used in several ways, most commonly in "if statements" and loops.

If statement

An "if statement" is written by using the if keyword.

      a = 33
      b = 200
      if b > a:
          print("b is greater than a")
      

In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a".

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.

      a = 33
      b = 200
      if b > a:
          print("b is greater than a")
      returns "b is greater than a" 
      

Note:If statement, without indentation will raise an error

Elif

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".

      a = 33
      b = 33
      if b > a:
          print("b is greater than a")
      elif a == b:
          print("a and b are equal")
      returns"a and b are equal"  
      

In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal".

Else

The else keyword catches anything which isn't caught by the preceding conditions.

      a = 200
      b = 33
      if b > a:
          print("b is greater than a")
      elif a == b:
          print("a and b are equal")
      else:
          print("a is greater than b")
          returns"a is greater than b"  
      

In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b".

• You can also have an else without the elif:

      a = 200
      b = 33
      if b > a:
          print("b is greater than a")
      else:
          print("a is greater than b")
          returns "a is greater than b" 
      

Shorthand If

If you have only one statement to execute, you can put it on the same line as the if statement.

      if a > b: print("a is greater than b")
      

Shorthand If..Else

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line.

      a = 2
      b = 330
      print("A") if a > b else print("B")
      

Note:This technique is known as Ternary Operators, or Conditional Expressions.

• You can also have multiple else statements on the same line:

      a = 2
      b = 330
      print("A") if a > b else print("=") if a == b else print("B")
      

And

The and keyword is a logical operator, and is used to combine conditional statements.

      a = 200
      b = 33
      c = 500
      if a > b and c > a:
          print("Both conditions are True")
      

Or

The or keyword is a logical operator, and is used to combine conditional statements.

      a = 200
      b = 33
      c = 500
      if a > b or a > c:
          print("At least one of the conditions is True")
      

Not

The not keyword is a logical operator, and is used to reverse the result of the conditional statement.

      a = 33
      b = 200
      if not a > b:
          print("a is NOT greater than b")
      

Nested If

You can have if statements inside if statements, this is called nested if statements.

      x = 41

      if x > 10:
          print("Above ten,")
          if x > 20:
          print("and also above 20!")
          else:
          print("but not above 20.")
      returns "Above ten,"
              "and also above 20!" 
      

The Pass Statement

If statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.

      a = 33
      b = 200

      if b > a:
          pass
      

Note:Having an empty if statement like this, would raise an error without the pass statement.

12. Loops (Iteration)

Python has two primitive loop commands:
While loops
For loops

While Loop

The While Loop

With the while loop we can execute a set of statements as long as a condition is true.

    i = 1
    while i < 6:
        print(i)
        i += 1
        returns 1
                2
                3
                4
                5
		

Note: Remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.

The break Statement

With the break statement we can stop the loop even if the while condition is true.

    i = 1
    while i < 6:
        print(i)
        if i == 3:
        break
        i += 1
    returns 1
            2
            3
		

The continue Statement

With the continue statement we can stop the current iteration, and continue with the next.

    i = 0
    while i < 6:
        i += 1
        if i == 3:
        continue
        print(i)
    returns 1
            2
            3
            4
            5
            6
		

The else Statement

With the else statement we can run a block of code once when the condition no longer is true.

    i = 1
    while i < 6:
        print(i)
        i += 1
    else:
        print("i is no longer less than 6")
    returns 1
            2
            3
            4
            5
            "i is no longer less than 6"
		

For Loop

The For Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

    fruits = ["apple", "banana", "cherry"]
    for x in fruits:
        print(x)
    returns  apple
            banana
            cherry
		

Note: The for loop does not require an indexing variable to set beforehand.

Even strings are iterable objects, they contain a sequence of characters.

    for x in "banana":
    print(x)
    returns  b
            a
            n
            a
            n
            a
		

The break Statement

With the break statement we can stop the loop before it has looped through all the items.

    fruits = ["apple", "banana", "cherry"]
     for x in fruits:
        if x == "banana":
        break
        print(x)
    returns apple
            banana
		

• Exit the loop when x is "banana", but this time the break comes before the print:

    fruits = ["apple", "banana", "cherry"]
    for x in fruits:
        print(x)
        if x == "banana":
        break
    returns apple
		

The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue with the next.

    fruits = ["apple", "banana", "cherry"]
    for x in fruits:
        if x == "banana":
        continue
        print(x)
    returns apple 
            
		

The range() Function

To loop through a set of code a specified number of times, we can use the range() function.
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

    for x in range(6):
        print(x)
    returns 0
            1
            2
            3
            4
            5 
		

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

• The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6:

    for x in range(2, 6):
        print(x)
    returns 2
            3
            4
            5
		

• The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):

    for x in range(2, 30, 3):
        print(x)
    returns 2
             5
             8
            11
            14
            17
            20
            23
            26
            29
		

Else in For loop

The else keyword in a for loop specifies a block of code to be executed when the loop is finished.

    for x in range(6):
        print(x)
    else:
        print("Finally finished!")
    returns 0
            1
            2
            3
            4
            5
        "Finally finished!"
		

Note: The else block will NOT be executed if the loop is stopped by a break statement.

    for x in range(6):
        if x == 3: break
        print(x)
    else:
        print("Finally finished!")
    returns 0
            1
            2
            3
		

Nested Loops

A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop".

    adj = ["red", "big", "tasty"]
    fruits = ["apple", "banana", "cherry"]

    for x in adj:
        for y in fruits:
        print(x, y)
    returns red apple
            red banana
            red cherry
            big apple
            big banana
            big cherry
            tasty apple
            tasty banana
            tasty cherry
		

The Pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.

    for x in [0, 1, 2]:
        pass   # having an empty for loop like this, would raise an error without the pass statement
		

Loop Lists

Loop Through a List

You can loop through the list items by using a class="python_highlight">for loop.

    thislist = ["apple", "banana", "cherry"]
     for x in thislist:
        print(x)
    returns apple
            banana
            cherry
		

Loop Through the Index Numbers

You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.

    thislist = ["apple", "banana", "cherry"]
    for i in range(len(thislist)):
        print(thislist[i])
    returns apple
            banana
            cherry
		

Using a While Loop

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.
Remember to increase the index by 1 after each iteration.

    thislist = ["apple", "banana", "cherry"]
    i = 0
    while i < len(thislist):
        print(thislist[i])
        i = i + 1
    returns apple
            banana
            cherry
		

Looping Using List Comprehension

List Comprehension offers the shortest syntax for looping through lists.

    thislist = ["apple", "banana", "cherry"]
    [print(x)  for x in thislist]
    returns apple
            banana
            cherry
		

Loop Tuples

Loop Through a Tuple

You can loop through the tuple items by using a class="python_highlight">for loop.

    thistuple = ("apple", "banana", "cherry")
    for x in thistuple:
        print(x)
    returns apple
            banana
            cherry
		

Loop Through the Index Numbers

You can also loop through the tuple items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.

    thistuple = ("apple", "banana", "cherry")
    for i in range(len(thistuple)):
        print(thistuple[i])
    returns apple
            banana
            cherry
		

Using a While Loop

You can loop through the tuple items by using a while loop. Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by referring to their indexes.
Remember to increase the index by 1 after each iteration.

    thistuple = ("apple", "banana", "cherry")
    i = 0
    while i < len(thistuple):
        print(thistuple[i])
        i = i + 1
    returns apple
            banana
            cherry
		

Loop Dictionaries

Loop Through a Dictionary

You can loop through a dictionary by using a class="python_highlight">for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
• Print all key names in the dictionary, one by one:

    thisdict = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    for x in thisdict:
        print(x)
    returns brand
            model
            year
		

• Print all values in the dictionary, one by one:

    thisdict = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    for x in thisdict:
        print(thisdict[x])
    returns Ford
            Mustang
            1964
		

• You can also use the keys() method to return values of a dictionary:

    thisdict = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    for x in thisdict.keys():
        print(x)
    returns brand
            model
            year
		

• You can also use the values() method to return values of a dictionary:

    thisdict = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    for x in thisdict.values():
        print(x)
    returns Ford
            Mustang
            1964
		

• Loop through both keys and values, by using the items() method:

    thisdict = {
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    for x,y in thisdict.items():
        print(x, y)
    returns brand Ford
            model Mustang
            year 1964
		

Loop Through Nested Dictionaries

You can loop through a dictionary by using the items() method.
Loop through the keys and values of all nested dictionaries:

    myfamily = {
        "child1" : {
            "name" : "Emil",
            "year" : 2004
        },
        "child2" : {
            "name" : "Tobias",
            "year" : 2007
        },
        "child3" : {
            "name" : "Linus",
            "year" : 2011
        }
    }

    for x, obj in myfamily.items():
        print(x)
        
        for y in obj:
            print(y + ':', obj[y])
    returns child1
            name: Emil
            year: 2004
            child2
            name: Tobias
            year: 2007
            child3
            name: Linus
            year: 2011
		

Loop Sets

Loop Through a Set

You can loop through the set items by using a for loop.

    thisset = {"apple", "banana", "cherry"}
    for x in thisset:
        print(x)
    returns apple
            banana
            cherry
        

13. Functions

Definition

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

	def my_function():
	print("Hello from a function") 
        

Calling a Function

To call a function, use the function name followed by parenthesis.

    def my_function():
        print("Hello from a function") 
    my_function()
    returns "Hello from a function" 
        

Arguments

Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

    def my_function(fname):
        print(fname + " Refsnes")

    my_function("Emil")
    my_function("Tobias")
    my_function("Linus")
    returns Emil Refsnes
            Tobias Refsnes
            Linus Refsnes
        

Note: Arguments are often shortened to args

Parameters or Arguments

The terms parameter and argument can be used for the same thing: information that are passed into a function.
• A parameter is the variable listed inside the parentheses in the function definition. e.g. def my_function(fname, lname):
• An argument is the value that is sent to the function when it is called.

Number of Arguments

By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less. • This function expects 2 arguments, and gets 2 arguments:

    def my_function(fname, lname):
        print(fname + " " + lname)

    my_function("Emil", "Refsnes")
    returns Emil Refsnes  
        

If you try to call the function with 1 or 3 arguments, you will get an error.
• This function expects 2 arguments, but gets only 1:

    def my_function(fname, lname):
        print(fname + " " + lname)
    my_function("Emil")
    returns TypeError: my_function() missing 1 required positional argument: 'lname' 
        

Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly:

    def my_function(fname):
        print("The youngest child is " + kids[2])
    my_function("Emil", "Tobias", "Linus")
    returns "The youngest child is Linus" 
        

Note: Arguments are often shortened to args

Keyword Arguments

You can also send arguments with the key = value syntax. This way the order of the arguments does not matter.

    def my_function(child3, child2, child1):
        print("The youngest child is " + child3)
    my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
    returns "The youngest child is Linus" 
        

Note: Keyword arguments are often shortened to kwargs

Arbitrary Keyword Arguments, *kwargs

If you do not know how many arguments that will be passed into your function, add a ** before the parameter name in the function definition. This way the function will receive a dictionary of arguments, and can access the items accordingly:

    def my_function(**kid):
        print("His last name is " + kid["lname"])
    my_function(fname = "Tobias", lname = "Refsnes")
    returns "His last name is Refsnes" 
        

Note: Keyword arguments are often shortened to kwargs

Default Parameter Value

The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:

    def my_function(country = "Norway"):
        print("I am from " + country)
    my_function("Sweden")
    my_function("India")
    my_function()
    my_function("Brazil")
    returns "I am from Sweden"
            "I am from India"
            "I am from Norway"
            "I am from Brazil"
        

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function

    def my_function(food):
    for x in food:
        print(x)
    fruits = ["apple", "banana", "cherry"]
    my_function(fruits)
    returns apple
            banana
            cherry
        

Return Values

To let a function return a value, use the return statement

    def my_function(x):
        return 5 * x
    print(my_function(3))
    print(my_function(5))
    print(my_function(9))
    returns 15
            25
            45
        

The pass Statement

function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.

    def my_function():
        pass 
        

Positional-Only Arguments vs Keyword-Only Arguments

• Positional arguments are arguments that need to be included in the proper position or order. The first positional argument always needs to be listed first when the function is called. The second positional argument needs to be listed second and the third positional argument listed third, etc.

    def nameAge(name, age):
        print("Hi, I am", name)
        print("My age is ", age)
        
    nameAge("Prince", 20)
    returns Hi, I am Prince 
            My age is 20
        

• Keyword arguments are arguments passed to a function or method which is preceded by a keyword and an equals sign.

    def nameAge(name, age):
        print("Hi, I am", name)
        print("My age is ", age)

    nameAge(name="Prince", age=20)
    returns Hi, I am Prince
            My age is 20 
        

Difference between the Keyword and Positional Argument

Positional-Only Argument Keyword-Only Argument
Arguments are passed in the order of parameters. The order defined in the order function declaration. Parameter Names are used to pass the argument during the function call.
Order of values cannot be changed to avoid the unexpected output. Order of parameter Names can be changed to pass the argument(or values).
Syntax :-FunctionName(value1,value2,value3,….) Syntax :–FunctionName(paramName=value,…)

Positional-Only Arguments

You can specify that a function can have ONLY positional arguments, or ONLY keyword arguments.
To specify that a function can have only positional arguments, add , / after the arguments:

    def my_function(x, /):
        print(x)
    my_function(3)
        

• Without the , / you are actually allowed to use keyword arguments even if the function expects positional arguments:

    def my_function(x):
        print(x)
    my_function(x = 3)
        

• But when adding the , / you will get an error if you try to send a keyword argument:

    def my_function(x, /):
        print(x)
    my_function(x = 3)
    returns TypeError: my_function() got some positional-only arguments passed as keyword arguments: 'x' 
        

Keyword-Only Arguments

To specify that a function can have only keyword arguments, add *, before the arguments:

def my_function(*, x): print(x) my_function(x =3)

• Without the * you are actually allowed to use keyword arguments even if the function expects positional arguments:

    def my_function(x):
        print(x)
    my_function(3)
        

• But when adding the * you will get an error if you try to send a keyword argument:

    def my_function(*, x):
        print(x)
    my_function(3)
    returns TypeError: my_function() takes 0 positional arguments but 1 was given 
        

Combine Positional-Only and Keyword-Only

You can combine the two argument types in the same function.
Any argument before the / , , are positional-only, and any argument after the *, are keyword-only.

    def my_function(a, b, /, *, c, d):
        print(a + b + c + d)
    my_function(5, 6, c = 7, d = 8)
    returns 26
        

Recursion

Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

    def tri_recursion(k):
        if(k > 0):
            result = k + tri_recursion(k - 1)
            print(result)
        else:
            result = 0
            return result

    print("Recursion Example Results:")
    tri_recursion(6)

    returns Recursion Example Results:  1
                                        3
                                        6
                                       10
                                       15
                                       21
        

In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

Lambda Function

Definition

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

Syntax

lambda arguments : expression

The expression is executed and the result is returned:

    x = lambda a : a + 10
    print(x(5))
    returns 15
        

Lambda functions can take any number of arguments.

• Multiply argument a with argument b and return the result:

    x = lambda a, b : a * b
    print(x(5, 6))
    returns 30
        

• Summarize argument a, b, and c and return the result:

    x = lambda a, b, c : a + b + c
    print(x(5, 6, 2))
    returns 13
        

Why Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous function inside another function.

• Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:

    def myfunc(n):
        return lambda a : a * n 
        

a) Use that function definition to make a function that always doubles the number you send in:

    def myfunc(n):
        return lambda a : a * n
    mydoubler = myfunc(2)

    print(mydoubler(11))
    returns 22
        

b) Or, use the same function definition to make a function that always triples the number you send in:

    def myfunc(n):
        return lambda a : a * n
    mydoubler = myfunc(3)

    print(mydoubler(11))
    returns 33
        

c) Or, use the same function definition to make both functions, in the same program:

    def myfunc(n):
        return lambda a : a * n
    mydoubler = myfunc(2)
    mytripler = myfunc(3)

    print(mydoubler(11))
    print(mytripler(11))
    returns 22
            33
        

Use lambda functions when an anonymous function is required for a short period of time.

Python Scope

A variable is only available from inside the region it is created. This is called scope.

Local Scope

A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.

    def myfunc():
        x = 300
        print(x)
    myfunc()
    returns 300
        

Function Inside Function

As explained in the example above, the variable x is not available outside the function, but it is available for any function inside the function:

    def myfunc():
        x = 300
        def myinnerfunc():
            print(x)
        myinnerfunc()
    
    myfunc()
    returns 300
        

Global Scope

A variable created in the main body of the Python code is a global variable and belongs to the global scope.
Global variables are available from within any scope, global and local.

    x = 300
    def myfunc():
        print(x)

    myfunc()
    print(x)
    returns 300
            300
        

Naming Variables

If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function):

    x = 300
    def myfunc():
            x = 200
        print(x)

    myfunc()
    print(x)
    returns 200
            300
        

Global Keyword

If you need to create a global variable, but are stuck in the local scope, you can use the global keyword. The global keyword makes the variable global.

    def myfunc():
        global x
        x = 300

    myfunc()
    print(x)
    returns 300
        

• Also, use the global keyword if you want to make a change to a global variable inside a function.

    x = 300
    def myfunc():
        global x
        x = 200

    myfunc()
    print(x)
    returns 200
        

Nonlocal Keyword

The nonlocal keyword is used to work with variables inside nested functions.
The nonlocal keyword makes the variable belong to the outer function.

    def myfunc1():
        x = "Jane"
        def myfunc2():
            nonlocal x
            x = "hello"
        myfunc2()
        return x
    
    print(myfunc1())
    returns "hello"
        

14. Error Handling (Try..Except)

Definition

Error handling is a critical aspect of programming, and it involves detecting and resolving errors that occur during program execution. Errors detected during execution are called exceptions.

Keywords

In Python to handle errors there are keywords that can be used to indentify and "catch" these errors:
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The else block lets you execute code when there is no error.
• The finally block lets you execute code, regardless of the result of the try- and except blocks.

Exception Handling

Try...Except

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
These exceptions can be handled using the try statement.
• The try block will generate an exception, because x is not defined:

    try:
        print(x)
    except:
        print("An exception occurred")
    returns "An exception occurred"
        

Since the try block raises an error, the except block will be executed. Without the try..except block, the program will crash and raise an error:

    print(x)
    returns NameError: name 'x' is not defined
        

Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error.

    try:
        print(x)
    except NameError:
        print("Variable x is not defined")
    except:
        print("Something else went wrong")
    returns "Variable x is not defined"
        

else

You can use the else keyword to define a block of code to be executed if no errors were raised.

    try:
        print("Hello")
    except:
        print("Something went wrong")
    else:
        print("Nothing went wrong")
    returns "Hello"
            "Nothing went wrong"
        

finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

    try:
        print(x)
    except:
        print("Something went wrong")
    finally:
        print("The 'try except' is finished")
    returns "Something went wrong"
            "The 'try except' is finished"
        

This can be useful to close objects and clean up resources.

    try:
        f = open("demofile.txt")
        try:
            f.write("Lorum Ipsum")
        except:
            print("Something went wrong when writing to the file")
        finally:
            f.close()
    except:
        print("Something went wrong when opening the file")
    returns "Something went wrong when opening the file"
        

The program can continue, without leaving the file object open.

Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.
To throw (or raise) an exception, use the raise keyword.

• Raise an error and stop the program if x is lower than 0:

    x = -1
    if x < 0:
        raise Exception("Sorry, no numbers below zero")
    returns "Sorry, no numbers below zero"
        

The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.

• Raise a TypeError if x is not an integer:

    x = "hello"
        if not type(x) is int:
            raise TypeError("Only integers are allowed")
    returns "Only integers are allowed"
        

Built-in Exceptions

Exception Description Error Code
ArithmeticError Raised when an error occurs in numeric calculations {{ error.2 {}
AssertionError Raised when an assert statement fails {{ error.2 {}
AttributeError Raised when attribute reference or assignment fails {{ error.2 {}
Exception Base class for all exceptions {{ error.2 {}
EOFError Raised when the input() method hits an 'end of file' condition (EOF) {{ error.2 {}
FileNotFoundError {{ error.2 {}
FloatingPointError Raised when a floating point calculation fails {{ error.2 {}
GeneratorExit Raised when a generator is closed (with the close() method) {{ error.2 {}
ImportError Raised when an imported module does not exist {{ error.2 {}
IndentationError Raised when indentation is not correct {{ error.2 {}
IndexError Raised when an index of a sequence does not exist {{ error.2 {}
KeyError Raised when a key does not exist in a dictionary {{ error.2 {}
KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete {{ error.2 {}
LookupError Raised when errors raised cant be found {{ error.2 {}
MemoryError Raised when a program runs out of memory {{ error.2 {}
ModuleNotFoundError Raised when a module could not be found {{ error.2 {}
NameError Raised when a variable does not exist {{ error.2 {}
NotImplementedError Raised when an abstract method requires an inherited class to override the method {{ error.2 {}
OSError Raised when a system related operation causes an error {{ error.2 {}
OverflowError Raised when the result of a numeric calculation is too large {{ error.2 {}
PermissionError {{ error.2 {}
RecursionError {{ error.2 {}
ReferenceError Raised when a weak reference object does not exist {{ error.2 {}
RuntimeError Raised when an error occurs that do not belong to any specific exceptions {{ error.2 {}
StopIteration Raised when the next() method of an iterator has no further values {{ error.2 {}
SyntaxError Raised when a syntax error occurs {{ error.2 {}
SystemError Raised when a system error occurs {{ error.2 {}
SystemExit Raised when the sys.exit() function is called {{ error.2 {}
TabError Raised when indentation consists of tabs or spaces {{ error.2 {}
TypeError Raised when two different types are combined {{ error.2 {}
UnboundLocalError Raised when a local variable is referenced before assignment {{ error.2 {}
UnicodeError Raised when a unicode problem occurs {{ error.2 {}
UnicodeEncodeError Raised when a unicode encoding problem occurs {{ error.2 {}
UnicodeDecodeError Raised when a unicode decoding problem occurs {{ error.2 {}
UnicodeTranslateError Raised when a unicode translation problem occurs {{ error.2 {}
ValueError Raised when there is a wrong value in a specified data type {{ error.2 {}
ZeroDivisionError Raised when the second operator in a division is zero {{ error.2 {}

15. User Input

Definition

In Python we can ask the user for input. The input() function allows user input.

    username = input("Enter username:")
    print("Username is: " + username)
        

Or we can use string format:

    username = input("Enter username:")
    print(f"Username is: {username}")
        

Python stops executing when it comes to the input() function, and continues when the user has given some input.

16. Classes and Objects

Definition

Python is an object-oriented programming language. Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class.

    class MyClass:
        x = 5
        

Create Object

Now we can use the class named MyClass to create objects.

    p1 = MyClass()
    print(p1.x)
    returns 5
        

The __init__() Function

The examples above are classes and objects in their simplest form, and are not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in _init__() function.
All classes have a function called _init__(), which is always executed when the class is being initiated.

Use the _init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

    class Person:
        def __init__(self, name, age):
        self.name = name
        self.age = age

    p1 = Person("John", 36)

    print(p1.name)
    print(p1.age)
    returns "John"
            "36" 
        

Note: The _init__() function is called automatically every time the class is being used to create a new object.

The __str__() Function

The __str__() function controls what should be returned when the class object is represented as a string.
If the __str__() function is not set, the string representation of the object is returned. • The string representation of an object WITHOUT the __str__() function:

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age

    p1 = Person("John", 36)

    print(p1)
    returns "__main__.Person object at 0x15039e602100" 
        

• The string representation of an object WITH the __str__() function:

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def __str__(self):
            return f"{self.name}({self.age})"
    
    p1 = Person("John", 36)
    print(p1)
    returns "John(36)" 
        

Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the object.

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def myfunc(self):
            print ("Hello my name is " + self.name)"
    
    p1 = Person("John", 36)
    p1.myfunc()

    returns "Hello my name is John" 
        

Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.

The self Parameter

The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
It does not have to be named self, you can call it whatever you like, but it has to be the first parameter of any function in the class

    class Person:
	    def __init__(mysillyobject, name, age):
            mysillyobject.name = name
		    mysillyobject.age = age

	    def myfunc(abc):
		    print ("Hello my name is " + abc.name)"
    
    p1 = Person("John", 36)
    p1.myfunc()

    returns "Hello my name is John" 
	    

Modify Object Properties

You can modify properties on objects like this:

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def myfunc(self):
            print ("Hello my name is " + self.name)"
        
    p1 = Person("John", 36)
    p1.age = 40
    print(p1.age)

    returns 40
        

Delete Object Properties

You can delete properties on objects by using the del keyword:

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def myfunc(self):
            print("Hello my name is " + self.name)"
        
    p1 = Person("John", 36)
    del p1.age
    print(p1.age)

    returns AttributeError: 'Person' object has no attribute 'age'
        

The pass Statement

class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.

    class Person:
        pass
        

Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.

Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class.

    class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

    #Use the Person class to create an object, and then execute the printname method:
    x = Person("John", "Doe")
    x.printname()
    returns John Doe
        

Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class.
Create a class named Student, which will inherit the properties and methods from the Person class:

    class Student(Person):
        pass 
        

Note: Use the pass keyword when you do not want to add any other properties or methods to the class.

Now the Student class has the same properties and methods as the Person class.

    class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname) 

    class Student(Person):
        pass

    x = Student("Mike", "Olsen")
    x.printname()
    returns John Doe
        

Add the __init__() Function

So far we have created a child class that inherits the properties and methods from its parent.
We want to add the __init__() function to the child class (instead of the pass keyword).

Note: The __init__() function is called automatically every time the class is being used to create a new object.

    class Student(Person):
        def __init__(self, fname, lname):
            self.firstname = fname
            self.lastname = lname
        

When you add the __init__() function, the child class will no longer inherit the parent's __init__() function.

Note: The __init__() function overrides the inheritance of the parent's __init__() function.

• To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function:

    class Student(Person):
        def __init__(self, fname, lname):
            Person.__init__(self, fname, lname)
        

The complete code would look lik this:

    class Person:
        def __init__(self, fname, lname):
            self.firstname = fname
            self.lastname = lname

        def printname(self):
            print(self.firstname, self.lastname) 

    class Student(Person):
        def __init__(self, fname, lname):
            Person.__init__(self, fname, lname)

    x = Student("Mike", "Olsen")
    x.printname()
    returns Mike Olsen
        

• Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in __init__() function.

Use the super() Function

Python also has a super() function that will make the child class inherit all the methods and properties from its parent:

    class Person:
        def __init__(self, fname, lname):
            self.firstname = fname
            self.lastname = lname

        def printname(self):
            print(self.firstname, self.lastname) 

    class Student(Person):
        def __init__(self, fname, lname):
            super().__init__(fname, lname)

    x = Student("Mike", "Olsen")
    x.printname()
    returns Mike Olsen
        

By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.

Add Properties

Add a property called graduationyear to the Student class:

    class Person:
        def __init__(self, fname, lname):
            self.firstname = fname
            self.lastname = lname

        def printname(self):
            print(self.firstname, self.lastname) 

    class Student(Person):
        def __init__(self, fname, lname):
            super().__init__(fname, lname)
            graduationyear = 2019

        x = Student("Mike", "Olsen")
        print(x.graduationyear)
        returns 2019
        

• In the example below, the year 2019 should be a variable, and passed into the Student class when creating student objects. To do so, add another parameter in the __init__ function.

    class Person:
        def __init__(self, fname, lname):
            self.firstname = fname
            self.lastname = lname

        def printname(self):
            print(self.firstname, self.lastname) 

    class Student(Person):
        def __init__(self, fname, lname, year):
            super().__init__(fname, lname)
            self.graduationyear = year

        x = Student("Mike", "Olsen", 2019)
        print(x.graduationyear)
        returns 2019
        

Add Methods

Add a method called welcome to the Student class:

    class Person:
        def __init__(self, fname, lname):
            self.firstname = fname
            self.lastname = lname

        def printname(self):
            print(self.firstname, self.lastname) 

    class Student(Person):
        def __init__(self, fname, lname, year):
            super().__init__(fname, lname)
            self.graduationyear = year
        
        def welcome(self):
            print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
        
    x = Student("Mike", "Olsen", 2024)
    x.welcome
    returns "Welcome Mike Olsen to the class of 2024"
        

Note: If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.

Iterators

Definition

An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().

Iterator vs Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.
All these objects have a iter() method which is used to get an iterator:

    mytuple = ("apple", "banana", "cherry")
    myit = iter(mytuple)

    print(next(myit))
    print(next(myit))
    print(next(myit))
    returns apple
            banana
            cherry
        

• Even strings are iterable objects, and can return an iterator:

    mystr = "banana"
    myit = iter(mystr)

    print(next(myit))
    print(next(myit))
    print(next(myit))
    print(next(myit))
    print(next(myit))
    print(next(myit))

    returns b
            a
            n
            a
            n
            a
        

Looping Through an Iterator

• We can also use a for loop to iterate through an iterable object:

    mytuple = ("apple", "banana", "cherry")
    for x in mytuple:
        print(x)
    returns apple
            banana
            cherry
        

• Iterate the characters of a string:

    mystr = "banana"
    for x in mystr:
        print(x)
    returns b
            a
            n
            a
            n
            a
        

The for loop actually creates an iterator object and executes the next() method for each loop.

Create an Iterator

To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object.
As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), which allows you to do some initializing when the object is being created.
The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.
The __next__() method also allows you to do operations, and must return the next item in the sequence.

    class MyNumbers:
        def __iter__(self):
            self.a = 1
            return self

            def __next__(self):
                x = self.a
                self.a += 1
                return x

        myclass = MyNumbers()
        myiter = iter myclass

        print(next(myiter))
        print(next(myiter))
        print(next(myiter))
        print(next(myiter))
        print(next(myiter))
        returns 1
                2
                3
                4
                5
        

Stop Iteration

The example above would continue forever if you had enough next() statements, or if it was used in a for loop.

    class MyNumbers:
        def __iter__(self):
            self.a = 1
            return self

            def __next__(self):
                x = self.a
                self.a += 1
                return x

        myclass = MyNumbers()
        myiter = iter myclass

        for x in myiter:
            print(x)
        

To prevent the iteration from going on forever, we can use the StopIteration statement.

    class MyNumbers:
        def __iter__(self):
            self.a = 1
            return self

        def __next__(self):
            if self.a <= 20:
                x = self.a
                self.a += 1
                return x
            else:
                raise StopIteration

    myclass = MyNumbers()
    myiter = iter myclass

    for x in myiter:
        print(x)
        returns  1
                 2
                 3
                 4
                 5
                 6
                 7
                 8
                 9
                10
                11
                12
                13
                14
                15
                16
                17
                18
                19
                20
        

Polymorphism

Definition

The word "polymorphism" means "many forms", and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or classes.

Function Polymorphism

An example of a Python function that can be used on different objects is the len() function.

String

For strings len() returns the number of characters:

    x = "Hello World!"
    print(len(x))
    returns 12
        

Tuple

For tuples len() returns he number of items in the tuple:

    mytuple = ("apple", "banana", "cherry")
    print(len(mytuple))
    returns 3
        

Dictionary

For dictionaries len() returns the number of key/value pairs in the dictionary:

    thisdict =	{
        "brand": "Ford",
        "model": "Mustang",
        "year": 1964
    }
    print(len(thisdict))
    returns 3
        

Class Polymorphism

Polymorphism is often used in Class methods, where we can have multiple classes with the same method name.
For example, say we have three classes: Car, Boat and Plane, and they all have a method called move():

    class Car:
        def __init__(self, brand, model):
            self.brand = brand
            self.model = model
        
        def move(self):
            print("Drive")

    class Boat:
        def __init__(self, brand, model):
            self.brand = brand
            self.model = model
        
        def move(self):
            print("Sail!")

    class Plane:
        def __init__(self, brand, model):
            self.brand = brand
            self.model = model
        
        def move(self):
            print("Fly!")

    car1 = Car("Ford", "Mustang")       #Create a Car class
    boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
    plane1 = Plane("Boeing", "747")     #Create a Plane class

    for x in (car1, boat1, plane1):
        x.move
    
    returns Drive!
            Sail!
            Fly!
        

• Look at the for loop at the end. Because of polymorphism we can execute the same method for all three classes.

Inheritance Class Polymorphism

What about classes with child classes with the same name? Can we use polymorphism there?
Yes. If we use the example above and make a parent class called Vehicle, and make Car, Boat, Plane child classes of Vehicle, the child classes inherits the Vehicle methods, but can override them:

    class Vehicle:
        def __init__(self, brand, model):
            self.brand = brand
            self.model = model
    
        def move(self):
            print("Move")

    class Car(Vehicle):
        pass

    class Boat(Vehicle):
        def move(self):
            print("Sail!")

    class Plane(Vehicle):
        def move(self):
            print("Fly!")

    car1 = Car("Ford", "Mustang")       #Create a Car class
    boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
    plane1 = Plane("Boeing", "747")     #Create a Plane class

    for x in (car1, boat1, plane1):
        print(x.brand)
        print(x.model)
        x.move()
    
    returns Ford
            Mustang
            Move!
            Ibiza
            Touring 20
            Sail!
            Boeing
            747
            Fly!
        

Child classes inherits the properties and methods from the parent class.

In the example above you can see that the Car class is empty, but it inherits brand, model, and move() from Vehicle.
The Boat and Plane classes also inherit brand, model, and move() from Vehicle, but they both override the move() method.
Because of polymorphism we can execute the same method for all classes.

17. Python Modules

Definition

A file containing a set of functions you want to include in your application.
Consider a module to be the same as a code library.

Create a Module

To create a module just save the code you want in a file with the file extension .py

Save this code in a file named mymodule.py

        def greeting(name):
            print("Hello, " + name)
        

Use a Module

Now we can use the module we just created, by using the import statement.

    import mymodule
    mymodule.greeting("Jonathan")
    returns Hello, Jonathan
        

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc.).

Save this code in the file mymodule.py

    person1 = {
        "name": "John",
        "age": 36,
        "country": "Norway"
    }
        

Import the module named mymodule, and access the person1 dictionary:

    import mymodule

    a = mymodule.person1["age"]
    print(a)
    returns 36
        

Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using the as keyword.

Create an alias for mymodule.py called mx:

    import mymodule as mx

    a = mx.person1["age"]
    print(a)
    returns 36
        

Import From Module

You can choose to import only parts from a module, by using the from keyword.

• The module named mymodule has one function and one dictionary:

    def greeting(name):
        print("Hello, " + name)
        
    person1 = {
        "name": "John",
        "age": 36,
        "country": "Norway"
    }
        

Import only the person1 dictionary from the module:

    from mymodule import person1

    print(person1["age"])
    returns 36
        

Note: When importing using the from keyword, do not use the module name when referring to elements in the module. eg. person1["age"], not mymodule.person1["age"]

Python Package Manager

In Python to install software we use a manager called PIP (an acronym of “pip Install Packages”)

What is PIP?

PIP is a package manager for Python packages, or modules. (built-in with Python 3.4 or later)

What is a Package?

A package contains all the files you need for a module.

Install PIP

Navigate your command line to the location of Python's script directory, and type the following:
pip --version

If you do not have PIP installed, you can download and install it from this page: https://pypi.org/project/pip/

Download a Package

Downloading a package is very easy.
Navigate your command line to the location of Python's script directory, and type the following: pip install camelcase

Using a Package

Once the package is installed, it is ready to use. Import the "camelcase" package into your project.

    import camelcase

    c = camelcase.CamelCase()
    txt = "lorem ipsum dolor sit amet"
    print(c.hump(txt))
    returns Lorem Ipsum Dolor Sit Amet
        

Remove a Package

Use the uninstall command to remove a package:
pip uninstall camelcase

The PIP Package Manager will ask you to confirm that you want to remove the camelcase package, press y (yes) and the package will be removed.

List Packages

Use the list command to list all the packages installed on your system:
pip list

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like. The Python standard library contains well over 200 modules.
Here are the most commonly used modules:

Numeric and Mathematical Module>

Name Definition Usage
Mathematical tasks import math
Mathematical tasks for complex numbers import cmath
Make random numbers import random

Data Types>

Name Definition Usage
To work with dates as date objects import datetime
To display calendars import calendar

Text Processing>

Name Definition Usage
A powerful toolkit that simplifies working with strings import strings
for regular expressions (RegEx) import re

Operating Systems>

Name Definition Usage
Provides functions for interacting with the Operating System import os
Retrieve information about the platform the program is running on import platform

MS Windows Specific Services>

Name Definition Usage
Functions and constants for reading, writing, and deleting registry keys/values import winreg
Access to the basic sound-playing machinery on Windows import winsound

Python Runtime Services>

Name Definition Usage
Manipulate parts of the Python runtime environment (PRE) import sys

Importing Modules>

Name Definition Usage
Allows for loading modules dynamically import importlib

Concurrent Execution>

Name Definition Usage
Spawn processes, connect to their pipes, and get return codes import subprocess
High-level interface for asynchronously executing callables import concurrent.futures

Database>

Name Definition Usage
Integrate the SQLite database with Python import sqlite3

Cryptographic Services>

Name Definition Usage
Implements secure cryptographic hash and message digest algorithms import hashlib
Generate secure random numbers for sensitive data import secrets

Networking and Interprocess Communication>

Name Definition Usage
Access the BSD socket interface import socket
TLS/SSL encryption and peer authentication for sockets import ssl

Internet Related Services>

Name Definition Usage
High-level interface to open web pages import webbrowser
Library for managing email messages import email
Send emails via SMTP import smtplib
Access emails via IMAP import imaplib
Client-side FTP protocol import ftplib
Work with IPv4/IPv6 addresses and networks import ipaddress
Utilities to manipulate HTML import html
JSON encoder and decoder import json

Graphical User Interfaces>

Name Definition Usage
Build basic GUI applications import tkinter

Numeric and Mathematical Modules

Math Module

Python has also a built-in module called math , which extends the list of mathematical functions.
To use it, you must import the math module:

    import math
        

When you have imported the math module, you can start using methods and constants of the module.
• The math.sqrt() method for example, returns the square root of a number:

    import math

    x = math.sqrt(64)
    print(x)
    returns 8
        

• The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer, and returns the result:

    import math

    x = math.ceil (1.4)
    y = math.floor (1.4)

    print(x)
    print(y)
    returns 2
            1
        

• The math.pi constant, returns the value of PI (3.14...):

    import math
    x = math.pi
    print(x)
    returns 3.141592653589793
        

Random Module

This module can be used to perform random actions such as generating random numbers, printing a random value for a list or string, etc.

    import random

    number = random.randint(1, 10)
    print(number)
    # returns a random number between 1 and 10, including 1 & 10
        

The random module has a set of methods:

Random Methods

Method Description
seed() Initialize the random number generator
getstate() Returns the current internal state of the random number generator
setstate() Restores the internal state of the random number generator
getrandbits() Returns a number representing the random bits
randrange() Returns a random number between the given range
randint() Returns a random number between the given range
choice() Returns a random element from the given sequence
choices() Returns a list with a random selection from the given sequence
shuffle() Takes a sequence and returns the sequence in a random order
sample() Returns a given sample of a sequence
random() Returns a random float number between 0 and 1
uniform() Returns a random float number between two given parameters
triangular() Returns a random float number between two given parameters, you can also set a mode parameter to specify the midpoint between the two other parameters
betavariate() Returns a random float number between 0 and 1 based on the Beta distribution (used in statistics)
expovariate() Returns a random float number based on the Exponential distribution (used in statistics)
gammavariate() Returns a random float number based on the Gamma distribution (used in statistics)
gauss() Returns a random float number based on the Gaussian distribution (used in probability theories)
lognormvariate() Returns a random float number based on a log-normal distribution (used in probability theories)
normalvariate() Returns a random float number based on the normal distribution (used in probability theories)
vonmisesvariate() Returns a random float number based on the von Mises distribution (used in directional statistics)
paretovariate() Returns a random float number based on the Pareto distribution (used in probability theories)
weibullvariate() Returns a random float number based on the Weibull distribution (used in statistics)

Data Types

DateTime Module

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.

    import datetime

    x = datetime.datetime.now()
    print(x)
    returns 2024-11-28 13:48:08.616653 
        

Date Output

In the example above the date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Here are a few examples:

        import datetime

        x = datetime.datetime.now()
        print(x.year)
        print(x.strftime("%A"))
        returns 2024
                Thursday
            

Creating Date Objects

To create a date, we can use the datetime() class (constructor) of the datetime module.
The datetime() class requires three parameters to create a date: year, month, day.

    import datetime

    x = datetime.datetime(2020, 5, 17)
    print(x)
    returns 2020-05-17 00:00:00
        

The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone).

The strftime() Method

The datetime() object has a method for formatting date objects into readable strings.
The method is called strftime(), and takes one parameter, format, to specify the format of the returned string.

    import datetime

    x = datetime.datetime(2018, 6, 1)
    print(x.strftime("%B"))
    returns june
        
strftime Formats
Directive Description Usage Output
%a Weekday, short version print(x.strftime('%a')) Wed
%A Weekday, full version print(x.strftime('%A')) Wednesday
%w Weekday as a number 0-6, 0 is Sunday print(x.strftime('%w')) 3
%d Day of month 01-31 print(x.strftime('%d')) 31
%b Month name, short version print(x.strftime('%b')) Dec
%B Month name, full version print(x.strftime('%B')) December
%m Month as a number 01-12 print(x.strftime('%m')) 12
%y Year, short version, without century print(x.strftime('%y')) 18
%Y Year, full version print(x.strftime('%Y')) 2018
%H Hour 00-23 print(x.strftime('%H')) 17
%I Hour 00-12 print(x.strftime('%I')) 05
%p AM/PM print(x.strftime('%p')) PM
%M Minute 00-59 print(x.strftime('%M')) 41
%S Second 00-59 print(x.strftime('%S')) 08
%f Microsecond 000000-999999 print(x.strftime('%f')) 548513
%z UTC offset print(x.strftime('%z')) +0100
%Z Timezone print(x.strftime('%Z')) CST
%j Day number of year 001-366 print(x.strftime('%j')) 365
%U Week number of year, Sunday as the first day of week, 00-53 print(x.strftime('%U')) 52
%W Week number of year, Monday as the first day of week, 00-53 print(x.strftime('%W')) 52
%c Local version of date and time print(x.strftime('%c')) Mon Dec 31 17:41:00 2018
%C Century print(x.strftime('%C')) 20
%x Local version of date print(x.strftime('%x')) 12/31/18
%X Local version of time print(x.strftime('%X')) 17:41:00
%% A % character print(x.strftime('%%')) %
%G ISO 8601 year print(x.strftime('%G')) 2018
%u ISO 8601 weekday (1-7) print(x.strftime('%u')) 1
%V ISO 8601 weeknumber (01-53) print(x.strftime('%V')) 01

Calendar Module

The calendar module is used to display calendars and provides useful Built-in functions for displaying week, week day, month, month of the year, and other operations.
By default, these calendars have Monday as the first day of the week, and Sunday as the last.

Calendar Methods

• Display the Year of a Calendar:

    import calendar

    year = 2024
    print(calendar.calendar(year))
        

• Display the Month of a Calendar:

    import calendar

    print(calendar.month(2024,11))
        

• Get the Weekday number:

    import calendar

    print(f'Monday Weekday Number: {calendar.MONDAY}')
    print(f'Tuesday Weekday Number: {calendar.TUESDAY}')
    print(f'Wednesday Weekday Number: {calendar.WEDNESDAY}')
    print(f'Thursday Weekday Number: {calendar.THURSDAY}')
    print(f'Friday Weekday Number: {calendar.FRIDAY}')
    print(f'Saturday Weekday Number: {calendar.SATURDAY}')
    print(f'Sunday Weekday Number: {calendar.SUNDAY}')

    returns Monday Weekday Number: 0
            Tuesday Weekday Number: 1
            Wednesday Weekday Number: 2
            Thursday Weekday Number: 3
            Friday Weekday Number: 4
            Saturday Weekday Number: 5
            Sunday Weekday Number: 6
        

• Check if an Year is a Leap Year:

    import calendar

    print(calendar.isleap(2020))
    print(calendar.isleap(2021))
    print(calendar.isleap(2022))
    print(calendar.isleap(2023))
    print(calendar.isleap(2024))
    print(calendar.isleap(2025))

    returns True
            False
            False
            False
            True
            False
        

Calendar Formats

The calendar() module also have a few formats.

Calendar Methods

Method Description
iterweekdays() Returns an iterator for the weekday numbers that will be used for one week
itermonthdates() Returns an iterator for the month (1–12) in the year
itermonthdays() Returns an iterator of a specified month and a year
itermonthdays2() This method is used to get an iterator for the month in the year similar to itermonthdates(). Days returned will be tuples consisting of a day of the month number and a week day number.
itermonthdays3() Returns an iterator for the month in the year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month and a day of the month numbers.
itermonthdays4() Returns an iterator for the month in the year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month, a day of the month, and a day of the week numbers.
monthdatescalendar() Used to get a list of the weeks in the month of the year as full weeks
monthdays2calendar() Used to get a list of the weeks in the month of the year as full weeks
monthdayscalendar Used to get a list of the weeks in the month of the year as full weeks
yeardatescalendar() Used to get a list of the weeks in the month of the year as full weeks
yeardays2calendar() Used to get the data for specified year. Entries in the week lists are tuples of day numbers and weekday numbers
yeardayscalendar() Used to get the data for specified year. Entries in the week lists are day numbers

• Text-Based Calendars:
To generate plain text calendars, the calendar module provides calendar.TextCalendar with methods to format and print monthly and yearly calendars.
TextCalendar.formatyear() accepts a single parameter for the year:

    import calendar

    text_calendar = calendar.TextCalendar()
    print(text_calendar.formatyear(2024))
    returns 
                            2024

        January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
1  2  3  4  5  6  7                1  2  3  4                   1  2  3
8  9 10 11 12 13 14       5  6  7  8  9 10 11       4  5  6  7  8  9 10
15 16 17 18 19 20 21      12 13 14 15 16 17 18      11 12 13 14 15 16 17
22 23 24 25 26 27 28      19 20 21 22 23 24 25      18 19 20 21 22 23 24
29 30 31                  26 27 28 29               25 26 27 28 29 30 31

        April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
1  2  3  4  5  6  7             1  2  3  4  5                      1  2
8  9 10 11 12 13 14       6  7  8  9 10 11 12       3  4  5  6  7  8  9
15 16 17 18 19 20 21      13 14 15 16 17 18 19      10 11 12 13 14 15 16
22 23 24 25 26 27 28      20 21 22 23 24 25 26      17 18 19 20 21 22 23
29 30                     27 28 29 30 31            24 25 26 27 28 29 30

        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
1  2  3  4  5  6  7                1  2  3  4                         1
8  9 10 11 12 13 14       5  6  7  8  9 10 11       2  3  4  5  6  7  8
15 16 17 18 19 20 21      12 13 14 15 16 17 18       9 10 11 12 13 14 15
22 23 24 25 26 27 28      19 20 21 22 23 24 25      16 17 18 19 20 21 22
29 30 31                  26 27 28 29 30 31         23 24 25 26 27 28 29
                                                    30

        October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
1  2  3  4  5  6                   1  2  3                         1
7  8  9 10 11 12 13       4  5  6  7  8  9 10       2  3  4  5  6  7  8
14 15 16 17 18 19 20      11 12 13 14 15 16 17       9 10 11 12 13 14 15
21 22 23 24 25 26 27      18 19 20 21 22 23 24      16 17 18 19 20 21 22
28 29 30 31               25 26 27 28 29 30         23 24 25 26 27 28 29
                                                    30 31
        

Text-Based Calendar Methods

Method Description
formatmonth() This method is used to get the month’s calendar in a multi-line string
prmonth() The function also prints the month of a specific year but there is no need of 'print' operation to execute this
formatyear() This method is used to get m-column calendar for an entire year as a multi-line string
pryear() This method is used to print the calendar for an entire year as returned by formatmonth()
setfirstweekday() This method sets the day start number of the week
sfirstweekday() This method returns the first weekday number. By default 0 (Monday)
sisleap() This method checks if the year mentioned in the argument is leap or not
sleapdays() This method returns the number of leap days between the specified years in arguments
sweekday() This method returns the weekday number(0 is Monday) of the date specified in its arguments
sweekheader() Returns a header containing abbreviated weekday names
smonthrange() The function returns two integers, first, the starting day number of the week(0 as monday), second, the number of days in the month
smonthcalendar() Returns a matrix representing a month’s calendar. Each row represents a week; days outside of the month are represented by zeros
month() The function prints the month of a specific year mentioned in arguments
prcal() The function also prints the calendar of a specific year but there is no need of “print” operation to execute this
calendar() The function displays the calendar for the given year.

• HTMLCalendar:
to create a calendar for a website, the calendar module can also output calendars in HTML with calendar.HTMLCalendar with methods to format and print monthly and yearly calendars.

    import calendar

    html_calendar = calendar.HTMLCalendar()
    print(html_calendar.formatyear(2024))
    returns the code to build an HTML Table which would look like this:

    
2024
January
MonTueWedThuFriSatSun
1234567
891011121314
15161718192021
22232425262728
293031    
February
MonTueWedThuFriSatSun
   1234
567891011
12131415161718
19202122232425
26272829   
March
MonTueWedThuFriSatSun
    123
45678910
11121314151617
18192021222324
25262728293031
April
MonTueWedThuFriSatSun
1234567
891011121314
15161718192021
22232425262728
2930     
May
MonTueWedThuFriSatSun
  12345
6789101112
13141516171819
20212223242526
2728293031  
June
MonTueWedThuFriSatSun
     12
3456789
10111213141516
17181920212223
24252627282930
July
MonTueWedThuFriSatSun
1234567
891011121314
15161718192021
22232425262728
293031    
August
MonTueWedThuFriSatSun
   1234
567891011
12131415161718
19202122232425
262728293031 
September
MonTueWedThuFriSatSun
      1
2345678
9101112131415
16171819202122
23242526272829
30      
October
MonTueWedThuFriSatSun
 123456
78910111213
14151617181920
21222324252627
28293031   
November
MonTueWedThuFriSatSun
    123
45678910
11121314151617
18192021222324
252627282930 
December
MonTueWedThuFriSatSun
      1
2345678
9101112131415
16171819202122
23242526272829
3031     

HTML Calendar Methods

Method Description
formatmonth() This method is used to get the month’s calendar as an HTML table
formatyear() This method is used to get a year’s calendar as an HTML table.
formatyearpage() This method is used to get the year’s calendar as a complete HTML page

Text Processing

Strings Module

Strings module is specifically designed for common string operations. It provides constants representing commonly used sets of characters (like lowercase and uppercase letters, digits, and punctuation) as well as utility functions like capwords() for manipulating strings.

Strings Constants

Constant Description Usage Output
ascii_letters The ascii_letters is a concatenation of all ASCII lowercase and uppercase letters print(string.ascii_letters) abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
ascii_lowercase The ascii_lowercase contains all ASCII lowercase letters print(string.ascii_lowercase) abcdefghijklmnopqrstuvwxyz
ascii_uppercase The ascii_uppercase contains all ASCII uppercase letters print(string.ascii_uppercase) ABCDEFGHIJKLMNOPQRSTUVWXYZ
digits The digits contains all decimal digits from 0 to 9 print(string.digits) 0123456789
hexdigits The hexdigits contains all characters used in hexadecimal numbers (0-9 and A-F) print(string.hexdigits) 0123456789abcdefABCDEF
octdigits The octdigits contains all characters used in octal numbers (0-7) print(string.octdigits) 01234567
punctuation The punctuation contains all characters used in octal numbers (0-7) print(string.punctuation) !#$%&'()*+,-./:;<=>?@[\]^_`{|}~
printable The printable contains all characters that are printable, including digits, letters, punctuation, and whitespace print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'()*+,-./:;<=>?@[\]^_`{|}~
whitespace The whitespace contains all characters that are considered whitespace (spaces, tabs, newlines, etc.) print(string.whitespace)

Whitespace Validation

We can use whitespace to check if a string contains only whitespace characters:

    import string

    def is_only_whitespace(s):
        return all(char in string.whitespace for char in s)

    print(is_only_whitespace("   \t\n"))
    returns TRUE
        

String Module Functions

Apart from constants, the string module provides several useful functions for string manipulation.

→ The capwords() The capwords() function capitalizes the first letter of every word in a string and lowers the rest of the letters. It also replaces multiple spaces between words with a single space.

    import string

    text = "hello, coder! this is your codeforcoders!"
    print(string.capwords(text))
    returns Hello, Coder! This Is Your Codeforcoders!
        

We can use capwords() to format user input or generate titles for articles, books, etc.

→ The formatter() provides an extensible way to create custom string formatting. It works behind the scenes in Python’s str.format() method but can be customized to fit our needs.

    from string import formatter

    print(formatter.format("Hello, {}!", "coder"))
    returns Hello, coder!
        

If we need special formatting rules beyond what str.format() provides, we can use Formatter() to define our own logic. → The Template() class allows us to create string templates where placeholders can be replaced by values. It's useful for situations where we need simple string substitution.

    from string import Template
    
    text = Template("Hello, $name!")
    print(text.substitute(name="coder"))
    returns Hello, coder!
        

⇉ The Template() class also offers safe substitution (safe_substitute) which will not raise an exception if a placeholder is missing:

    from string import Template
    
    text = Template("Hello, $name!")
    print(text.safe_substitute(name="Python"))
    print(text.safe_substitute())

    returns Hello, Python
            Hello, $name
        

We can use Template() for creating email templates where placeholders like $name or $date are replaced with actual values.

RegEx Module

A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. RegEx can be used to check if a string contains the specified search pattern.

    import re

    txt = "The rain in Spain"
    x = re.search("^The.*Spain$", txt)

    if x:
        print("YES! We have a match!")
    else:
        print("No match")
    
    returns YES! We have a match!
        

The re module offers a set of functions that allows us to search a string for a match.

RegEx Functions

Function Description
findall Returns a list containing all matches
fsearch Returns a Match object if there is a match anywhere in the string
split Returns a list where the string has been split at each match
fsub Replaces one or many matches with a string

Metacharacters

Metacharacters are characters with a special meaning:

Character Description Example Usage
[] A set of characters '[a-m]' x = re.findall('[a-m]', txt)
\ Signals a special sequence (can also be used to escape special characters) '\d' x = re.findall('\d', txt)
. Any character (except newline character) 'he..o' x = re.findall('he..o', txt)
^ Starts with '^hello' x = re.findall('^hello', txt)
$ Ends with 'planet$' x = re.findall('planet$', txt)
* Zero or more occurrences 'he.*o' x = re.findall('he.*o', txt)
+ One or more occurrences 'he.+o' x = re.findall('he.+o', txt'), print(x)
? Zero or one occurrences 'he.?o' x = re.findall('he.?o', txt), print(x)
{} Exactly the specified number of occurrences 'he.{2}o' x = re.findall('he.{2}o', txt)
| Either or 'falls|stays' x = re.findall('falls|stays', txt)
() Capture and group string = 'John Doe, 25 years old', pattern = r'(\w+) (\w+), (\d+) years old', x = re.findall(pattern, string)

Special Sequences

A special sequence is a \ followed by one of the characters in the list below, and has a special meaning:

Character Description Example Usage
\A Returns a match if the specified characters are at the beginning of the string '\AThe' x = re.findall('\AThe', txt)
 Returns a match where the specified characters are at the beginning or at the end of a word r'ain' x = re.findall(r'ain', txt)
(the 'r' in the beginning is making sure that the string is being treated as a 'raw string') r'ain' x = re.findall(r'ain', txt)
\B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word r'\Bain' x = re.findall(r'\Bain', txt)
(the 'r' in the beginning is making sure that the string is being treated as a 'raw string') r'ain\B' x = re.findall(r'ain\B', txt)
\d Returns a match where the string contains digits (numbers from 0-9) '\d' x = re.findall('\d', txt)
\D Returns a match where the string DOES NOT contain digits '\D' x = re.findall('\D', txt)
\s Returns a match where the string contains a white space character '\s' x = re.findall('\s', txt)
\S Returns a match where the string DOES NOT contain a white space character '\S' x = re.findall('\S', txt)
\w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) '\w' x = re.findall('\w', txt)
\W Returns a match where the string DOES NOT contain any word characters '\W' x = re.findall('\W', txt)
\Z Returns a match if the specified characters are at the end of the string 'Spain\Z' x = re.findall('Spain\Z', txt)

Sets

A set is a set of characters inside a pair of square brackets [] with a special meaning:

Character Description Usage
[arn] Returns a match where one of the specified characters (a, r, or n) is present x = re.findall('[arn]', txt)
[a-n] Returns a match for any lower case character, alphabetically between a and n x = re.findall('[a-n]', txt)
[^arn] Returns a match for any character EXCEPT a, r, and n x = re.findall('[^arn]', txt)
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present x = re.findall('[0123]', txt)
[0-9] Returns a match for any digit between 0 and 9 x = re.findall('[0-9]', txt)
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59 x = re.findall('[0-5][0-9]', txt)
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case x = re.findall('[a-zA-Z]', txt)
[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in the string x = re.findall('[+]', txt)

The findall() Function

The findall() function returns a list containing all matches.

    import re

    txt = "The rain in Spain"
    x = re.findall("ai", txt)


    print(x)
    returns ['ai', 'ai']
        

The list contains the matches in the order they are found.
If no matches are found, an empty list is returned:

    import re

    txt = "The rain in Spain"
    x = re.findall("Portugal", txt)

    print(x)
    returns []
        

The search() Function

The search() searches the string for a match, and returns a Match object if there is a match.
If there is more than one match, only the first occurrence of the match will be returned:

    import re

    txt = "The rain in Spain"
    x = re.search("\s", txt)

    print("The first white-space character is located in position:", x.start())
    returns The first white-space character is located in position: 3
        

If no matches are found, the value None is returned:

    import re

    txt = "The rain in Spain"
    x = re.search("Portugal", txt)

    print(x)
    returns None
        

The split() Function

The split() function returns a list where the string has been split at each match:

    import re

    txt = "The rain in Spain"
    x = re.split("\s", txt)

    print(x)
    returns ['The', 'rain', 'in', 'Spain']
        

You can control the number of occurrences by specifying the maxsplit parameter:

    import re

    txt = "The rain in Spain"
    x = re.split("\s", txt, 1) #Split the string at the first white-space character

    print(x)
    returns ['The', 'rain in Spain']
        

The sub() Function

The sub() function replaces the matches with the text of your choice:

    import re

    txt = "The rain in Spain"
    x = re.sub("\s", "9", txt)

    print(x)
    returns The9rain9in9Spain
        

You can control the number of replacements by specifying the count parameter:

    import re

    txt = "The rain in Spain"
    x = re.sub("\s", "9", txt, 2)

    print(x)
    returns The9rain9in Spain
        

Match Object

A Match Object is an object containing information about the search and the result.
Note:If there is no match, the value None will be returned, instead of the Match Object.

You can control the number of replacements by specifying the count parameter:

    import re

    txt = "The rain in Spain"
    x = re.search("ai", txt)

    print(x) #this will print an object
    returns sre.SRE_Match object; span=(5, 7), match='ai'
        

The Match object has properties and methods used to retrieve information about the search, and the result:
.span() returns a tuple containing the start-, and end positions of the match.

    import re

    txt = "The rain in Spain"
    x = re.search(r"\bS\w+", txt)

    print(x.span())
    returns (12, 17)
        

.string returns the string passed into the function.

    import re

    txt = "The rain in Spain"
    x = re.search(r"\bS\w+", txt)

    print(x.string)
    returns The rain in Spain
        

.group() returns the part of the string where there was a match.

    import re

    txt = "The rain in Spain"
    x = re.search(r"\bS\w+", txt)

    print(x.group())
    returns Spain
        

Note: If there is no match, the value None will be returned, instead of the Match Object.

Operating Systems

OS Module

Python has a built-in os module with methods for interacting with the operating system, like creating files and directories, management of files and directories, input, output, environment variables, process management, etc.
The os module has the following set of methods and constants.

OS Methods

Method Description
os._exit() Exits the process with the specified status
os.abort() Terminates a running process immediately
os.access() Uses the real uid/gid to check access to a path
os.add_dll_directory() Adds a path to the DLL search path
os.chdir() Change the current working directory
os.chflags() Sets the flags of path to the numeric flags
os.chmod() Changes the mode of path to the numeric mode
os.chown() Changes the owner and group id of a specified path to the specified numeric owner id and group id
os.chroot() Changes the root directory of the current process to a specified path
os.close() Closes the specified file descriptor
os.closerange() Closes all file descriptors from fd_low to fd_high
os.confstr() Returns string-valued system configuration values
os.cpu_count() Returns the number of CPUs present in the system
os.ctermid() Returns the filename associated with the controlling terminal of the process
os.device_encoding() Returns the encoding of the device associated with the file descriptor, if it is connected to a terminal
os.dup() Duplicates a file descriptor
os.dup2() Duplicates a file descriptor to a given value
os.fchdir() Changes the current working directory to a directory opened by ['os.open()'
os.fchmod() Changes the mode of a file to the specified numeric mode
os.fchown() Changes the owner and group id of a file to the numeric uid and gid
os.fdatasync() Forces write of file to disc - not forces update of metadata
os.fdopen() Returns an open file object connected to a file
os.fork() Forks a child process
os.forkpty() Forks a child process, using a new pseudo-terminal as the child's controlling terminal
os.fpathconf() Returns system configuration information relevant to an open file
os.fsdecode() Decodes a file path
os.fsencode() Encodes a file path
os.fspath() Returns the file system representation of a path
os.fstat() Returns the status of a file
os.fstatvfs() Returns information about the file system of a file
os.fsync() Forces write of file with file descriptor fd to disk
os.ftruncate() Truncates a file to a specified length
os.fwalk()
os.get_blocking() Returns the blocking mode information of the file descriptor
os.get_exec_path() Returns a list of directories, in which the system looks for named executable programs
os.get_handle_inheritable()
os.get_inheritable() Returns the inheritable flag of the file descriptor
os.get_terminal_size() Returns the size of a terminal as a pair of columns and lines
os.getcwd() Returns the current working directory
os.getcwdb() Returns the current working directory in bytestring
os.getegid() Return the effective group id of the current process
os.getenv() Returns the value of the environment variable key
os.getenvb() Returns the value of the environment variable key, in bytes
os.geteuid() Returns the effective user id of the current process
os.getgid() Returns the real group id of the current process
os.getgrouplist() Returns a list of all group ids for a specified user
os.getgroups() Returns a list of supplementary group ids associated with the current process
os.getloadavg() Returns the load average over the last 1, 5, and 15 minutes
os.getlogin() Returns the name of the user logged in to the terminal
os.getpgid() Returns the process group id of a specific process id
os.getpgrp() Returns the current process group id
os.getpid() Returns the process id of the current process
os.getppid() Returns the parent process id of the current process
os.getpriority() Returns the scheduling priority of a process, process group, or user
os.getresgid() Returns the current process' real, effective, and saved group ids
os.getresuid() Returns the current process' real, effective, and saved user ids
os.getsid() Returns the session id of a process
os.getuid() Returns the current process' real user id
os.initgroups() Initializes a group access list showing all the member groups of a user plus the group id
os.isatty() Returns whether a file descriptor is open and connected to a tty(-like) device or not.
os.kill() Sends a signal to the process with the specified process id
os.killpg() Sends a signal to the process with the specified process id
os.lchflags() Changes the flags of a path to the numeric flags
os.lchmod() Changes the mode of path to the numeric mode
os.lchown() Changes the owner and group id of path to the numeric uid and gid
os.link() Creates a hard link pointing to source named destination
os.listdir() Returns a list of the names of the entries in a directory
os.lockf() Applies, tests, or removes a POSIX lock on an open file
os.lseek() Sets the current position of file descriptor to the defined position
os.lstat() Returns the status of a file or file descriptor, but does not follow symbolic links
os.major() Returns the device major number from raw device number
os.makedev() Returns a raw device number from the specified major and minor device numbers
os.makedirs() Creates a directory recursively
os.memfd_create() Create an anonymous file and returns a file descriptor
os.minor() Returns the device minor number from raw device number
os.mkdir() Creates a directory (with a specified mode)
os.mkfifo() Creates a FIFO named path (with a specified mode)
os.mknod() Creates a filesystem node, such as file, device special file and named pipe with the given path.
os.nice() Increment the process's niceness by specified value
os.open() Opens the specified file and returns a corresponding file descriptor
os.openpty() Open a new pseudo-terminal pair
os.pathconf() Returns system configuration information relevant to a named file
os.pipe() Ceates a pipe for inter-process communication
os.pipe2() To pass information from one process to another process
os.plock() Lock program segments into memory
os.popen() Provides a way to run shell commands using Python code
os.posix_fadvise() To announce an intention to access file data in a specific pattern in the future
os.posix_fallocate() Ensures that disk space is allocated for the file referred to by the file descriptor
os.posix_spawn() Create a new child process that executes a specified file
os.posix_spawnp()
os.pread() Read at most n bytes from the file associated with the given file descriptor at a position of given offset value
os.preadv() Read data from a file descriptor into multiple vectors
os.putenv() Set the environment variable named key to the string value
os.pwrite() Write the specified bytestring to the file associated with the specified file descriptor at the specified position
os.pwritev() Write the contents of specified buffers to the specified file descriptor
os.read() Read a specified number of bytes from a file associated with the given file descriptor
os.readlink() Takes the path of a symbolic link as its argument and returns the path to which the symbolic link points
os.readv() Read data from a file indicated by the specified file descriptor into a number of specified buffers
os.register_at_fork()
os.remove() Rmove or delete a file path
os.removedirs() Rmove directories recursively
os.removexattr() Removes an extended attribute associated with the given file system object path
os.rename() Renames a source file or directory to a specified destination file or directory
os.renames() A recursive directory or file renaming function
os.replace() Rename the file or directory
os.rmdir() Remove or delete an empty directory
os.scandir() Get an iterator of os.DirEntry objects corresponding to the entries in the directory given by the specified path
os.sched_get_priority_max() Get the maximum priority value for the specified scheduling policy
os.sched_get_priority_min() Get the minimum priority value for the specified scheduling policy
os.sched_getaffinity() Get the set of CPUs on which the process with the specified process id is eligible to run
os.sched_getparam() Return the scheduling parameters of a process specified by process id
os.sched_getscheduler() Return the scheduling policy of the process specified by process id
os.sched_rr_get_interval() Get the Round Robin quantum in seconds for the process indicated by the specified process
os.sched_setaffinity() Set the CPU affinity mask of a process indicated by the specified process id
os.sched_setparam() Set the scheduling parameters of a process specified by process id
os.sched_setscheduler() Sets both the scheduling policy and the associated parameters for the process identified by process id
os.sched_yield() Causes the calling thread to relinquish the CPU
os.sendfile() Copy specified number of bytes from specified source file descriptor to specified dest file descriptor
os.set_blocking() Set the blocking mode of the specified file descriptor
os.set_handle_inheritable() Set the “inheritable” flag of the specified handle
os.set_inheritable() Set the value of inheritable flag of the specified file descriptor
os.setegid() Set the effective group id of the current process
os.seteuid() Set the effective user id of the current process
os.setgid() Set the real group id of the current process
os.setgroups() Set the list of supplementary group ids associated with the current process
os.setpgid() Set the process group id of a specific process id
os.setpriority() Set the scheduling priority of a process, process group, or user
os.setregid() Set the current process's real and effective group ids
os.setresgid() Set the current process' real, effective, and saved group ids
os.setresuid() Set the current process' real, effective, and saved user ids
os.setreuid() Set the current process' real user id
os.setsid() Set the session id of a process
os.setuid() Set the current process' real user id
os.setxattr() Set the extended filesystem attribute attribute on path to value
os.spawnl() Execute file with arguments from args in a subprocess
os.spawnle() Execute file with arguments from args in a subprocess with the supplied environment
os.spawnlp() Execute file (which is looked for along PATH) with arguments from args in a subprocess
os.spawnlpe() Execute file (which is looked for along PATH) with arguments from args in a subprocess with the supplied environment
os.spawnv() Execute file with arguments from args in a subprocess
os.spawnve() Execute file with arguments from args in a subprocess with the specified environment
os.spawnvp() Execute file (which is looked for along PATH) with arguments from args in a subprocess
os.spawnvpe() Execute file (which is looked for along PATH) with arguments from args in a subprocess with the supplied environment
os.startfile() 'start' a file with its associated program
os.stat() Get the status of the specified path
os.statvfs() Get the information about the mounted file system containing the given path
os.strerror() Returns a string representing the error message corresponding to the specified error code
os.symlink() Create a symbolic link that points to the given source
os.sync() Force write of everything to disk
os.sysconf() Get integer-valued system configuration values
os.system() Executes a specified command in a subshell
os.tcgetpgrp() Get the process group ID associated with the terminal represented by a given file descriptor
os.tcsetpgrp() Sets the process group ID associated with the terminal represented by a given file descriptor to an integer value
os.times() Get the current global process times
os.truncate() Ttruncates the file corresponding to the path so that it is at the most length bytes in size
os.ttyname() Get the terminal device associated with the specified file descriptor
os.umask() Set the current numeric umask value and get the previous umask value
os.uname() Retrieves information identifying the operating system you are running on
os.unlink() Remove or delete a file path
os.unsetenv() Deletes an environment variable from the environment of the calling process
os.urandom() Generates a string containing random characters
os.utime() Set the access and modification times of the file specified by path
os.wait() Used by a process to wait for completion of a child process
os.wait3() Used by a process to wait for completion of any child process
os.wait4() Used by a process to wait for completion of a specific child process
os.waitid() Used by a process to wait for completion of one or more child processes
os.waitpid() Suspends execution of the current process until a child specified by process id argument has changed state
os.walk() Generate the file names in a directory tree by walking the tree either top-down or bottom-up
os.write() Write a bytestring to the given file descriptor
os.writev() Write the contents of specified buffers to the specified file descriptor

OS Objects

Object Description
os.altsep An alternative character used by the operating system to separate pathname components
os.confstr_names Returns a dictionary of the names and integer values that is accepted as parameter for the os.confstr() method
os.curdir Return a relative filepath to path either from the current directory or from an optional start directory
os.defpath The default search path used by exec*p*() and spawn*p*() if the environment doesn't have a 'PATH' key
os.devnull Return the platform-specific file path of the device
os.environ A mapping object that represents the user's OS environmental variables
os.environb A mapping object where both keys and values are bytes objects representing the process environment
os.extsep The character which separates the base filename from the extension
os.linesep The string used to separate (or, rather, terminate) lines on the current platform
os.name Find the name of the current OS
os.pardir a constant string used by the operating system to refer to the parent directory
os.pathconf_names Returns system configuration information relevant to a named file
os.pathsep The character conventionally used by the operating system to separate search path components
os.sep The character used by the operating system to separate pathname components
os.supports_bytes_environ Used to check whether the native OS type of the environment is bytes or not
os.supports_dir_fd Indicates which methods in the OS module permit the use of their dir_fd parameter
os.supports_effective_ids Indicating whether os.access() permits specifying True for its effective_ids parameter on the local platform
os.supports_fd Check if a particular method permits specifying their path parameter as an open file descriptor or not
os.supports_follow_symlinks Indicates which methods in the OS module permit the use of their follow_symlinks parameter
os.sysconf_names A dictionary mapping of names accepted as parameter by os.sysconf() method to the integer values defined for those names by the host operating system

OS Constants

Object Description
os.CLD_CONTINUED
os.CLD_DUMPED
os.CLD_EXITED
os.CLD_TRAPPED
os.EX_CANTCREAT Exit code that indicates: User specified output file could not be created
os.EX_CONFIG Exit code that indicates: Some kind of configuration error occurred
os.EX_DATAERR Exit code that indicates: Input data was incorrect
os.EX_IOERR Exit code that indicates: An error occurred while doing input/output on some file
os.EX_NOHOST Exit code that indicates: The host did not exist
os.EX_NOINPUT Exit code that indicates: The input file did not exist or was not readable
os.EX_NOPERM Exit code that indicates: Insufficient permissions to perform the operation
os.EX_NOTFOUND Exit code that indicates: Entry not found
os.EX_NOUSER Exit code that indicates: The user does not exists
os.EX_OK Exit code that indicates: No error occurred
os.EX_OSERR Exit code that indicates: An operating system error was detected
os.EX_OSFILE Exit code that indicates: Error in a system file
os.EX_PROTOCOL Exit code that indicates: Protocol exchange was illegal, invalid, or not understood
os.EX_SOFTWARE Exit code that indicates: An internal software produced an error
os.EX_TEMPFAIL Exit code that indicates: A temporary failure occurred
os.EX_UNAVAILABLE Exit code that indicates: A required service is unavailable
os.EX_USAGE Exit code that indicates: The command was used incorrectly
os.F_LOCK
os.F_OK Tests the existence of the path
os.F_TEST
os.F_TLOCK
os.F_ULOCK
os.GRND_NONBLOCK
os.GRND_RANDOM
os.MFD_ALLOW_SEALING
os.MFD_CLOEXEC
os.MFD_HUGETLB
os.MFD_HUGE_16GB
os.MFD_HUGE_16MB
os.MFD_HUGE_1GB
os.MFD_HUGE_1MB
os.MFD_HUGE_256MB
os.MFD_HUGE_2GB
os.MFD_HUGE_2MB
os.MFD_HUGE_32MB
os.MFD_HUGE_512KB
os.MFD_HUGE_512MB
os.MFD_HUGE_64KB
os.MFD_HUGE_8MB
os.MFD_HUGE_MASK
os.MFD_HUGE_SHIFT
os.O_APPEND
os.O_ASYNC
os.O_BINARY
os.O_CLOEXEC
os.O_CREAT
os.O_DIRECT
os.O_DIRECTORY
os.O_DSYNC
os.O_EXCL
os.O_EXLOCK
os.O_NDELAY
os.O_NOATIME
os.O_NOCTTY
os.O_NOFOLLOW
os.O_NOINHERIT
os.O_NONBLOCK
os.O_PATH
os.O_RANDOM
os.O_RDONLY
os.O_RDWR
os.O_RSYNC
os.O_SEQUENTIAL
os.O_SHLOCK
os.O_SHORT_LIVED
os.O_SYNC
os.O_TEMPORARY
os.O_TEXT
os.O_TMPFILE
os.O_TRUNC
os.O_WRONLY
os.POSIX_FADV_DONTNEED
os.POSIX_FADV_NOREUSE
os.POSIX_FADV_NORMAL
os.POSIX_FADV_RANDOM
os.POSIX_FADV_SEQUENTIAL
os.POSIX_FADV_WILLNEED
os.PRIO_PGRP
os.PRIO_PROCESS
os.PRIO_USER
os.P_ALL
os.P_DETACH
os.P_NOWAIT
os.P_NOWAITO
os.P_OVERLAY
os.P_PGID
os.P_PID
os.P_WAIT
os.RTLD_DEEPBIND
os.RTLD_GLOBAL
os.RTLD_LAZY
os.RTLD_LOCAL
os.RTLD_NODELETE
os.RTLD_NOLOAD
os.RTLD_NOW
os.RWF_DSYNC
os.RWF_HIPRI
os.RWF_NOWAIT
os.RWF_SYNC
os.R_OK Tests the readability of the path
os.SCHED_BATCH
os.SCHED_FIFO
os.SCHED_IDLE
os.SCHED_OTHER
os.SCHED_RESET_ON_FORK
os.SCHED_RR
os.SCHED_SPORADIC
os.SEEK_CUR
os.SEEK_END
os.SEEK_SET
os.SF_MNOWAIT
os.SF_NODISKIO
os.SF_SYNC
os.WCONTINUED
os.WCOREDUMP(status)
os.WEXITED
os.WEXITSTATUS(status)
os.WIFCONTINUED(status)
os.WIFEXITED(status)
os.WIFSIGNALED(status)
os.WIFSTOPPED(status)
os.WNOHANG
os.WNOWAIT
os.WSTOPPED
os.WSTOPSIG(status)
os.WTERMSIG(status)
os.WUNTRACED
os.W_OK Tests the writability of the path
os.XATTR_CREATE
os.XATTR_REPLACE
os.XATTR_SIZE_MAX
os.X_OK Tests the executability of the path

OS Classes

Object Description
class os.DirEntry Used to get the entry's full path name
class os.PathLike An interface for names of files
class os.sched_param(sched_priority) Represents tunable scheduling parameters used in sched_setparam()
class os.stat_result Object whose attributes correspond roughly to the members of the stat structure
class os.terminal_size A subclass of tuple, holding (columns, lines) of the terminal window size.

Platform Module

The Platform Module is used to retrieve as much possible information about the platform on which the program is being currently executed.
It can be imported using the following syntax:

    import platform
    
    print('Platform processor:', platform.processor())
    returns 'Platform processor:' 'Intel64 family 69 Stepping 1', 'GenuineIntel'
        

Platform Functions

Function Description Usage Output
platform.processor() Returns a string that displays the information about the platform processor, basically the real name of the system’s processor print('Platform processor:', platform.processor()) 'Platform processor:' 'Intel64 family 69 Stepping 1', 'GenuineIntel'
platform.architecture() Returns a tuple that stores information about the bit architecture and linkage format print('Platform architecture:', platform.architecture()) 'Platform architecture:' ('64bit', 'WindowsPE')
platform.machine() Returns a string that displays the machine type, by machine type here it means the information that tells the width or size of registers available in the core print('Machine type:', platform.machine()) 'Machine Type:', 'AMD64'
platform.node() Returns a string that displays the information about the node, basically the system’s network name. print('System's network name:', platform.node()) 'System's network name:', 'dell-PC'
platform.platform() Returns a single string containing as much useful information that is to retrievable about the system print('Platform information:', platform.platform()) 'Platform information:', 'Windows-8-6.2.9200'
platform.system() Returns a string that displays the name of the operation system on the current device being used to run the program print('Operating system:', platform.system()) 'Operating system:', 'Windows'
platform.uname() Returns a tuple that stores information regarding the system. Basically this function can be used to replace the individual functions to retrieve information about the system, node, release, version, machine, version and processor. Thus, a single function serving many purposes print('System info:', platform.uname()) 'System info:', ('Windows', 'dell-PC', '8', '6.2.9200', 'AMD64', 'Intel 64 Family 6 Model 69 Stepping 1', 'GenuineIntel')
platform.python_build() Returns a tuple that stores information about the python build date and build no print('Python build no. and date:', platform.python_build()) 'Python build no. and date:', ('default', 'May 23 2015 09:44:00')
platform.python_compiler() Returns a string that displays the compiler used for compiling the Python programs print('Python compiler:', platform.python_compiler()) 'Python compiler:', 'MSC v.1500 64bit (AMD64)'
platform.python_branch() Returns a string displaying information about the python SCM branch, SCM here stands for Source Code Manager , it is a tool used by programmers to manage source code. SCM is used to track revisions in software print('Python SCM:', platform.python_compiler()) 'Python SCM:', 'MSC v.1500 64bit (AMD64)'
platform.python_implementation() Returns a string that displays information about the python implementation print('Python implementation:', platform.python_implementation()) 'Python implementation:', 'CPython'
platform.python_version() Returns a string that displays the version of Python running currently on the system print('Python version:', platform.python_version()) 'Python version:', '2.7.10'

Python Runtime Services

SYS Module

The SYS Module provides various functions and variables that are used to manipulate different parts of the Python runtime environment.

sys.version returns a string containing the version of Python Interpreter with some additional information.

    import sys
    
    print(sys.version)
    returns 3.6.9 (default, Oct  8 2020, 12:12:24) [GCC 8.4.0]
        

sys.path returns the list of directories that the interpreter will search for the required module.

    import sys
    
    print(sys.path)
    returns ['/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/home/user/PycharmProjects/MyProject/.venv/lib/python3.12/site-packages']
        

sys.module return the name of the Python modules that the current shell has imported.

    import sys
    
    print(sys.module)
    returns {'sys': module 'sys' (built-in)>, 'builtins': module 'builtins' (built-in)>, '_frozen_importlib': module '_frozen_importlib' (frozen)>, '_imp': module '_imp' (built-in)>, 
            '_thread': module '_thread' (built-in)>, '_warnings': module '_warnings' (built-in)>, '_weakref': module '_weakref' (built-in)>, '_io': module '_io' (built-in)>, 'marshal': module 'marshal' (built-in)>, 'posix': module 'posix' (built-in)>, 
            '_frozen_importlib_external': module '_frozen_importlib_external' (frozen)>, 'time': module 'time' (built-in)>, 'zipimport': module 'zipimport' (frozen)>, '_codecs': module '_codecs' (built-in)>, 
            'codecs': module 'codecs' (frozen)>, 'encodings.aliases': module 'encodings.aliases' from '/usr/lib/python3.12/encodings/aliases.py'>, 'encodings': module 'encodings' from '/usr/lib/python3.12/encodings/__init__.py'>, 
            'encodings.utf_8': module 'encodings.utf_8' from '/usr/lib/python3.12/encodings/utf_8.py'>, '_signal': module '_signal' (built-in)>, '_abc': module '_abc' (built-in)>, 'abc': module 'abc' (frozen)>, 
            'io': module 'io' (frozen)>, '__main__': module '__main__' from '/home/reaper/PycharmProjects/Password Manager/test.py'>, '_stat': module '_stat' (built-in)>, 'stat': module 'stat' (frozen)>, 
            '_collections_abc': module '_collections_abc' (frozen)>, 'genericpath': module 'genericpath' (frozen)>, 'posixpath': module 'posixpath' (frozen)>, 'os.path': module 'posixpath' (frozen)>, 
            'os': module 'os' (frozen)>, '_sitebuiltins': module '_sitebuiltins' (frozen)>, '__future__': module '__future__' from '/usr/lib/python3.12/__future__.py'>, 'itertools': module 'itertools' (built-in)>, 
            'keyword': module 'keyword' from '/usr/lib/python3.12/keyword.py'>, '_operator': module '_operator' (built-in)>, 'operator': module 'operator' from '/usr/lib/python3.12/operator.py'>, 
            'reprlib': module 'reprlib' from '/usr/lib/python3.12/reprlib.py'>, '_collections': module '_collections' (built-in)>, 'collections': module 'collections' from '/usr/lib/python3.12/collections/__init__.py'>, 
            'types': module 'types' from '/usr/lib/python3.12/types.py'>, '_functools': module '_functools' (built-in)>, 'functools': module 'functools' from '/usr/lib/python3.12/functools.py'>, 
            'contextlib': module 'contextlib' from '/usr/lib/python3.12/contextlib.py'>, '_virtualenv': module '_virtualenv' from '/home/reaper/PycharmProjects/Password Manager/.venv/lib/python3.12/site-packages/_virtualenv.py'>, 
            'sitecustomize': module 'sitecustomize' from '/usr/lib/python3.12/sitecustomize.py'>, 'site': module 'site' (frozen)>, 'enum': module 'enum' from '/usr/lib/python3.12/enum.py'>, '_sre': module '_sre' (built-in)>, 
            're._constants': module 're._constants' from '/usr/lib/python3.12/re/_constants.py'>, 're._parser': module 're._parser' from '/usr/lib/python3.12/re/_parser.py'>, 're._casefix': module 're._casefix' from '/usr/lib/python3.12/re/_casefix.py'>, 
            're._compiler': module 're._compiler' from '/usr/lib/python3.12/re/_compiler.py'>, 'copyreg': module 'copyreg' from '/usr/lib/python3.12/copyreg.py'>, 're': module 're' from '/usr/lib/python3.12/re/__init__.py'>, 
            'platform': module 'platform' from '/usr/lib/python3.12/platform.py'>, 'errno': module 'errno' (built-in)>, '_locale': module '_locale' (built-in)>, 'locale': module 'locale' from '/usr/lib/python3.12/locale.py'>, 
            'signal': module 'signal' from '/usr/lib/python3.12/signal.py'>, '_weakrefset': module '_weakrefset' from '/usr/lib/python3.12/_weakrefset.py'>, 'threading': module 'threading' from '/usr/lib/python3.12/threading.py'>, 
            'warnings': module 'warnings' from '/usr/lib/python3.12/warnings.py'>, 'fcntl': module 'fcntl' (built-in)>, '_posixsubprocess': module '_posixsubprocess' (built-in)>, 'select': module 'select' (built-in)>, 
            'collections.abc': module 'collections.abc' from '/usr/lib/python3.12/collections/abc.py'>, 'math': module 'math' (built-in)>, 'selectors': module 'selectors' from '/usr/lib/python3.12/selectors.py'>, 
            'subprocess': module 'subprocess' from '/usr/lib/python3.12/subprocess.py'>, '_struct': module '_struct' (built-in)>, 'struct': module 'struct' from '/usr/lib/python3.12/struct.py'>}
        

getrefcount() is used to get the reference count for any given object. This value is used by Python as when this value becomes 0, the memory for that particular value is deleted

    import sys
    
    a = 'Geeks'
    print(sys.getrefcount(a))
    returns 4
        

stdin is used to get input from the command line directly. It is used for standard input. It internally calls the input() method. It, also, automatically adds ‘\n’ after each sentence.

    import sys
    
    for line in sys.stdin:
        if x == line.rstrip():
            break
        print(f'Input : {line}')

    print("Exit")
        

stdout is used to display output directly to the screen console.

    import sys
    
    sys.stdout.write('Coding is awesome')

    returns 'Coding is awesome'
        

• Whenever an exception occurs in Python it is written to stderr.

    import sys
    
    def print_to_stderr(*a):
        print(*a, file = sys.stderr)

    print_to_stderr("Hello World")
        

sys.argv is a Command-line argument which are passed during the calling of the program along with the calling statement.

    import sys
    
    n = len(sys.argv)
    print("Total arguments passed:", n)
    print("\nName of Python script:", sys.argv[0])
    print("\nArguments passed:", end = " ")

    for i in range(1, n):
        print(sys.argv[i], end = " ")
    
    Sum = 0
    for i in range(1, n):
        Sum += int(sys.argv[i])

    print("\n\nResult:", Sum)
        

sys.exit can be used to exit the program.

    import sys

    age = 17
    if age < 18:
        sys.exit("Age less than 18") 
    else:
        print("Age is not less than 18")
        

sys.setrecursionlimit() is used to set the maximum depth of the Python interpreter stack to the required limit, while sys.getrecursionlimit() is used to find the current recursion limit of the interpreter or to find the maximum depth of the Python interpreter stack.

    import sys

    limit = sys.getrecursionlimit()
    print('Before changing, limit of stack =', limit)

    Newlimit = 500
    sys.setrecursionlimit(Newlimit)

    limit = sys.getrecursionlimit() 
    print('After changing, limit of stack =', limit)
    
    returns Before changing, limit of stack = 1000
            After changing, limit of stack = 500
        

sys.settrace() is used for implementing debuggers, profilers and coverage tools.

    from sys import settrace

    def my_tracer(frame, event, arg = None):
        code = frame.f_code
        func_name = code.co_name
        line_no = frame.f_lineno

        print(f"A {event} encountered in \
        {func_name}() at line number {line_no} ")

        return my_tracer

    def fun():
        return "GFG"
    
    def check():
        return fun()

    settrace(my_tracer) 
  
    check() 
    
    returns A call encountered in check() at line number 30 
            A line encountered in check() at line number 31 
            A call encountered in fun() at line number 24 
            A line encountered in fun() at line number 25 
            A return encountered in fun() at line number 25 
            A return encountered in check() at line number 31
        

sys.setswitchinterval() is used to set the interpreter’s thread switch interval (in seconds).

    import sys

    interval = sys.getswitchinterval()
    print('Before changing, switchinterval =', interval)

    interval = 1
    sys.setswitchinterval(interval)

    interval = sys.getswitchinterval() 
    print('After changing, switchinterval =', interval)
    
    returns Before changing, switchinterval = 0.005
            After changing, switchinterval = 1.0
        

sys.maxsize() fetches the largest value a variable of data type Py_ssize_t can store.

    import sys

    max_val = sys.maxsize
    print(max_val)
    
    returns 9223372036854775807
        

sys.getdefaultencoding() is used to get the current default string encoding used by the Unicode implementation.

    import sys

    encoding = sys.getdefaultencoding()
    print(encoding)
    
    returns utf-8
        

Concurrent Execution

SubProcess Module

The subprocess modul is a built-in module that allows us to create new child processes. We can get exit codes, output, and error messages from these child processes. It is a valuable tool for executing external functions or commands in your Python code. Think of it as a way to programmatically interact with your computer using Python instead of manually entering commands in the terminal. This module simplifies the implementation process and seamlessly integrates external programming into your Python workflow.

Uses of Subprocess Module

• Run system commands or external programs from your Python script.
• Handle input, output, and errors caused by child programs in your Python code.
• Capture the output (stdout) and error messages (stderr) generated by these commands.
• Communicate with the running process by sending input (stdin).
• Wait for the command to complete and obtain its return code to check for success or failure.

Subprocess functions

subprocess.Popen is a low-level interface for running subprocesses. Allows you to start a new process and interact with its standard input, output, and error streams. It returns a handle to the running procedure that can be used to wait for the procedure to complete, check its return code, or abort it.
subprocess.run s a high-level wrapper around Popen intended for ease of use. is a more flexible function that allows you to run a command and capture its results in a single call, allowing you to specify options for a command without having to create a Popen object and manage the streams yourself, such as whether to raise or exception if the command fails.

* run() in Windows:

    import subprocess

    result = subprocess.run(["dir"], shell=True, capture_output=True, text=True)
    print(result.stdout)
        

* run() in Linux:

    import subprocess

    result = subprocess.run(["ls"], capture_output=True, text=True)
    print(result.stdout)
        

Note: You should use subprocess.run if you just want to run the command and capture its output and subprocess.Popen if you need more control over the process, such as interacting with its input and output streams. The Popen class takes the same arguments as run(), including args specifying which commands to run and other optional arguments such as stdin, stdout, stderr, shell, cwd, and env

subprocess.check_output is a function that closely resembles subprocess.run. It has the specific behavior of returning only the standard output of the command. However, it differs in how it handles command execution outcomes: if the command’s return code is non-zero, it triggers a CalledProcessError exception. subprocess.check_output function shares the same set of arguments as the subprocess.run function.

    import subprocess

    try:
        ans = subprocess.check_output(["python", "--version"], text=True)
        print(ans)
    except subprocess.CalledProcessError as e:
        print(f"Command failed with return code {e.returncode}")
    
    returns Python 3.7.17
        

subprocess.PIPE can connect the output of one command to the input of another, allowing the output of the first command to be used as input to the second command.

    import subprocess

    lsProcess = subprocess.Popen(["ls"], stdout=subprocess.PIPE, text=True)
    grepProcess = subprocess.Popen(
        ["grep", "sample"], stdin=ls_process.stdout,
        stdout=subprocess.PIPE, text=True)
    output, error = grepProcess.communicate()

    print(output)
    print(error)
        

subprocess.call() is employed to execute a command in a separate process and wait for its completion. The function returns a return code, which is typically zero for success and non-zero for failure.

    import subprocess

    ans = subprocess.call(["python", "--version"])
    if ans == 0:
        print("Command executed.")
    else:
        print("Command failed.", return_code)
        returns Python 3.7.17
                Command executed.
        

Concurrent Module

The concurrent.futures module provides a high-level interface for asynchronously executing callables. The asynchronous execution can be performed with threads, using ThreadPoolExecutor, or separate processes, using ProcessPoolExecutor.

ThreadPoolExecutor Methods

• submit(fn, *args, **kwargs): It runs a callable or a method and returns a Future object representing the execution state of the method.

    from concurrent.futures import ThreadPoolExecutor

    with ThreadPoolExecutor(max_workers=1) as executor:
        future = executor.submit(pow, 323, 1235)
        print(future.result())
        

• map(fn, *iterables, timeout=None, chunksize=1): It maps the method and iterables together immediately and will raise an exception concurrent. futures.TimeoutError if it fails to do so within the timeout limit.

    from concurrent.futures import ThreadPoolExecutor
    from time import sleep

    values = [3,4,5,6]

    def cube(x):
        print(f'Cube of {x}:{x*x*x}')

    if __name__ == '__main__':
        result =[]
        with ThreadPoolExecutor(max_workers=5) as executor:
        executor.submit(cube, 2)
        executor.map(cube,values)

        returns Cube of 2:8
                Cube of 3:27
                Cube of 4:64
                Cube of 5:125
                Cube of 6:216
        

• shutdown(wait=True, *, cancel_futures=False):
* It signals the executor to free up all resources when the futures are done executing.
* It must be called after executor.submit() and executor.map() method else it would throw RuntimeError.
* wait=True makes the method not to return until execution of all threads is done and resources are freed up.
* cancel_futures=True then the executor will cancel all the future threads that are yet to start.

    from concurrent.futures import ThreadPoolExecutor
    from time import sleep

    values = [3,4,5,6]

    def cube(x):
        print(f'Cube of {x}:{x*x*x}')
        sleep(1)

    if __name__ == '__main__':
        executor = ThreadPoolExecutor(max_workers=3)
        executor.submit(cube, 2)
        executor.map(cube,values)

        executor.shutdown(wait=True)
        print("Executor has been shut down.")

        returns Cube of 2:8
                Cube of 3:27
                Cube of 4:64
                Cube of 5:125
                Cube of 6:216
                Executor has been shut down.
        
Note: Since the with block in previous example automatically handles shutdown, there is no need for an explicit shutdown() call.

ProcessPoolExecutor Methods

The ProcessPoolExecutor, like ThreadPoolExecutor, uses submit, map and shutdown fuctions. It also has additional methods:
• cancel(): It Attempts to cancel the call, if the call cannot be canceled then it returns False, else True.
• cancelled(): Returns True if the call is canceled.
• running(): Rreturn True if the process is running and cannot be canceled.
• done(): Returns True if the process has finished executing.
• result(timeout=None): Returns the value which is returned by the process, if the process is still in execution then it waits for the timeout specified else raises a TimeoutError, if None is specified it will wait forever for the process to finish.
• add_done_callback(fn): Attaches a callback function which is called when the process finishes its execution.

Databases

SqLite Module

See the Database section for more details

Graphical User Interface

TKinter Module

See the Graphical User Interface section for more details

Cryptographic Services

Definition

A Cryptographic hash function is a function that takes in input data and produces a statistically unique output, which is unique to that particular set of data. The hash is a fixed-length byte stream used to ensure the integrity of the data

Hashlib Module

The hashlib module implements a common interface for many secure cryptographic hash and message digest algorithms. There is one constructor method named for each type of hash. All return a hash object with the same simple interface. Constructors for hash algorithms are always present in this module.

hashlib.algorithms_guaranteed is a set containing the names of the hash algorithms is guaranteed to be supported by this module on all platforms.

    print(hashlib.algorithms_guaranteed)
    returns {‘sha3_512’, ‘sha1’, ‘sha224’, ‘shake_256’, ‘sha3_384’, ‘sha512’, ‘sha384’, ‘blake2s’, ‘md5’, ‘sha3_224’, ‘sha256’, ‘blake2b’, ‘sha3_256’, ‘shake_128’}       
        

hashlib.algorithms_available is a set containing the names of the hash algorithms available in the running Python interpreter. The same algorithm may appear multiple times in this set under different names (due to OpenSSL).

    print(hashlib.algorithms_available)
    returns {‘sha384’, ‘sha3_224’, ‘whirlpool’, ‘ripemd160’, ‘blake2s’, ‘md5-sha1’, ‘sm3’, ‘sha256’, ‘shake_256’, ‘sha1’, ‘sha3_384’, ‘sha512’, ‘blake2b’, ‘sha512_256’, ‘sha3_256’, ‘shake_128’, ‘sha3_512’, ‘sha224’, ‘md5’, ‘mdc2’, ‘sha512_224’, ‘md4’}       
        

We will use the FIPS secure hash algorithm SHA-256 to obtain the file hash.
Other secure hash algorithms include:
• MD5 (Message Digest 5)
• SHA-512 (Secure Hashing Algorithm 512 bits)
• RC4 (Rivest Cipher 4)

The reason for the usage of SHA-256 is it is one of the most renowned and secure hashing algorithms currently used while offering less time required to compute a hash. The algorithm belongs to the SHA-2 Family, which is succeeded by the SHA-3 family based on sponge construction structure.

Cryptographic Hash

• Obtaining a Cryptographic Hash of a File

    import sys
    import hashlib

    def hashfile(file):
        # A arbitrary (but fixed) buffer size
        # 65536 = 65536 bytes = 64 kilobytes
        BUF_SIZE = 65536

        sha256 = hashlib.sha256()

        with open("test.txt", 'rb') as f:
            while True:
                data = f.read(BUF_SIZE)

                if not:
                    break
                
                sha256.update(data)

        return sha256.hexdigest()

    file_hash = hashfile(sys.argv[1])
    print(f"Hash:{file_hash}")
    returns Hash:7f83b1657fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069
        

• Obtaining a Cryptographic Hash of a String

    import hashlib

    string = b"My name is apple and I am a vegetable?"
    sha256 = hashlib.sha256()
    sha256.update(string)
    string_hash = sha256.hexdigest()

    print(f"Hash:{string_hash}")
    returns Hash:252f8ca07a6fcaae293e5097151c803a7f16504e48c4eb60f651c11341e83217
        

Secrets Module

The secrets module is used for generating random numbers for managing important data such as passwords, account authentication, security tokens, and related secrets, that are cryptographically strong.

Random Numbers

secrets.choice() returns a randomly-chosen element from a non-empty sequence to manage a basic level of security.

    import secrets
    import strings

    alphabet = string.ascii_letters + string.digits 
    password = ''.join(secrets.choice(alphabet) for i in range(10))

    print(password)
    returns 'tmX47l1uo4'
        

Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits.

    import secrets
    import strings

    alphabet = string.ascii_letters + string.digits

    while True:
        password = ''.join(secrets.choice(alphabet) for i in range(10))
        if (any(c.islower() for c in password) and any(c.isupper()
        for c in password) and sum(c.isdigit() for c in password) >= 3):
            print(password)
            break
        
    returns Tx8LppU05Q
        

secrets.randbelow(n) returns a random integer in the range (0, n).

    import secrets
    
    passwd = secrets.randbelow(20)

    print(passwd)
    returns 2
        

secrets.randbits(k) returns an int with k random bits.

    import secrets
    
    passwd = secrets.randbits(7)

    print(passwd)
    returns 61
        

Generating tokens

his module provides several functions for generating secure tokens for applications such as password resets, hard-to-guess URLs etc. • secrets.token_bytes([nbytes=None]) is responsible for generating a random byte string containing nbytes number of bytes. If no value is provided, a reasonable default is used.

    import secrets
    
    token1 = secrets.token_bytes() 
    token2 = secrets.token_bytes(10) 

    print(token1)
    print(token2)
    returns b"\x86?\x85\xcf\x8ek8ud\x8a\x92\x8b>R\xc7\x89_\xc4x\xce'u]\x95\x0c\x05*?HG8\xfb"
            b'Dx\xe8\x7f\xc05\xdf\xe0\xf6\xe1'
    
        

secrets.token_hex([nbytes=None]) is responsible for generating a random text string in hexadecimal containing nbytes random bytes. If no value is provided, a reasonable default is used.

    import secrets
    
    token1 = secrets.token_hex(16) 
    token2 = secrets.token_hex(9) 

    print(token1)
    print(token2)
    returns 5d894a501c88fbe735c6ff496a6d3e51
            78baed9057e597dce4
    
        

secrets.token_urlsafe([nbytes=None]) is responsible for generating a random URL-safe text string containing nbytes random bytes. This is suitable for password recovery applications.

    import secrets
    
    url = 'https://mydomain.com/reset=' + secrets.token_urlsafe()

    print(url)
    returns https://mydomain.com/reset=GbOiFIvhMoqWsfaTQKbj8ydbo8G1lsMx1ECa6SXjb1s
        

Note: At least 32 bytes for tokens should be used to be secure against a brute-force attack.

Networking and Interprocess Communication

Socket Module

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server.
They are the real backbones behind web browsing.

• Connecting to a server:

    import socket
    import sys

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    
        print("Socket successfully created")
    except socket.error as err:
        print("socket creation failed with error %s" %(err))
        
    port = 80

    try:
        host_ip = socket.gethostbyname('www.google.com') 
    except socket.gaierror:
        print("there was an error resolving the host")
        sys.exit()

    s.connect((host_ip, port))
    print("the socket has successfully connected to google")
        

A simple server-client program:

• Server:

A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listening mode. This allows the server to listen to incoming connections. And last a server has an accept() and close() method. The accept method initiates a connection with the client and the close method closes the connection with the client.

    import socket

    s = socket.socket()   
    print("Socket successfully created")
        
    port = 12345

    s.bind(('', port))
    print("socket binded to %s" %(port))

    s.listen(5)
    print("socket is listening")

    while True:
        c, addr = s.accept()
        print('Got connection from', addr )

        c.send('Thank you for connecting'.encode())
        c.close()

        break
        

• Client:

Now we need something with which a server can interact.

    import socket

    s = socket.socket()
    port = 12345
    s.connect(('127.0.0.1', port))

    print(s.recv(1024).decode())

    s.close()
        

Check internet conectivity

A simple script to check if an active internet connection is available.

    import socket

    def check_internet_connection(host="8.8.8.8", port=53, timeout=5):
        try:
            socket.setdefaulttimeout(timeout)
            socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
            return True
        except socket.error as ex:
            print(f"No internet connection: {ex}")
            return False
        

SSL Module

The ssl module is essential for creating secure connections in network applications. It provides tools to wrap sockets with SSL/TLS support, ensuring that data transmitted over the network is encrypted and secure.

Classes and Functions

?>
Function Description Usage
SSLContext An SSLContext object holds various SSL-related settings and configurations. It is used to create SSL-wrapped sockets. context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
wrap_socket Wraps an existing socket in an SSL context, providing SSL/TLS functionality. wrapped_socket = context.wrap_socket(socket.socket(), server_hostname='example.com')
create_default_context Creates an SSLContext object with default settings. context = ssl.create_default_context()
SSLSocket An SSLSocket object represents an SSL-wrapped socket.
SSLObject An SSLObject represents a non-networked SSL protocol instance.

• Creating a Secure Server

    import socket
    import ssl

    def secure_server():
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain(certfile='cert.pem', keyfile='key.pem')

        with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
            sock.bind(('localhost', 8443))
            sock.listen(5)
            with context.wrap_socket(sock, server_side=True) as ssock:
                conn, addr = ssock.accept()
                print(f'Connection from {addr}')
                data = conn.recv(1024)
                conn.sendall(b'HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello, World!')
                conn.close()
    
    secure_server()
        

• Creating a Secure Client

    import socket
    import ssl

    def secure_client():
        context = ssl.create_default_context()

        with socket.create_connection(('www.example.com', 443)) as sock:
            with context.wrap_socket(sock, server_hostname='www.example.com') as ssock:
                ssock.sendall(b'GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n')
                print(ssock.recv(4096).decode())
    
    secure_client()
        

• Secure File Transfer

    import socket
    import ssl

    def secure_file_transfer_client(file_path):
        context = ssl.create_default_context()

        with socket.create_connection(('localhost', 8443)) as sock:
            with context.wrap_socket(sock, server_hostname='localhost') as ssock:
                with open(file_path, 'rb') as f:
                    data = f.read()
                    ssock.sendall(data)

    def secure_file_transfer_server(save_path):
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain(certfile='cert.pem', keyfile='key.pem')

        with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
            sock.bind(('localhost', 8443))
            sock.listen(5)
            with context.wrap_socket(sock, server_side=True) as ssock:
                conn, addr = ssock.accept()
                print(f'Connection from {addr}')
                data = conn.recv(4096)
                with open(save_path, 'wb') as f:
                    f.write(data)
                conn.close()
        

Internet Related Services

Web Browser Module

In Python, webbrowser module is a convenient web browser controller. It provides a high-level interface that allows displaying Web-based documents to users.
webbrowser can also be used as a CLI tool. It accepts a URL as the argument with the following optional parameters: -n opens the URL in a new browser window, if possible, and -t opens the URL in a new browser tab.

    python -m webbrowser -t "https://www.google.com"
        

• The webbrowser module can be used to launch a browser in a platform-independent manner.

    import webbrowser
    webbrowser.open('http://www.python.org')
        

• Open the page in a new browser window.

    import webbrowser
    webbrowser.open_new('http://www.python.org')
        

• Open the page in a new browser tab.

    import webbrowser
    webbrowser.open_new_tab('http://www.python.org')
        

• To open a page in a specific browser, use the webbrowser.get() function to specify a particular browser.

    import webbrowser
    c = webbrowser.get('firefox')
    c.open('http://www.python.org')
    c.open_new_tab('http://docs.python.org')
        

18. File Handling

Python has several functions for creating, reading, updating, and deleting files.

File Handling

The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:

Method Name Description
r Read Opens a file for reading, error if the file does not exist
a Append Opens a file for appending, creates the file if it does not exist
w Write Opens a file for writing, creates the file if it does not exist
x Create Creates the specified file, returns an error if the file exists
t Text Text mode
b Binary Binary mode (e.g. images)

To open a file for reading it is enough to specify the name of the file:

    f = open("demofile.txt")
        

The code above is the same as:

    f = open("demofile.txt", "rt")
        

Note: Make sure the file exists, or else you will get an error.

Read Files

The open() function returns a file object, which has a read() method for reading the content of the file:

    f = open("demofile.txt", "r")
    print(f.read())
        

If the file is located in a different location, you will have to specify the file path, like this:

    f = open("D:\\myfiles\welcome.txt", "r")
    print(f.read())
        

By default the read() method returns the whole text, but you can also specify how many characters you want to return:

    f = open("demofile.txt", "r")
    print(f.read(5))
        

You can return one line by using the readline() method:

    f = open("demofile.txt", "r")
    print(f.readline())
        

By calling readline() two times, you can read the two first lines:

    f = open("demofile.txt", "r")
    print(f.readline())
    print(f.readline())
        

By looping through the lines of the file, you can read the whole file, line by line:

    f = open("demofile.txt", "r")
    for x in f:
        print(x)
        

It is a good practice to always close the file when you are done with it.

    f = open("demofile.txt", "r")
    print(f.readline())
    f.close()
        

Note: You should always close your files. In some cases, due to buffering, changes made to a file may not show until you close the file.

Write Files

To write to an existing file, you must add a parameter to the open() function:
• "a" - Append = will append to the end of the file.

    f = open("demofile2.txt", "a")
    f.write("Now the file has more content!")
    f.close()

    f = open("demofile2.txt", "r")
    print(f.read())
        

• "w" - Write = will overwrite any existing content.

    f = open("demofile3.txt", "w")
    f.write("Woops! I have deleted the content!")
    f.close()

    f = open("demofile2.txt", "r")
    print(f.read())
        

Note: the "w" method will overwrite the entire file.

To create a new file in Python, use the open() method, with one of the following parameters:
• "x" - Create = will create a file, returns an error if the file exists

    f = open("myfile.txt", "x")
        

Result: a new empty file is created!

• "a" - Append = will create a file if the specified file does not exists.

• "w" - Write = will create a file if the specified file does not exists.

    f = open("myfile.txt", "w")
        

Delete Files

To delete a file, you must import the OS module, and run its os.remove() function:

    import os
    os.remove("demofile.txt")
        

To avoid getting an error, you might want to check if the file exists before you try to delete it:

    import os

    if os.path.exists("demofile.txt"):
        os.remove("demofile.txt")
    else:
        print("The file does not exist")
        

To delete an entire folder, use the os.rmdir() method:

    import os

    os.rmdir("myfolder")
        

Note: You can only remove empty folders.

19. Python System Functions

20. Databases

SqLite

Introduction to SQLite in Python

Databases offer numerous functionalities by which one can manage large amounts of information easily over the web and high-volume data input and output over a typical file such as a text file. SQL is a query language and is very popular in databases.
Python has a library to access SQLite databases, called sqlite3, intended for working with this database which has been included with Python package since version 2.5. SQLite has the following features:

• Serverless
SQLite does not require a server to run. SQLite database is joined with the application that accesses the database. SQLite database read and write directly from the database files stored on disk and applications interact with that SQLite database.

• Self-Contained
SQLite is self-contained means it does not need any external dependencies like an operating system or external library. This feature of SQLite help especially in embedded devices like iPhones, Android phones, game consoles, handheld media players, etc.

• Zero-Configuration
SQLite is zero-configuration means no setup or administration needed. Because of the serverless architecture, you don’t need to “install” SQLite before using it. There is no server process that needs to be configured, started, and stopped.

• Transactional
SQLite is Transactional means they are atomic, consistent, isolated, and durable(ACID). All transactions in SQLite are fully ACID-compliant. In other words, all changes within a transaction take place completely or not at all even when an unexpected situation like application crash, power failure, or operating system crash occurs.

• Single-Database
SQLite is a single database that means it allows a single database connection to access multiple database files simultaneously. These features bring many nice features like joining tables in different databases or copying data between databases in a single command. SQLite also uses dynamic types for tables. It means you can store any value in any column, regardless of the data type.

Connecting to Database

Connecting to the SQLite Database can be established using the connect() method, passing the name of the database to be accessed as a parameter. If that database does not exist, then it’ll be created.

    sqliteConnection = sqlite3.connect('sql.db')
        

A cursor is created using the cursor() method on the connection instance, which will execute our SQL queries.

    cursor = sqliteConnection.cursor()
        

The SQL query to be executed can be written in form of a string, and then executed by calling the execute() method on the cursor object. Then, the result can be fetched from the server by using the fetchall() method.

    query = 'select sqlite_version();'
    cursor.execute(query)
    result = cursor.fetchall()
    print('SQLite Version is {}'.format(result))
    returns SQLite Version is [('3.45.1',)]
        

Let's now put it all together in a script to find the sqlite version:

    import sqlite3

    try:
        sqliteConnection = sqlite3.connect('sql.db')
        cursor = sqliteConnection.cursor()
        print('DB Init')

        query = 'select sqlite_version();'
        cursor.execute(query)
        result = cursor.fetchall()
        print('SQLite Version is {}'.format(result))

        cursor.close()

    except sqlite3.Error as error:
        print('Error occurred - ', error)

    finally:
        if sqliteConnection:
            sqliteConnection.close()
            print('SQLite Connection closed')

    returns DB Init
            SQLite Version is [('3.45.1',)]
            SQLite Connection closed
        

SQLite Datatypes and its Corresponding Python Types

A storage class can be called a collection of similar DataTypes. SQLite provides the following storage classes:

Storage Class Value Stored
NULL NULL
INTEGER Signed Integer (1, 2, 3, 4, 5, or 8 bytes depending on magnitude)
REAL Floating point value (8 byte IEEE floating-point numbers)
TEXT Text string (encoded in UTF-8, UTF-16BE or UTF-16LE
BLOB (Binary Large Object) Data stored exactly the way it was input, generally in binary format

The SQLite DataTypes and their corresponding Python types are as follows

Storage Class Python Database
NULL None
INTEGER int
REAL Float
TEXT str
BLOB bytes

The type() function can be used in python to get the class of an argument. In the program below, the type() function is used to print the classes of every value we store in a database.

    import sqlite3

    cnt = sqlite3.connect('cfg.db')
    sql_table = ('''CREATE TABLE exam_hall( 
                    NAME TEXT, 
                    PIN INTEGER, 
                    OCCUPANCY REAL, 
                    LOGO BLOB);''')
    cnt.execute (sql_table)
    
    fileh = open('/content/JSBinCollaborativeJavaScriptDebugging6-300x160.png', 'rb') 
    img = fileh.read()
    
    sql = '''INSERT INTO exam_hall VALUES('centre-a',1125,98.6,?)''', (img,)
    sql2 = '''INSERT INTO exam_hall VALUES(NULL,1158,80.5,?)''', (img,)
    cnt.execute (sql, sql2)

    cursor = cnt.execute('''SELECT * FROM exam_hall;''')
    for i in cursor:
        print(str(i[0])+" "+str(i[1])+" "+str(i[2])+" "+str(len(i[3])))
        print(str(type(i[0]))+" "+str(type(i[1]))+" " + str(type(i[2]))+" "+str(type(i[3]))+"\n") 
    
    returns centre-a 1125 98.6 17030 
            class 'str' class 'int' class 'float' class 'bytes'
            
            None 1158 80.5 17030
            class 'NoneType' class 'int' class 'float' class 'bytes'
        

From the output of this program, the following observations can be made:
• ‘centre-a’ that was inserted as TEXT has been interpreted by python as str.
• 1125, 1158 that were inserted as INTEGER have been interpreted by python as int.
• 98.6, 80.5 that were inserted as REAL have been interpreted by python as float.
• NULL was interpreted by python as NoneType.
• The logo image which was inserted in binary format as BLOB has been interpreted by python as bytes.

Cursor Object

It is an object that is used to make the connection for executing SQL queries. It acts as middleware between SQLite database connection and SQL query. It is created after giving connection to SQLite database.

Syntax: cursor_object=connection_object.execute(“sql query”);

Python code to create a hotel_data database and insert records into the hotel table:

    import sqlite3

    connection = sqlite3.connect('hotel_data.db')
    sql_table = (''' CREATE TABLE hotel
                (FIND  INT PRIMARY KEY  NOT NULL,
                FNAME  TEXT  NOT NULL,
                COST   INT   NOT NULL,
                WEIGHT INT);
                ''')
    connection.execute(sql_table)

    sql = "INSERT INTO hotel (FIND, FNAME, COST, WEIGHT) VALUES (?, ?, ?, ?)"
    sql_data = [
    (1, 'cakes', 800, 10),
    (2, 'biscuits', 100, 20),
    (3, 'chocos', 1000, 30)
    ]
    connection.executemany(sql, sql_data)

    print("All data in food table\n")

    cursor = connection.execute("SELECT * from hotel")
    for row in cursor:
        print(row)

    returns All data in food table
            (1, 'cakes', 800, 10),
            (2, 'biscuits', 100, 20),
            (3, 'chocos', 1000, 30)
        

Create Table

In SQLite database we use the following syntax to create a table:

    CREATE TABLE database_name.table_name(

    column1 datatype PRIMARY KEY(one or more columns),

    column2 datatype,

    column3 datatype,

    …..

    columnN datatype

    );
        

Now let's create a table in the following example:

    import sqlite3

    connection_obj = sqlite3.connect('coding.db')
    cursor_obj = connection_obj.cursor()
    cursor_obj.execute("DROP TABLE IF EXISTS CODING")

    table = """ CREATE TABLE GEEK (
            Email VARCHAR(255) NOT NULL,
            First_Name CHAR(25) NOT NULL,
            Last_Name CHAR(25),
            Score INT
        ); """
 
    cursor_obj.execute(table)
    print("Table is Ready")

    connection_obj.close()

    returns "Table is Ready"
        

Insert Data

The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows:
• Only values: The first method is to specify only the value of data to be inserted without the column names.

    INSERT INTO table_name VALUES (value1, value2, value3,…);
        

• Column names and values both: In the second method we will specify both the columns which we want to fill and their corresponding values.

    INSERT INTO table_name (column1, column2, column3,..) VALUES ( value1, value2, value3,..);
        

Let's put above into practice:

    import sqlite3

    conn = sqlite3.connect('coding2.db')
    cursor = conn.cursor()

    table ="""CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255), SECTION VARCHAR(255));"""
    cursor.execute(table)

    sql = "INSERT INTO STUDENT VALUES (?, ?, ?)"
    sql_data = [
        ('Raju', '7th', 'A'),
        ('Shyam', '8th', 'B'),
        ('Baburao', '9th', 'C')
    ]
    connection.executemany(sql, sql_data)
    print("Data Inserted in the table: ")

    data=cursor.execute('''SELECT * FROM STUDENT''')
    for row in data:
        print(row)

    conn.commit()
    conn.close()

    returns "Data Inserted in the table: 
            ('Raju', '7th', 'A'),
            ('Shyam', '8th', 'B'),
            ('Baburao', '9th', 'C')"
        

We can also specify the columns for the values to be inserted:

    sql = "INSERT INTO STUDENT (NAME, CLASS, SECTION) VALUES (?, ?, ?)"
    sql_data = [
        ('Raju', '7th', 'A'),
        ('Shyam', '8th', 'B'),
        ('Baburao', '9th', 'C')
    ]
    connection.executemany(sql, sql_data)
        

Select Data from Table

The SELECT statement is used to retrieve data from an SQLite table and this returns the data contained in the table.
In SQLite the syntax of Select Statement is:

    SELECT * FROM table_name;
        

Note: * means all the column from the table. To select specific column replace * with the column name or column names.

Now we will use the Select statement in the Python program and see the results.
Creating the table:

    import sqlite3

    conn = sqlite3.connect('coding3.db')
    cursor = conn.cursor()

    table ="""CREATE TABLE CODING(Email varchar(255), Name varchar(50), Score int);"""
    cursor.execute(table)

    sql = "INSERT INTO CODING (Email,Name,Score) VALUES (?, ?, ?)"
    sql_data = [
        ("coding1@gmail.com","Coding1",25),
        ("coding2@gmail.com","Coding2",15),
        ("coding3@gmail.com","Coding3",36),
        ("coding4@gmail.com","Coding4",27),
        ("coding5@gmail.com","Coding5",40),
        ("coding6@gmail.com","Coding6",36),
        ("coding7@gmail.com","Coding7",27)
    ]
    connection.executemany(sql, sql_data)
    conn.commit()
    conn.close()
        

• Read All Rows:
Now we will use the Select statement to retrieve data from the table and fetch all records. To fetch all records we will use fetchall() method.

    Syntax: cursor.fetchall()
        

Example:

    import sqlite3
    
    conn = sqlite3.connect('coding3.db')
    cursor = conn.cursor()

    statement = '''SELECT * FROM CODING'''
    cursor.execute(statement)

    print("All the data")
    output = cursor.fetchall()
    for row in output:
        print(row)
    
    conn.commit()
    conn.close()

    returns All the data
            ("coding1@gmail.com","Coding1",25),
            ("coding2@gmail.com","Coding2",15),
            ("coding3@gmail.com","Coding3",36),
            ("coding4@gmail.com","Coding4",27),
            ("coding5@gmail.com","Coding5",40),
            ("coding6@gmail.com","Coding6",36),
            ("coding7@gmail.com","Coding7",27)
        

• Read Some Rows:
Now we will use the Select statement to retrieve data from the table and fetch many records not all. To fetch many records we will use fetchmany() method.

    Syntax: cursor.fetchmany(size)

    Parameters: size – a limit to fetch records
        

Example:

    import sqlite3
    
    conn = sqlite3.connect('coding3.db')
    cursor = conn.cursor()

    statement = '''SELECT * FROM CODING'''
    cursor.execute(statement)

    print("Limited data")
    output = cursor.fetchmany(5)
    for row in output:
        print(row)
    
    conn.commit()
    conn.close()

    returns Limited data
            ("coding1@gmail.com","Coding1",25),
            ("coding2@gmail.com","Coding2",15),
            ("coding3@gmail.com","Coding3",36),
            ("coding4@gmail.com","Coding4",27),
            ("coding5@gmail.com","Coding5",40),
        

• Read Only one Row:
Now we will use the Select statement to retrieve data from the table and fetch only one record. To fetch only one record, we will use fetchone() method.

    Syntax: cursor.fetchone()
        

Example:

    import sqlite3
    
    conn = sqlite3.connect('coding3.db')
    cursor = conn.cursor()

    statement = '''SELECT * FROM CODING'''
    cursor.execute(statement)

    print("Only one data")
    output = cursor.fetchone()
    print(output)
    
    conn.commit()
    conn.close()

    returns All the data
            ("coding1@gmail.com","Coding1",25)
        

WHERE Clause

The WHERE clause is used in order to make our search results more specific, using the where clause in SQL/SQLite we can go ahead and specify specific conditions that have to be met when retrieving data from the database.

    Syntax:  
    SELECT column_1, column_2,…,column_N FROM table_name WHERE [search_condition]

    Here, in this [search_condition] you can use comparison or logical operators to specify conditions.
    For example:  = , > , < , != , LIKE, NOT, etc. 
        

Let’s Create a Database (codingforgeeks_student.db) and a Table (STUDENT) and insert data into STUDENT table.

    import sqlite3
    
    conn = sqlite3.connect('codingforgeeks_student.db')
    cursor = conn.cursor()

    cursor.execute("DROP TABLE IF EXISTS STUDENT")
    createTable = '''CREATE TABLE STUDENT(
                    Student_ID int, First_Name VARCHAR(100),
                    Last_Name VARCHAR(100), Age int,
                    Department VARCHAR(100)
    )'''
    cursor.execute(createTable)

    if cursor:
        print("Database Created Successfully !")
    else:
        print("Database Creation Failed !")

    connection.commit()

    sql = "INSERT INTO STUDENT VALUES (?, ?, ?, ?, ?)"
    sql_data = [
        (1,'Rohit', 'Pathak', 21, 'IT'),
        (2,'Nitin', 'Biradar', 21, 'IT'),
        (3,'Virat', 'Kohli', 30, 'CIVIL'),
        (,'Rohit', 'Sharma', 32, 'COMP')
    ]
    connection.executemany(sql, sql_data)

    n class="python_highlight">if cursor:
        print("Data Inserted !")
    else:
        print("Data Insertion Failed !")

    connection.commit()
    connection.close()
        

Example 1: To retrieve the data of the students whose Department is IT

    import sqlite3
    
    conn = sqlite3.connect('codingforgeeks_student.db')
    cursor = conn.cursor()

    cursor.execute("SELECT * FROM STUDENT WHERE Department = 'IT'")
    print(cursor.fetchall())

    connection.commit()
    connection.close()

    returns (1, ‘Rohit’, ‘Pathak’, 21, ‘IT’), (2, ‘Nitin’, ‘Biradar’, 21, ‘IT’)]
        

Example 2: To retrieve the data of the students whose First Name starts with ‘R’. We can also use Wildcard characters with WHERE clause.

    import sqlite3
    
    conn = sqlite3.connect('codingforgeeks_student.db')
    cursor = conn.cursor()

    cursor.execute("SELECT * from STUDENT WHERE First_name Like'R%'")
    print(cursor.fetchall())

    connection.commit()
    connection.close()

    returns [(1, ‘Rohit’, ‘Pathak’, 21, ‘IT’), (4, ‘Rohit’, ‘Sharma’, 32, ‘COMP’)]
        

ORDER BY Clause

The ORDER BY statement is a SQL statement that is used to sort the data in either ascending or descending according to one or more columns. By default, ORDER BY sorts the data in ascending order.
• DESC is used to sort the data in descending order.
• ASC to sort in ascending order.

    Syntax: SELECT column1,column2,., column n  FROM table_name ORDER BY column_name ASC|DESC;
        

First, let’s create a database and Insert 5 records into the customer_address table.

    import sqlite3

    connection = sqlite3.connect('code_database.db')
    sql_table = CREATE TABLE customer_address 
         (ID INT PRIMARY KEY     NOT NULL, 
         NAME           TEXT    NOT NULL, 
         AGE            INT     NOT NULL, 
         ADDRESS        CHAR(50)); '''

    connection.execute(sql_table)

    sql = "INSERT INTO customer_address VALUES (?, ?, ?, ?)"
    sql_data = [
        (1, 'nikhil teja', 22, 'hyderabad'),
        (2, 'karthik', 25, 'khammam'),
        (3, 'sravan', 22, 'ponnur'),
        (4, 'deepika', 25, 'chebrolu'),
        (5, 'jyothika', 22, 'noida')
    ]
    connection.executemany(sql, sql_data)
    conn.commit()
    conn.close()
        

Example 1: Display all details from the table in ascending order(default) based on address.

    import sqlite3

    connection = sqlite3.connect('code_database.db')
    cursor = connection.execute("SELECT ADDRESS,ID from customer_address ORDER BY address DESC")

    for i in cursor:
        print(i)
    conn.close()

    returns (4, 'deepika', 25, 'chebrolu')
            (1, 'nikhil teja', 22, 'hyderabad'),
            (2, 'karthik', 25, 'khammam')
            (5, 'jyothika', 22, 'noida')
            (3, 'sravan', 22, 'ponnur')
        

LIMIT Clause

If there are many tuples satisfying the query conditions, it might be resourceful to view only a handful of them at a time. LIMIT keyword is used to limit the data given by the SELECT statement.

        Syntax:
        SELECT column1, column2, column n FROM table_name LIMIT [no of rows];

        where no of rows is an integer value specified as the no of rows to get as output from table.
        

Using our code_database.db, we are going to display the top 4 data from the table.

    import sqlite3

    connection = sqlite3.connect('code_database.db')
    cursor = connection.execute("SELECT * FROM customer_address LIMIT 4")

    for i in cursor:
        print(i)
    conn.close()

    returns (1, 'nikhil teja', 22, 'hyderabad'),
            (2, 'karthik', 25, 'khammam')
            (3, 'sravan', 22, 'ponnur')
            (4, 'deepika', 25, 'chebrolu')
        

JOIN Clause

A JOIN clause combines the records from two tables on the basis of common attributes. The different types of joins are as follows:
• INNER JOIN (OR JOIN) – Gives the records that have common attributes in both tables.
• LEFT JOIN – Gives all records from the left table and only the common records from the right table.
• RIGHT JOIN – Gives all records from the right table and only the common records from the left table.
• FULL OUTER JOIN – Gives all records when there is a common attribute in either the left or the right table.
• CROSS JOIN – Gives records of one table with all other records of another table.

Note: SQLite does not directly support the RIGHT JOIN and FULL OUTER JOIN.

Here, we will create a simple database having two tables Advisor(AdvisorID, AdvisorName) and Student(StudentID, StudentName, AdvisorID) where AdvisorID of the Student table is the foreign key referencing AdvisorID of the Advisor table.

    import sqlite3

    conn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')
    cursor = conn.cursor()

    cursor.executescript(''' 
    CREATE TABLE Advisor( 
        AdvisorID INTEGER NOT NULL, 
        AdvisorName TEXT NOT NULL, 
        PRIMARY KEY(AdvisorID) 
    ); 
    
    CREATE TABLE Student( 
        StudentID NUMERIC NOT NULL, 
        StudentName NUMERIC NOT NULL, 
        AdvisorID INTEGER, 
        FOREIGN KEY(AdvisorID) REFERENCES Advisor(AdvisorID), 
        PRIMARY KEY(StudentID) 
    ); 
  
    INSERT INTO Advisor(AdvisorID, AdvisorName) VALUES 
        (1,"John Paul"),  
        (2,"Anthony Roy"),  
        (3,"Raj Shetty"), 
        (4,"Sam Reeds"), 
        (5,"Arthur Clintwood"); 
    
    INSERT INTO Student(StudentID, StudentName, AdvisorID) VALUES 
        (501,"Geek1",1), 
        (502,"Geek2",1), 
        (503,"Geek3",3), 
        (504,"Geek4",2), 
        (505,"Geek5",4), 
        (506,"Geek6",2), 
        (507,"Geek7",2), 
        (508,"Geek8",3), 
        (509,"Geek9",NULL), 
        (510,"Geek10",1); 
    ''') 
    conn.commit()
    conn.close()
        

• INNER JOIN:
Inner join also represented as join which gives the records that have common attributes in both tables.

    Syntax:
    SELECT columns FROM table1 [INNER] JOIN table2 ON table1.column = table2.column;

    ** INNER keyword is optional **
        

Example:

    import sqlite3

    conn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')
    cursor = conn.cursor()

    sql = '''SELECT StudentID, StudentName, AdvisorName FROM Student INNER JOIN Advisor ON Student.AdvisorID = Advisor.AdvisorID;'''
    cursor.execute(sql)

    result = cursor.fetchall()
    for row in result:
        print(row)
    conn.close() 

    returns (501,"Geek1","John Paul"), 
        (502,"Geek2","John Paul"), 
        (503,"Geek3","Raj Shetty"), 
        (504,"Geek4","Anthony Roy"), 
        (505,"Geek5","Sam Reeds"), 
        (506,"Geek6","Anthony Roy"), 
        (507,"Geek7","Anthony Roy"), 
        (508,"Geek8","Raj Shetty"), 
        (510,"Geek10","John Paul")
        

• LEFT JOIN:
Gives all records from the left table, and only the common records from the right table.


    Syntax:
    SELECT columns FROM table1 LEFT [OUTER] JOIN table2 ON table1.column = table2.column;

    ** OUTER keyword is optional **
        

Example:

    import sqlite3

    conn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')
    cursor = conn.cursor()

    sql = '''SELECT StudentID, StudentName, AdvisorName FROM Student LEFT JOIN Advisor USING(AdvisorID);'''
    cursor.execute(sql)

    result = cursor.fetchall()
    for row in result:
        print(row)
    conn.close() 

    returns (501,"Geek1","John Paul"), 
        (502,"Geek2","John Paul"), 
        (503,"Geek3","Raj Shetty"), 
        (504,"Geek4","Anthony Roy"), 
        (505,"Geek5","Sam Reeds"), 
        (506,"Geek6","Anthony Roy"), 
        (507,"Geek7","Anthony Roy"), 
        (508,"Geek8","Raj Shetty"), 
        (509,"Geek9","None"),
        (510,"Geek10","John Paul")
        

• RIGHT JOIN:
Gives all records from the right table, and only the common records from the left table. As mentioned before, SQLite does not directly support RIGHT JOIN. However, it can be emulated using LEFT JOIN by switching the positions of the student and advisor table.

    Syntax:
    SELECT columns FROM table1 RIGHT [OUTER] JOIN table2 ON table1.column = table2.column;

    ** OUTER keyword is optional **
        

Example:

    import sqlite3

    conn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')
    cursor = conn.cursor()

    sql = '''SELECT StudentID, StudentName, AdvisorName FROM Advisor LEFT JOIN Student USING(AdvisorID);'''
    cursor.execute(sql)

    result = cursor.fetchall()
    for row in result:
        print(row)
    conn.close()
    
    returns (501,"Geek1","John Paul"), 
        (502,"Geek2","John Paul"),
        (510,"Geek10","John Paul"),
        (504,"Geek4","Anthony Roy"), 
        (506,"Geek6","Anthony Roy"), 
        (507,"Geek7","Anthony Roy"), 
        (503,"Geek3","Raj Shetty"), 
        (508,"Geek8","Raj Shetty"), 
        (505,"Geek5","Sam Reeds"),
        (None,"None","Arthur Clintwood")
        

• FULL OUTER JOIN:
Gives all records when there is a common attribute in either left or the right table. As mentioned before, SQLite does not directly support FULL OUTER JOIN. However, it can be emulated using LEFT JOIN. In this query, the second SELECT statement has the positions of the student and advisor table switched. The UNION ALL clause retains the duplicate rows from the result of both SELECT queries. And the WHERE clause in the second SELECT statement removes rows that already included in the result set of the first SELECT statement.

    Syntax:
    SELECT columns FROM table1 FULL [OUTER] JOIN table2 ON table1.column = table2.column;

    ** OUTER keyword is optional **
        

Example:

    import sqlite3

    conn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')
    cursor = conn.cursor()

    sql = '''SELECT StudentID, StudentName, AdvisorName FROM Student LEFT JOIN Advisor USING(AdvisorID) UNION ALL 
             SELECT StudentID, StudentName, AdvisorName FROM Advisor LEFT JOIN Student USING(AdvisorID) WHERE Student.AdvisorID IS NULL;'''
    cursor.execute(sql)

    result = cursor.fetchall()
    for row in result:
        print(row)
    conn.close()
    
    returns (501,"Geek1","John Paul"), 
        (502,"Geek2","John Paul"), 
        (503,"Geek3","Raj Shetty"), 
        (504,"Geek4","Anthony Roy"), 
        (505,"Geek5","Sam Reeds"), 
        (506,"Geek6","Anthony Roy"), 
        (507,"Geek7","Anthony Roy"), 
        (508,"Geek8","Raj Shetty"), 
        (509,"Geek9","None"),
        (510,"Geek10","John Paul")
        (None,"None","Arthur Clintwood")
        

• CROSS JOIN:
It combines all records of one table with all other records of another table, that is, it creates a Cartesian product of records from the join tables.

    Syntax:
    SELECT columns FROM table1 CROSS JOIN table2;
        

Example:

    import sqlite3

    conn = sqlite3.connect(r'C:\Users\SQLite\Geeks.db')
    cursor = conn.cursor()

    sql = '''SELECT StudentID, StudentName, AdvisorName FROM Student CROSS JOIN Advisor;'''
    cursor.execute(sql)

    result = cursor.fetchall()
    for row in result:
        print(row)
    conn.close()
    
    returns (501, 'Geek1', 'John Paul')
            (501, 'Geek1', 'Anthony Roy')
            (501, 'Geek1', 'Raj Shetty')
            (501, 'Geek1', 'Sam Reeds')
            (501, 'Geek1', 'Arthur Clintwood')
            (502, 'Geek2', 'John Paul')
            (502, 'Geek2', 'Anthony Roy')
            (502, 'Geek2', 'Raj Shetty')
            (502, 'Geek2', 'Sam Reeds')
            (502, 'Geek2', 'Arthur Clintwood')
            (503, 'Geek3', 'John Paul')
            (503, 'Geek3', 'Anthony Roy')
            (503, 'Geek3', 'Raj Shetty')
            (503, 'Geek3', 'Sam Reeds')
            (503, 'Geek3', 'Arthur Clintwood')
            (504, 'Geek4', 'John Paul')
            (504, 'Geek4', 'Anthony Roy')
            (504, 'Geek4', 'Raj Shetty')
            (504, 'Geek4', 'Sam Reeds')
            (504, 'Geek4', 'Arthur Clintwood')
            (505, 'Geek5', 'John Paul')
            (505, 'Geek5', 'Anthony Roy')
            (505, 'Geek5', 'Raj Shetty')
            (505, 'Geek5', 'Sam Reeds')
            (505, 'Geek5', 'Arthur Clintwood')
            (506, 'Geek6', 'John Paul')
            (506, 'Geek6', 'Anthony Roy')
            (506, 'Geek6', 'Raj Shetty')
            (506, 'Geek6', 'Sam Reeds')
            (506, 'Geek6', 'Arthur Clintwood')
            (507, 'Geek7', 'John Paul')
            (507, 'Geek7', 'Anthony Roy')
            (507, 'Geek7', 'Raj Shetty')
            (507, 'Geek7', 'Sam Reeds')
            (507, 'Geek7', 'Arthur Clintwood')
            (508, 'Geek8', 'John Paul')
            (508, 'Geek8', 'Anthony Roy')
            (508, 'Geek8', 'Raj Shetty')
            (508, 'Geek8', 'Sam Reeds')
            (508, 'Geek8', 'Arthur Clintwood')
            (509, 'Geek9', 'John Paul')
            (509, 'Geek9', 'Anthony Roy')
            (509, 'Geek9', 'Raj Shetty')
            (509, 'Geek9', 'Sam Reeds')
            (509, 'Geek9', 'Arthur Clintwood')
            (510, 'Geek10', 'John Paul')
            (510, 'Geek10', 'Anthony Roy')
            (510, 'Geek10', 'Raj Shetty')
            (510, 'Geek10', 'Sam Reeds')
            (510, 'Geek10', 'Arthur Clintwood')
        

Deleting Data in Table

n SQLite database we use the following syntax to delete data from a table:

    DELETE FROM table_name [WHERE Clause]
        

Example:

    import sqlite3

    connection = sqlite3.connect('geek.db')
    cursor = connection.cursor()

    sql_table = """ CREATE TABLE GEEK (
                    Email VARCHAR(255) NOT NULL,
                    Name CHAR(25) NOT NULL,
                    Score INT
                ); """

    connection.execute(sql_table)

    sql = "INSERT INTO GEEK (Email,Name,Score) VALUES (?, ?, ?)"
    sql_data = [
        ("geekk1@gmail.com","Geek1",25),
        ("geekk2@gmail.com","Geek2",15),
        ("geekk3@gmail.com","Geek3",36),
        ("geekk4@gmail.com","Geek4",27),
        ("geekk5@gmail.com","Geek5",40),
        ("geekk6@gmail.com","Geek6",14),
        ("geekk7@gmail.com","Geek7",10)
    ]
    connection.executemany(sql, sql_data)
    conn.commit()
    conn.close()
        

Delete some data:

    import sqlite3

    connection = sqlite3.connect('geek.db')
    cursor = connection.cursor()

    cursor.execute("DELETE FROM GEEK WHERE Score < 15")
    connection.commit()

    select_query = "SELECT * FROM GEEK"
    cursor.execute(select_query)

    data = cursor.fetchall()

    print("Remaining rows in the database:")
    for row in data:
        print(row)

    connection.close()
    
    returns Remaining rows in the database:
            ('geekk1@gmail.com', 'Geek1', 25)
            ('geekk2@gmail.com', 'Geek2', 15)
            ('geekk3@gmail.com', 'Geek3', 36)
            ('geekk4@gmail.com', 'Geek4', 27)
            ('geekk5@gmail.com', 'Geek5', 40)
        

Delete all data:

    import sqlite3

    connection = sqlite3.connect('geek.db')
    cursor = connection.cursor()

    cursor.execute("DELETE FROM GEEK")
    connection.commit()

    select_query = "SELECT * FROM GEEK"
    cursor.execute(select_query)

    data = cursor.fetchall()

    print("After deleting all rows")
    print(data)

    connection.close()
    
    returns Remaining rows in the database:
    []
        

DROP Table

DROP is used to delete the entire database or a table. It deleted both records in the table along with the table structure.

    Syntax: 
        DROP TABLE TABLE_NAME;
        

First create a database and a table. Then Insert 5 records into the customer_address table.

    import sqlite3

    connection = sqlite3.connect('code_database.db')
    sql_table = CREATE TABLE customer_address 
         (ID INT PRIMARY KEY     NOT NULL, 
         NAME           TEXT    NOT NULL, 
         AGE            INT     NOT NULL, 
         ADDRESS        CHAR(50)); '''

    connection.execute(sql_table)

    sql = "INSERT INTO customer_address VALUES (?, ?, ?, ?)"
    sql_data = [
        (1, 'nikhil teja', 22, 'hyderabad'),
        (2, 'karthik', 25, 'khammam'),
        (3, 'sravan', 22, 'ponnur'),
        (4, 'deepika', 25, 'chebrolu'),
        (5, 'jyothika', 22, 'noida')
    ]
    connection.executemany(sql, sql_data)
    conn.commit()
    conn.close()
        

Let’s see how to execute the drop table command.

    import sqlite3

    connection = sqlite3.connect('code_database.db')
    connection.execute("DROP TABLE customers_address")
    connection.close()

    print("data dropped successfully")
    returns data dropped successfully
        

Update Data

The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement.

    Syntax:
        UPDATE table_name SET column1 = value1, column2 = value2,…
        WHERE condition; 
        

In the above syntax, the SET statement is used to set new values to the particular column, and the WHERE clause is used to select the rows for which the columns are needed to be updated.
Create an EMPLOYEE table and insert values into it. Then we are going to set the income of employees to 5000 whose age is less than 25.

    import sqlite3

    connection = sqlite3.connect('cfg1.db')
    cursor = connection.cursor()

    sql_table = '''CREATE TABLE IF NOT EXISTS EMPLOYEE (
        FIRST_NAME VARCHAR(255),  
        LAST_NAME VARCHAR(255),
        AGE INT, 
        SEX VARCHAR(255), 
        INCOME INT
    );'''

    connection.execute(sql_table)

    sql = "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (?, ?, ?, ?, ?)"
    sql_data = [
        ('Anand', 'Choubey', 25, 'M', 10000),
        ('Mukesh', 'Sharma', 20, 'M', 9000),
        ('Ankit', 'Pandey', 24, 'M', 6300),
        ('Subhdra ', 'Singh', 26, 'F', 8000),
        ('Tanu', 'Mishra', 24, 'F', 6500)
    ]
    connection.executemany(sql, sql_data)

    print("EMPLOYEE Table: ")
    data = cursor.execute('''SELECT * FROM EMPLOYEE''')
    for row in data:
        print(row)
    returns ('Anand', 'Choubey', 25, 'M', 10000),
            ('Mukesh', 'Sharma', 20, 'M', 9000),
            ('Ankit', 'Pandey', 24, 'M', 6300),
            ('Subhdra ', 'Singh', 26, 'F', 8000),
            ('Tanu', 'Mishra', 24, 'F', 6500)

    sql = '''UPDATE EMPLOYEE SET INCOME = ? WHERE AGE< ?;'''
    sql_data = (5000, 25)
    cursor.execute(sql, sql_data)
    print('\nAfter Updating...\n')
    print("EMPLOYEE Table: ")
    data = cursor.execute('''SELECT * FROM EMPLOYEE''')
    for row in data:
        print(row)
    returns ('Anand', 'Choubey', 25, 'M', 10000),
            ('Mukesh', 'Sharma', 20, 'M', 5000),
            ('Ankit', 'Pandey', 24, 'M', 5000),
            ('Subhdra ', 'Singh', 26, 'F', 8000),
            ('Tanu', 'Mishra', 24, 'F', 5000)

    conn.commit()
    conn.close()
        

Update multiple columns using the UPDATE statement.

    import sqlite3

    connection = sqlite3.connect('cfg2.db')
    cursor = connection.cursor()

    sql_table = '''CREATE TABLE IF NOT EXISTS EMPLOYEE (
        NAME VARCHAR(255),  
        AGE INT, 
        DEPARTMENT VARCHAR(255)
    );'''

    connection.execute(sql_table)

    sql = "INSERT INTO STAFF(NAME, AGE, DEPARTMENT) VALUES (?, ?, ?)"
    sql_data = [
        ('Anand', 45, 'Chemistry'),
        ('Ravi', 32, 'Physics'),
        ('Chandini', 32, 'Computer'),
        ('Latika', 40, 'Maths')
    ]
    connection.executemany(sql, sql_data)

    print("STAFF Table: ")
    data = cursor.execute('''SELECT * FROM STAFF''')
    for row in data:
        print(row)
    returns ('Anand', 45, 'Chemistry'),
            ('Ravi', 32, 'Physics'),
            ('Chandini', 32, 'Computer'),
            ('Latika', 40, 'Maths')

    sql = '''UPDATE EMPLOYEE SET INCOME = ?, AGE = ?, DEPARTMENT = ? WHERE DEPARTMENT = ?;'''
    sql_data = ('Ram', 30, 'Biology', 'Computer')
    cursor.execute(sql, sql_data)
    print('\nAfter Updating...\n')
    print("STAFF Table: ")
    data = cursor.execute('''SELECT * FROM STAFF''')
    for row in data:
        print(row)
    returns ('Anand', 45, 'Chemistry'),
            ('Ravi', 32, 'Physics'),
            ('Ram', 30, 'Biology'),
            ('Latika', 40, 'Maths')

    conn.commit()
    conn.close()
        

How to use of the UPDATE statement without the WHERE statement.

    import sqlite3

    connection = sqlite3.connect('cfg2.db')
    cursor = connection.cursor()

    print("STAFF Table: ")
    data = cursor.execute('''SELECT * FROM STAFF''')
    for row in data:
        print(row)
    returns ('Anand', 45, 'Chemistry'),
            ('Ravi', 32, 'Physics'),
            ('Chandini', 32, 'Computer'),
            ('Latika', 40, 'Maths')

    sql = '''UPDATE EMPLOYEE SET INCOME = ?, AGE = ?, DEPARTMENT = ? ;'''
    sql_data = ('Employee', 0, 'Deparment')
    cursor.execute(sql, sql_data)
    print('\nAfter Updating...\n')
    print("STAFF Table: ")
    data = cursor.execute('''SELECT * FROM STAFF''')
    for row in data:
        print(row)
    returns ('Employee', 0, 'Deparment'),
            ('Employee', 0, 'Deparment'),
            ('Employee', 0, 'Deparment'),
            ('Employee', 0, 'Deparment')

    conn.commit()
    conn.close()
        

Note: If values are specified without using the WHERE statement, all records will be updated.

Check if Table Exists

In an SQLite database, the names of all the tables are enlisted in the sqlite_master table. So in order to check if a table exists or not we need to check that if the name of the particular table is in the sqlite_master table or not.

    Syntax:
        SELECT tableName FROM sqlite_master WHERE type=’table’ AND tableName=’STUDENT’;
        

Check if the STUDENT and TEACHER table exists in g4gdata.db database or not.

    import sqlite3

    connection = sqlite3.connect('cfg4.db')
    cursor = connection.cursor()

    employee_table = '''CREATE TABLE IF NOT EXISTS EMPLOYEE (
        FIRST_NAME VARCHAR(255),  
        LAST_NAME VARCHAR(255),
        AGE INT, 
        SEX VARCHAR(255), 
        INCOME INT
    );'''    
    connection.execute(employee_table)

    student_table = '''CREATE TABLE IF NOT EXISTS STUDENT (
        NAME VARCHAR(255),  
        AGE INT, 
        SEX VARCHAR(1)
    );'''    
    connection.execute(student_table)

    staff_table = '''CREATE TABLE IF NOT EXISTS STAFF (
        NAME VARCHAR(255),  
        INCOME INT
    );'''    
    connection.execute(staff_table)

    print('Check if STUDENT table exists in the database:')
    listOfTables = cursor.execute("""SELECT tableName FROM sqlite_master WHERE type='table' AND tableName='STUDENT'; """).fetchall()

    if listOfTables == []:
        print('Table not found!')
    else:
         print('Table found!')
    returns Check if STUDENT table exists in the database:
            Table found!

    print('Check if TEACHER table exists in the database:')
    listOfTables = cursor.execute("""SELECT tableName FROM sqlite_master WHERE type='table' AND tableName='TEACHER'; """).fetchall()

    if listOfTables == []:
        print('Table not found!')
    else:
         print('Table found!')
    returns Check if TEACHER table exists in the database:
            Table not found!

    connection.commit()
    connection.close()
        

List all the tables in the SQLite database and use exception handling during connecting to our database.

Database: Student, contacts, groups, persons, employees

    import sqlite3

    try:
        sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db')
        cursor = sqliteConnection.cursor()

        sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""
        cursor.execute(sql_query)
        print("List of tables\n")
        print(cursor.fetchall())

    except sqlite3.Error as error:
        print("Failed to execute the above query", error)

    finally:
        if sqliteConnection:
            sqliteConnection.close()

    returns List of tables
        [('Student',), ('contacts',), ('groups',), ('persons',), ('employees',)]
    
        

Alter a Table

By using the ALTER statement we can add one or more column to the table or change the name of the table.
• Adding a column to a table:

    Syntax:
            ALTER TABLE table_name ADD COLUMN column_name colume_type
        

Note: The column is added but will have all the values to be NULL.

    import sqlite3

    connection = sqlite3.connect('coding.db')
    cursor = connection.cursor()
    cursor.execute("DROP TABLE IF EXISTS GEEK")

    table = '''CREATE TABLE IF NOT EXISTS GEEK (
        Email VARCHAR(255),  
        Name VARCHAR(255),
        Score INT
    );'''    
    connection.execute(employee_table)

    sql = "INSERT INTO GEEK(Email, Name, Score) VALUES (?, ?, ?)"
    sql_data = [
        ("geekk1@gmail.com","Geek1",25),
        ("geekk2@gmail.com","Geek2",15),
        ("geekk3@gmail.com","Geek3",36),
        ("geekk4@gmail.com","Geek4",27),
        ("geekk5@gmail.com","Geek5",40),
        ("geekk6@gmail.com","Geek6",14),
        ("geekk7@gmail.com","Geek7",10)
    ]
    connection.executemany(sql, sql_data)

    data = cursor.execute("""SELECT * FROM GEEK""")
    print(GEEK Table:)
    for row in data:
        print(row)
    returns GEEK Table:
            ("geekk1@gmail.com","Geek1",25),
            ("geekk2@gmail.com","Geek2",15),
            ("geekk3@gmail.com","Geek3",36),
            ("geekk4@gmail.com","Geek4",27),
            ("geekk5@gmail.com","Geek5",40),
            ("geekk6@gmail.com","Geek6",14),
            ("geekk7@gmail.com","Geek7",10)

    new_column = "ALTER TABLE GEEK ADD COLUMN UserName CHAR(25)"
    cursor.execute(new_column)

    data = cursor.execute("""SELECT * FROM GEEK""")
    print(GEEK Table:)
    for row in data:
        print(row)
    returns GEEK Table:
            ("geekk1@gmail.com","Geek1",25,None),
            ("geekk2@gmail.com","Geek2",15,None),
            ("geekk3@gmail.com","Geek3",36,None),
            ("geekk4@gmail.com","Geek4",27,None),
            ("geekk5@gmail.com","Geek5",40,None),
            ("geekk6@gmail.com","Geek6",14,None),
            ("geekk7@gmail.com","Geek7",10,None)
        

• Changing the name of the table:

    Syntax:
            ALTER TABLE table_name RENAME TO newTableName;
        

We will use the same GEEK table that we created above:

    import sqlite3

    connection = sqlite3.connect('coding.db')
    cursor = connection.cursor()

    cursor.execute("SELECT * FROM sqlite_master")
    table = cursor.fetchall()
    print("Before changing the name of Table")
    print("The name of the table:", table[0][2])
    returns Before changing the name of Table
            The name of the table: GEEK

    renameTable = "ALTER TABLE GEEK RENAME TO CFG"
    cursor.execute(renameTable)
    cursor.execute("SELECT * FROM sqlite_master")
    table = cursor.fetchall()
    print("Before changing the name of Table")
    print("The name of the table:", table[0][2])
    returns Before changing the name of Table
            The name of the table: CFG

    connection.commit()
    connection.close()
        

Insert Image

How to insert images in SQLite using SQLite3

    import sqlite3

    def convertToBinaryData(filename):
        with open(filename, 'rb') as file:
            blobData = file.read()
        return blobData

    def insertBLOB(name, photo):
        try:
            connection = sqlite3.connect('SQLite_Retrieving_data.db') 
            cursor = connection.cursor()
            print("Connected to SQLite")

            sqlite_insert_blob_query = """ INSERT INTO Student (name, img) VALUES (?, ?)"""

            empPhoto = convertToBinaryData(photo)
            data_tuple = (name, empPhoto)

            cursor.execute(sqlite_insert_blob_query, data_tuple)
            connection.commit()
            
        except sqlite3.Error as error:
            print("Failed to insert blob data into sqlite table", error)

        finally:
            if connection:
                connection.close()
                print("the sqlite connection is closed")

    insertBLOB("Smith", "D:\Internship Tasks\GFG\images\One.png") 
    insertBLOB("David", "D:\Internship Tasks\GFG\images\person.png")

    cursor.execute("SELECT * FROM STUDENT")
    table = cursor.fetchall()
    print("table)
    returns (Smith, ?PNG)
            (David, ?PNG)
    
        

Read Image

How to read or retrieve images that are stored in the form of BLOB data type in an SQLite table.

    import sqlite3
    from PIL import Image 

    def convert_data(data, file_name):
        with open(file_name, 'wb') as file:
            file.write(data)
            img = Image.open(file_name)
            print(img)

    try:
        connection = sqlite3.connect('SQLite_Retrieving_data.db') 
        cursor = connection.cursor()
        print("Connected to SQLite")

        query = "SELECT * FROM Student"
        cursor.execute(query)
        records = cursor.fetchall()

        for row in records:
            name = row[0]
            print("Student Name = ", name)
            image = row[1]
            convert_data(image, "D:\Internship Tasks\GFG\sqlite\\" + name + ".png")
            print("Yeah!! We have successfully retrieved values from database")

        if len(records) == 0:
            print("Sorry! Please Insert some data before reading from the database.")

    except sqlite3.Error as error:
        print(format(error))

    finally:
        if connection:
            connection.close()
            print("the sqlite connection is closed")
        

MySQL

Python needs a MySQL driver to access the MySQL database. We will use the driver "MySQL Connector". We recommend that you use PIP to install "MySQL Connector".

Create Connection

Start by creating a connection to the database. Use the username and password from your MySQL database:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
    )
    print(mydb)
    returns mysql.connector.connection.MySQLConnection object ar 0x016645F0
        

Create a Database

• To create a database in MySQL, use the "CREATE DATABASE" statement:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
    )

    mycursor = mydb.cursor()
    mycursor.execute("CREATE DATABASE mydatabase")
        

• Check if a database exist by listing all databases in your system by using the "SHOW DATABASES" statement:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
    )

    mycursor = mydb.cursor()
    mycursor.execute("SHOW DATABASES")

    for x in cursor:
        print(x)
        

Create a Table

• To create a table in MySQL, use the "CREATE TABLE" statement. Make sure you define the name of the database when you create the connection:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    mytable = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))"
    mycursor.execute(mytable)
        

• Check if a table exist by listing all tables in your database with the "SHOW TABLES" statement:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    mycursor.execute("SHOW TABLES")

    for x in cursor:
        print(x)

    returns ('customers',)
        

• When creating a table, you should also create a column with a unique key for each record. This can be done by defining a PRIMARY KEY. We use the statement "INT AUTO_INCREMENT PRIMARY KEY" which will insert a unique number for each record. Starting at 1, and increased by one for each record.

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    mytable = "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))"
    mycursor.execute(mytable)
        

• If the table already exists, use the ALTER TABLE keyword:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    mytable = "ALTER TABLE customers (ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY)"
    mycursor.execute(mytable)
        

Insert Into Table

• To fill a table in MySQL, use the "INSERT INTO" statement.

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
    val = ("John", "Highway 21")
    mycursor.execute(sql, val)
    mydb.commit()

    print(mycursor.rowcount, "record inserted.")
    returns 1 record inserted.
        

Important: Notice the statement: mydb.commit(). It is required to make the changes, otherwise no changes are made to the table.

• To insert multiple rows into a table, use the executemany() method. The second parameter of the executemany() method is a list of tuples, containing the data you want to insert:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
    val = [
    ('Peter', 'Lowstreet 4'),
    ('Amy', 'Apple st 652'),
    ('Hannah', 'Mountain 21'),
    ('Michael', 'Valley 345'),
    ('Sandy', 'Ocean blvd 2'),
    ('Betty', 'Green Grass 1'),
    ('Richard', 'Sky st 331'),
    ('Susan', 'One way 98'),
    ('Vicky', 'Yellow Garden 2'),
    ('Ben', 'Park Lane 38'),
    ('William', 'Central st 954'),
    ('Chuck', 'Main Road 989'),
    ('Viola', 'Sideway 1633')
    ]

    mycursor.executemany(sql, val)
    mydb.commit()

    print(mycursor.rowcount, "was inserted.")
    returns 13 record was inserted.
        

• You can get the id of the row you just inserted by asking the cursor object.

Note: If you insert more than one row, the id of the last inserted row is returned.

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
    val = ("Michelle", "Blue Village")

    mycursor.execute(sql, val)
    mydb.commit()

    print("1 record inserted, ID:", mycursor.lastrowid)
    returns 1 record inserted, ID: 15
        

Select From a Table

• To select from a table in MySQL, use the "SELECT" statement:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    mycursor.execute("SELECT * FROM customers")

    myresult = mycursor.fetchall()

    for x in myresult:
        print(x)

    returns (1, 'John', 'Highway 21')
            (2, 'Peter', 'Lowstreet 27')
            (3, 'Amy', 'Apple st 652')
            (4, 'Hannah', 'Mountain 21')
            (5, 'Michael', 'Valley 345')
            (6, 'Sandy', 'Ocean blvd 2')
            (7, 'Betty', 'Green Grass 1')
            (8, 'Richard', 'Sky st 331')
            (9, 'Susan', 'One way 98')
            (10, 'Vicky', 'Yellow Garden 2')
            (11, 'Ben', 'Park Lane 38')
            (12, 'William', 'Central st 954')
            (13, 'Chuck', 'Main Road 989')
            (14, 'Viola', 'Sideway 1633')
            (15, 'Michelle', 'Blue Village')
        

Note: We use the fetchall() method, which fetches all rows from the last executed statement.

• To select only some of the columns in a table, use the "SELECT" statement followed by the column name(s):

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    mycursor.execute("SELECT name, address FROM customers")

    myresult = mycursor.fetchall()

    for x in myresult:
        print(x)

    returns (1, 'John', 'Highway 21')
            (2, 'Peter', 'Lowstreet 27')
            (3, 'Amy', 'Apple st 652')
            (4, 'Hannah', 'Mountain 21')
            (5, 'Michael', 'Valley 345')
            (6, 'Sandy', 'Ocean blvd 2')
            (7, 'Betty', 'Green Grass 1')
            (8, 'Richard', 'Sky st 331')
            (9, 'Susan', 'One way 98')
            (10, 'Vicky', 'Yellow Garden 2')
            (11, 'Ben', 'Park Lane 38')
            (12, 'William', 'Central st 954')
            (13, 'Chuck', 'Main Road 989')
            (14, 'Viola', 'Sideway 1633')
            (15, 'Michelle', 'Blue Village')
        

• If you are only interested in one row, you can use the fetchone() method. The fetchone() method will return the first row of the result:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    mycursor.execute("SELECT * FROM customers")

    myresult = mycursor.fetchone()

    print(myresult)

    returns (1, 'John', 'Highway 21')
        

Select With a Filter

• When selecting records from a table, you can filter the selection by using the "WHERE" statement:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    sql = "SELECT * FROM customers WHERE address = %s"
    adr = ('Park Lane 38', )

    mycursor.execute(sql, adr)
    myresult = mycursor.fetchall()

    for x in myresult:
        print(x)

    returns (1, 'John', 'Highway 21')
            (9, 'Susan', 'One way 98')
            (14, 'Viola', 'Sideway 1633')
        

Note: When query values are provided by the user, you should escape the values. This is to prevent SQL injections, which is a common web hacking technique to destroy or misuse your database.

• You can also select the records that starts, includes, or ends with a given letter or phrase. Use the % to represent wildcard characters:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    sql = "SELECT * FROM customers WHERE address LIKE %s"
    adr = ('%way%', )

    mycursor.execute(sql, adr)
    myresult = mycursor.fetchall()

    for x in myresult:
        print(x)

    returns (1, 'John', 'Highway 21')
            (9, 'Susan', 'One way 98')
            (14, 'Viola', 'Sideway 1633')
        

Sort the Result

• Use the ORDER BY statement to sort the result in ascending or descending order. The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the DESC keyword.

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    sql = "SELECT * FROM customers ORDER BY name"

    mycursor.execute(sql)
    myresult = mycursor.fetchall()

    for x in myresult:
        print(x)

    returns (3, 'Amy', 'Apple st 652')
            (11, 'Ben', 'Park Lane 38')
            (7, 'Betty', 'Green Grass 1')
            (13, 'Chuck', 'Main Road 989')
            (4, 'Hannah', 'Mountain 21')
            (1, 'John', 'Highway 21')
            (5, 'Michael', 'Valley 345')
            (15, 'Michelle', 'Blue Village') 
            (2, 'Peter', 'Lowstreet 27')
            (8, 'Richard', 'Sky st 331')
            (6, 'Sandy', 'Ocean blvd 2')
            (9, 'Susan', 'One way 98')
            (10, 'Vicky', 'Yellow Garden 2')
            (14, 'Viola', 'Sideway 1633')
            (12, 'William', 'Central st 954')
        

• Use the DESC keyword to sort the result in descending order.

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    sql = "SELECT * FROM customers ORDER BY name DESC"

    mycursor.execute(sql)
    myresult = mycursor.fetchall()

    for x in myresult:
        print(x)

    returns (12, 'William', 'Central st 954') 
            (14, 'Viola', 'Sideway 1633')
            (10, 'Vicky', 'Yellow Garden 2')
            (9, 'Susan', 'One way 98')
            (6, 'Sandy', 'Ocean blvd 2')
            (8, 'Richard', 'Sky st 331')
            (2, 'Peter', 'Lowstreet 27')
            (15, 'Michelle', 'Blue Village') 
            (5, 'Michael', 'Valley 345')
            (1, 'John', 'Highway 21')
            (4, 'Hannah', 'Mountain 21')
            (13, 'Chuck', 'Main Road 989')
            (7, 'Betty', 'Green Grass 1')
            (11, 'Ben', 'Park Lane 38')
            (3, 'Amy', 'Apple st 652')
        

Delete Record

• You can delete records from an existing table by using the "DELETE FROM" statement:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    sql = "DELETE FROM customers WHERE address = %s"
    val = ('Mountain 21', )
    mycursor.execute(sql, val)

    mydb.commit()

    print(mycursor.rowcount, "record(s) deleted")

    returns 1 record(s) deleted
        

Note: Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record(s) that should be deleted. If you omit the WHERE clause, all records will be deleted!

Delete a Table

• ou can delete an existing table by using the "DROP TABLE" statement:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()sql = "DROP TABLE customers"
    mycursor.execute(sql)
        

• If the table you want to delete is already deleted, or for any other reason does not exist, you can use the IF EXISTS keyword to avoid getting an error.

    import mysql.connector
    
    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()

    sql = "DROP TABLE IF EXISTS customers"
    mycursor.execute(sql)
        

Update Table

• You can update existing records in a table by using the "UPDATE" statement:

    import mysql.connector
    
    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()

    sql = "UPDATE customers SET address = %s WHERE address = %s"
    val = ("Valley 345", "Canyon 123")
    mycursor.execute(sql, val)

    mydb.commit()

    print(mycursor.rowcount, "record(s) affected")
    returns 1 record(s) affected
        

Note: Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!

Limit the Result

• You can limit the number of records returned from the query, by using the "LIMIT" statement:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()

    mycursor.execute("SELECT * FROM customers LIMIT 5")
    myresult = mycursor.fetchall()

    for x in cursor:
        print(x)
    returns (1, 'John', 'Highway 21')
            (2, 'Peter', 'Lowstreet 27')
            (3, 'Amy', 'Apple st 652')
            (4, 'Hannah', 'Mountain 21')
            (5, 'Michael', 'Valley 345')
        

• If you want to return five records, starting from the third record, you can use the "OFFSET" keyword:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()

    mycursor.execute("SELECT * FROM customers LIMIT 5 OFFSET 2")
    myresult = mycursor.fetchall()

    for x in cursor:
        print(x)
    returns (3, 'Amy', 'Apple st 652')
            (4, 'Hannah', 'Mountain 21')
            (5, 'Michael', 'Valley 345')
            (6, 'Sandy', 'Ocean blvd 2')
            (7, 'Betty', 'Green Grass 1')
        

Join Two or More Tables

• You can combine rows from two or more tables, based on a related column between them, by using a JOIN statement.
Create two tables and insert some data:

    import mysql.connector
    
    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    table1 = "CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), fav VARCHAR(255))"
    table2 = "CREATE TABLE products (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255))"
    mycursor.execute(table1, table2)

    sql1 = "INSERT INTO users (name, fav) VALUES (%s, %s)"
    val1 = [
        ('John', 154)
        ('Peter', 154)
        ('Amy', 155)
        ('Hannah', 0,)
        ('Michael', 0)
        ]
        mycursor.executemany(sql1, val1)

    sql2 = "INSERT INTO products (id, name) VALUES (%s, %s)"
    val1 = [
        (154, 'Chocolate Heaven'),
        (155, 'Tasty Lemons'),
        (156, 'Vanilla Dreams')
        ]
        mycursor.executemany(sql2, val2)

        mydb.commit()
        

• These two tables can be combined by using users' fav field and products' id field.

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    
    sql = "SELECT users.name AS user, products.name AS favorite FROM users INNER JOIN products ON users.fav = products.id"

    mycursor.execute(sql)
    myresult = mycursor.fetchall()

    for x in cursor:
        print(x)
    returns ('John', 'Chocolate Heaven')
            ('Peter', 'Chocolate Heaven')
            ('Amy', 'Tasty Lemon')
        

Note: You can use JOIN instead of INNER JOIN. They will both give you the same result. INNER JOIN only shows the records where there is a match.

• If you want to show all users, even if they do not have a favorite product, use the LEFT JOIN statement:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    
    sql = "SELECT users.name AS user, products.name AS favorite FROM users LEFT JOIN products ON users.fav = products.id"

    mycursor.execute(sql)
    myresult = mycursor.fetchall()

    for x in cursor:
        print(x)
    returns ('John', 'Chocolate Heaven')
            ('Peter', 'Chocolate Heaven')
            ('Amy', 'Tasty Lemon')
            ('Hannah', None)
            ('Michael', None)
        

• If you want to return all products, and the users who have them as their favorite, even if no user have them as their favorite, use the RIGHT JOIN statement:

    import mysql.connector

    mydb = mysql.connector.connect(
        host="localhost",
        user="yourusername",
        password="yourpassword"
        database="mydatabase"
    )

    mycursor = mydb.cursor()
    
    sql = "SELECT users.name AS user, products.name AS favorite FROM users RIGHT JOIN products ON users.fav = products.id"

    mycursor.execute(sql)
    myresult = mycursor.fetchall()

    for x in cursor:
        print(x)
    returns ('John', 'Chocolate Heaven')
            ('Peter', 'Chocolate Heaven')
            ('Amy', 'Tasty Lemon')
            (None, 'Vanilla Dreams')
        

21. Graphical User Interface

TKinter

Introduction

Tkinter is a standard Python GUI (Graphical User Interface) library that provides a set of tools and widgets to create desktop applications with graphical interfaces. Tkinter is included with most Python installations, making it easily accessible for developers who want to build GUI applications without requiring additional installations or libraries. The name “Tkinter” comes from “Tk interface“, referring to the Tk GUI toolkit that Tkinter is based on. Tkinter provides a way to create windows, buttons, labels, text boxes, and other GUI components to build interactive applications.

Create Tkinter GUI Application

• To create a Tkinter Python app, follow these basic steps:
1. Import the tkinter module: Import the tkinter module, which is necessary for creating the GUI components.
2. Create the main window (container): Initialize the main application window using the tk() class.
3. Set Window Properties: We can set properties like the title and size of the window.
4. Add widgets to the main window: We can add any number of widgets like buttons, labels, entry fields, etc., to the main window to design the interface.
5. Pack Widgets: Use geometry managers like pack(), grid() or place() to arrange the widgets within the window.
6. Apply event triggers to the widgets: We can attach event triggers to the widgets to define how they respond to user interactions.

    # Import Module
    import tkinter
    
    # Create Main Window
    root = tk()

    # Set Window Properties
    root.title(main_title)
    window_widths = 800
    window_height = 400

    # Add and Pack Widgets
    heading = Label(root, text='My First App')
    heading.grid(row=0, column=0)
    my_entry = Entry(root, show="*", width=32, fg='red')
    my_entry.grid(row=1, column=0, pady=10)
    submit_button = Button(root, text="Submit", command=submit_entry)
    submit_button.grid(row=2, column=0, pady=10, padx=15)

    # Create Event Triggers
    def change_cursor_to_hand(event):
    my_entry.config(cursor="hand2")

    def reset_cursor(event):
    my_entry.config(cursor="xterm")

    my_entry.bind("<Enter>", change_cursor_to_hand)
    my_entry.bind("<Leave>", reset_cursor)
        

• There are two main methods used which the user needs to remember while creating the Python application with GUI.
▸ 1. tk()
To create a main window in Tkinter, we use the tk() class. The syntax for creating a main window is as follows:

    root = tk.Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)
        

→ screenName: This parameter is used to specify the display name.
⇉ baseName: This parameter can be used to set the base name of the application.
⇶ useTk: This parameter indicates whether to use Tk or not.

▸ 2. mainloop()
The mainloop() method is used to run application once it is ready. It is an infinite loop that keeps the application running, waits for events to occur (such as button clicks) and processes these events as long as the window is not closed.

    import tkinter
    root = tkinter.tk()
    '''
    widgets are added here
    '''
    root.mainloop()
        

Note: Use root.quit() to close the mainloop()

Close a window in Tkinter

To close a tkinter window, we can use the destroy() method. The destroy() is a universal widget method i.e. we can use this method with any of the available widgets as well as with the main tkinter window:

    from tkinter import *
    
    root = tkinter.tk()

    Button(root, text="Quit", command=root.destroy).pack()
    root.mainloop()
        

Widgets

In Tkinter we have fundamental building blocks called widgets. From simple frames and labels to more complex elements like scrollable frames and treeviews, we’ll cover a wide range of widgets and their customization options.

Label

Label is a widget that is used to implement display boxes where you can place text or images.

    Syntax: Label ( master, option )

    • master: This represents the parent window
    • options: Below is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
        

Label options

Option Description
anchor This option is used to control the positioning of the text if the widget has more space than required for the text. The default is anchor=CENTER, which centers the text in the available space.
bg This option is used to set the normal background color displayed behind the label and indicator.
height This option is used to set the vertical dimension of the new frame.
width Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents.
bd This option is used to set the size of the border around the indicator. Default bd value is set on 2 pixels.
font If you are displaying text in the label (with the text or textvariable option), the font option is used to specify in what font that text in the label will be displayed.
cursor It is used to specify what cursor to show when the mouse is moved over the label. The default is to use the standard cursor.
textvariable As the name suggests it is associated with a Tkinter variable (usually a StringVar) with the label. If the variable is changed, the label text is updated.
bitmap It is used to set the bitmap to the graphical object specified so that, the label can represent the graphics instead of text.
fg The label clior, used for text and bitmap labels. The default is system specific. If you are displaying a bitmap, this is the clior that will appear at the position of the 1-bits in the bitmap.
image This option is used to display a static image in the label widget.
padx This option is used to add extra spaces between left and right of the text within the label.The default value for this option is 1.
pady This option is used to add extra spaces between top and bottom of the text within the label.The default value for this option is 1.
justify This option is used to define how to align multiple lines of text. Use LEFT, RIGHT, or CENTER as its values. Note that to position the text inside the widget, use the anchor option. Default value for justify is CENTER.
relief This option is used to specify appearance of a decorative border around the label. The default value for this option is FLAT.
underline This will underline the text.
wraplength Instead of having only one line as the label text it can be broken into to the number of lines where each line has the number of characters specified to this option.

Example:

    from tkinter import * 

    root = tk()
    root.geometry("400x250")
    root.title("Welcome to My App")

    # Create a StringVar to associate with the label
    text_var = StringVar()
    text_var.set("Hello, World!")

    # Create the label widget with all options
    label = Label(root, 
                 textvariable=text_var, 
                 anchor=CENTER,       
                 bg="lightblue",      
                 height=3,              
                 width=30,              
                 bd=3,                  
                 font=("Arial", 16, "bold"), 
                 cursor="hand2",   
                 fg="red",             
                 padx=15,               
                 pady=15,                
                 justify=CENTER,    
                 relief=RAISED,     
                 underline=0,           
                 wraplength=250         
                )
    label.pack(pady=20)

    root.mainloop()
        

Button

The Button widget is a graphical control element used to create clickable buttons in a graphical user interface (GUI). It provides a way for users to trigger actions or events when clicked.

    Syntax: Button(parent, options) 

    • parent: This parameter is used to represents the parent window.
    • options:There are many options which are available and they can be used as key-value pairs separated by commas.
        

Button Options

Option Description
activebackground Background color when the button is under the cursor.
activeforeground Foreground color when the button is under the cursor.
anchor Anchor position for text or image on the button.
bd or borderwidth Width of the border around the outside of the button.
bg or background Normal background color.
command Function or method to be called when the button is clicked.
cursor Selects the cursor to be shown when the mouse is over the button.
text Text displayed on the button.
disabledforeground Foreground color used when the button is disabled.
fg or foreground Normal foreground (text) color.
font Text font to be used for the button’s label.
height Height of the button in text lines.
highlightbackground Color of the focus highlight when the widget does not have focus.
highlightcolor Color of the focus highlight when the widget has focus.
highlightthickness Thickness of the focus highlight.
image Image to be displayed on the button (instead of text).
justify Aligns multiple lines of text: LEFT, CENTER, or RIGHT.
overrelief The relief style when the mouse is on the button; default is RAISED.
padx, pady Padding left/right and top/bottom of the button.
width Width of the button in characters or pixels.
underline Index of character to underline; -1 for none.
wraplength Wraps text lines to fit within this length.

Methods:

Example using TK:

    from tkinter import * 

    root = tk()
    root.geometry("400x250")
    root.title("Welcome to My App")

    def button_clicked():
        print("Button clicked!")

    my_button = Button(root, 
            text="Click Me", 
            command=button_clicked,
            activebackground="blue", 
            activeforeground="white",
            anchor="center",
            bd=3,
            bg="lightgray",
            cursor="hand2",
            disabledforeground="gray",
            fg="black",
            font=("Arial", 12),
            height=2,
            highlightbackground="black",
            highlightcolor="green",
            highlightthickness=2,
            justify="center",
            overrelief="raised",
            padx=10,
            pady=5,
            width=15,
            wraplength=100)

    button.pack(padx=20, pady=20)

    root.mainloop()
        

Example using TK Themed Widget:
Creation of Button using tk themed widget (tkinter.ttk). This will give you the effects of modern graphics.

    from tkinter import * 
    from tkinter.ttk import * 

    root = tk()
    root.geometry("100x100")

    btn = Button(root, text = 'Click me !', command = root.destroy)
    btn.pack(side = 'top') 
    
    root.mainloop() 
        

Entry

The Entry Widget is a Tkinter Widget used to Enter or display a single line of text.

    Syntax : entry = Entry(parent, options)

    • Parent: The Parent window or frame in which the widget to display.
    • Options: The various options provided by the entry widget are:
        

Entry Options

Option Description
bg The normal background color displayed behind the label and indicator.
bd The size of the border around the indicator. Default is 2 pixels.
font The font used for the text.
fg The color used to render the text.
justify If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT.
relief With the default value, relief=FLAT. You may set this option to any of the other styles like : SUNKEN, RIGID, RAISED, GROOVE.
show Normally, the characters that the user types appear in the entry. To make a .password. entry that echoes each character as an asterisk, set show='*'.
textvariable In order to be able to retrieve the current text from your entry widget, you must set this option to an instance of the StringVar class.

Methods:

Example:

    from tkinter import *

    root = tk()
    root.geometry("600x400")

    # declaring string variable for storing name and password
    name_var=StringVar()
    passw_var=StringVar()

    # defining a function that will get the name and password and print them on the screen
    def submit():
        name = name_var.get()
        password = passw_var.get()
        print("The name is : " + name)
        print("The password is : " + password)

    # creating a label for name and password, a entry for input name and password
    name_label = Label(root, text = 'Username', font=('calibre',10, 'bold'))
    name_entry = Entry(root,textvariable = name_var, font=('calibre',10,'normal'))

    passw_label = Label(root, text = 'Password', font = ('calibre',10,'bold'))
    passw_entry = Entry(root, textvariable = passw_var, font = ('calibre',10,'normal'), show = '*')

    creating a button that will call the submit function
    sub_btn = Button(root,text = 'Submit', command = submit)
    
    # placing the label and entry in the required position using grid method
    name_label.grid(row=0,column=0)
    name_entry.grid(row=0,column=1)
    passw_label.grid(row=1,column=0)
    passw_entry.grid(row=1,column=1)
    sub_btn.grid(row=2,column=1)

    root.mainloop()

    returns The name is : User1
            The password is : MyPassword
        

Frame

A frame is a rectangular region on the screen. A frame can also be used as a foundation class to implement complex widgets. It is used to organize a group of widgets.

    Syntax: w = frame( master, options)

    • master: This parameter is used to represent the parent window.
    • options: There are many options which are available and they can be used as key-value pairs separated by commas:
        

Frame Options

Option Description
bg This option used to represent the normal background color displayed behind the label and indicator.
bd This option used to represent the size of the border around the indicator and the default value is 2 pixels.
cursor By using this option, the mouse cursor will change to that pattern when it is over the frame.
height The vertical dimension of the new frame.
highlightcolor This option used to represent the color of the focus highlight when the frame has the focus.
highlightthickness This option used to represent the color of the focus highlight when the frame does not have focus.
highlightbackground This option used to represent the thickness of the focus highlight.
relief The type of the border of the frame. It’s default value is set to FLAT.
width This option used to represents the width of the frame.

Example:

    from tkinter import *

    def create_widget(parent, widget_type, **options):
        return widget_type(parent, **options)

    window = tk()
    window.title("GUI Frame Example")

    # Create a Frame widget with all options
    frame = create_widget(window, Frame, bg='lightblue', bd=3, cursor='hand2', height=100, 
                          highlightcolor='red', highlightthickness=2, highlightbackground='black', 
                          relief=RAISED, width=200)
    frame.pack(padx=20, pady=20)

    # Create Label widget with all options
    label = create_widget(frame, Label, text='GeeksForGeeks', font='50', bg='lightblue', bd=3, cursor='hand2',
                          highlightcolor='red', highlightthickness=2, highlightbackground='black', relief=RAISED)
    label.pack()

    # Create a frame for buttons
    button_frame = create_widget(window, Frame, bg='lightblue', bd=3, cursor='hand2', height=50, 
                                 highlightcolor='red', highlightthickness=2, highlightbackground='black', 
                                 relief=RAISED, width=200)
    button_frame.pack(pady=10)

    def create_button(parent, text, fg):
        return create_widget(parent, Button, text=text, fg=fg, bg='lightblue', 
                             bd=3, cursor='hand2', highlightcolor='red', highlightthickness=2, highlightbackground='black', 
                             relief=RAISED)

    # Create buttons
    buttons_info = [("Geeks1", "red"), ("Geeks2", "brown"), ("Geeks3", "blue"), 
                    ("Geeks4", "green"), ("Geeks5", "green"), ("Geeks6", "green")]

    for text, fg in buttons_info:
        button = create_button(button_frame, text=text, fg=fg)
        button.pack(side=tk.LEFT)

    window.mainloop()
        

Checkbutton

The Checkbutton widget is a standard Tkinter widget that is used to implement on/off selections. Checkbuttons can contain text or images. When the button is pressed, Tkinter calls that function or method.

    Syntax: Checkbutton ( master, options)

    • This parameter is used to represents the parent window.
    • here are many options which are available and they can be used as key-value pairs separated by commas:
        

Checkbutton Options

Option Description
activebackground This option used to represent the background color when the checkbutton is under the cursor.
activeforeground This option used to represent the foreground color when the checkbutton is under the cursor.
bg This option used to represent the normal background color displayed behind the label and indicator.
bitmap This option used to display a monochrome image on a button.
bd This option used to represent the size of the border around the indicator and the default value is 2 pixels.
command This option is associated with a function to be called when the state of the checkbutton is changed.
cursor By using this option, the mouse cursor will change to that pattern when it is over the checkbutton.
disabledforeground The foreground color used to render the text of a disabled checkbutton. The default is a stippled version of the default foreground color.
font This option used to represent the font used for the text.
fg This option used to represent the color used to render the text.
height This option used to represent the number of lines of text on the checkbutton and it’s default value is 1.
highlightcolor This option used to represent the color of the focus highlight when the checkbutton has the focus.
image This option used to display a graphic image on the button.
justify This option used to control how the text is justified
offvalue The associated control variable is set to 0 by default if the button is unchecked. We can change the state of an unchecked variable to some other one.
onvalue The associated control variable is set to 1 by default if the button is checked. We can change the state of the checked variable to some other one.
padx This option used to represent how much space to leave to the left and right of the checkbutton and text. It’s default value is 1 pixel.
pady This option used to represent how much space to leave above and below the checkbutton and text. It’s default value is 1 pixel.
relief The type of the border of the checkbutton. It’s default value is set to FLAT.
selectcolor This option used to represent the color of the checkbutton when it is set. The Default is selectcolor=”red”.
selectimage The image is shown on the checkbutton when it is set.
state It represents the state of the checkbutton. By default, it is set to normal. We can change it to DISABLED to make the checkbutton unresponsive. The state of the checkbutton is ACTIVE when it is under focus.
text This option used use newlines (“ ”) to display multiple lines of text.
underline This option used to represent the index of the character in the text which is to be underlined. The indexing starts with zero in the text.
variable This option used to represents the associated variable that tracks the state of the checkbutton.
width This option used to represents the width of the checkbutton. and also represented in the number of characters that are represented in the form of texts.
wraplength This option will be broken text into the number of pieces.

Methods:

Example:

    from tkinter import *

    root = tk()

    def on_button_toggle():
        if var.get() == 1:
            print("Checkbutton is selected")
        else:
            print("Checkbutton is deselected")

    # Creating a Checkbutton
    var = IntVar()
    checkbutton = Checkbutton(root, text="Enable Feature", variable=var, onvalue=1, offvalue=0, command=on_button_toggle)
    checkbutton.config(bg="lightgrey", fg="blue", font=("Arial", 12), selectcolor="green", relief="raised", padx=10, pady=5)
    checkbutton.config(bitmap="info", width=20, height=2)
    checkbutton.pack(padx=40, pady=40)

    checkbutton.flash()

    root.mainloop()
        

Example for Multiple Checkbuttons for Selection:

    from tkinter import *

    root = tk()
    root.geometry("300x200")

    w = Label(root, text ='CodingForGeeks', font = "50") 
    w.pack()

    checkbox_labels = ["Tutorial", "Student", "Courses"]
    checkbox_vars = []

    for text in checkbox_labels:
        var = IntVar()
        checkbox_vars.append(var)
        checkbox = Checkbutton(root, text=text, variable=var, onvalue=1, offvalue=0, height=2, width=10)
        checkbox.pack()

    root.mainloop()
        

Radiobutton

The Radiobutton is a standard Tkinter widget used to implement one-of-many selections. Radiobuttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter automatically calls that function or method.

    Syntax: button = Radiobutton(master, text=”Name on Button”, variable = “shared variable”, value = “values of each button”, options = values, …)

    • shared variable = A Tkinter variable shared among all Radio buttons
    • value = each radiobutton should have different value otherwise more than 1 radiobutton will get selected.
        

Example1: Buttonbox

    from tkinter import *

    root = tk()
    root.geometry("175x175")

    v = StringVar(root, "1")

    # Dictionary to create multiple buttons
    values = {"RadioButton 1" : "1",
              "RadioButton 2" : "2",
              "RadioButton 3" : "3",
              "RadioButton 4" : "4",
              "RadioButton 5" : "5"}

    for (text, value) in values.items():
        Radiobutton(root, text = text, variable = v, value = value, indicator = 0,
                    background = "light blue").pack(fill = X, ipady = 5)

    root.mainloop()
        

Example2: Standard Radio Buttons

    from tkinter import *
    from tkinter.ttk import *

    root = tk()
    root.geometry("175x175")

    v = StringVar(root, "1")

    # Dictionary to create multiple buttons
    values = {"RadioButton 1" : "1",
              "RadioButton 2" : "2",
              "RadioButton 3" : "3",
              "RadioButton 4" : "4",
              "RadioButton 5" : "5"}

    for (text, value) in values.items():
        Radiobutton(root, text = text, variable = v, value = value).pack(fill = X, ipady = 5)

    root.mainloop()
        

Example3: Adding Style to Radio Buttons

    from tkinter import *
    from tkinter.ttk import *
    
    root = Tk()
    root.geometry("175x175")

    v = StringVar(root, "1")

    style = Style(root)
    style.configure("TRadiobutton", background = "light green", foreground = "red", font = ("arial", 10, "bold"))

    # Dictionary to create multiple buttons
    values = {"RadioButton 1" : "1",
              "RadioButton 2" : "2",
              "RadioButton 3" : "3",
              "RadioButton 4" : "4",
              "RadioButton 5" : "5"}

    for (text, value) in values.items():
        Radiobutton(root, text = text, variable = v, value = value).pack(fill = X, ipady = 5)

    root.mainloop()
        

Listbox

The ListBox widget is used to display different types of items. These items must be of the same type of font and having the same font color. The items must also be of Text type. The user can select one or more items from the given list according to the requirement.

            Syntax: listbox = Listbox(root, bg, fg, bd, height, width, font, ..)
        

Optional Parameters:

Methods:

Example:

    from tkinter import *

    root = tk()
    root.geometry("300x250")

    # create listbox object
    listbox = Listbox(root, height = 10, width = 15, bg = "grey", activestyle = 'dotbox', font = "Helvetica", fg = "yellow")

    label = Label(root, text = " FOOD ITEMS")

    # insert elements by their index and names.
    food_items = ["Nachos", "Sandwich", "Burger", "Pizza", "Burrito"]

    for index, item in enumerate(food_items, start=1):
        listbox.insert(index, item)

    label.pack()
    listbox.pack()

    root.mainloop()
        

Delete the elements from the above created listbox:

    from tkinter import *

    root = tk()
    root.geometry("300x250")

    # create listbox object
    listbox = Listbox(root, height = 10, width = 15, bg = "grey", activestyle = 'dotbox', font = "Helvetica", fg = "yellow")

    label = Label(root, text = " FOOD ITEMS")

    # insert elements by their index and names.
    food_items = ["Nachos", "Sandwich", "Burger", "Pizza", "Burrito"]

    for index, item in enumerate(food_items, start=1):
        listbox.insert(index, item)

    label.pack()
    listbox.pack()

    listbox.delete(2)

    root.mainloop()
        

Scrollbar

The scrollbar widget is used to scroll down the content.

    Syntax: w = Scrollbar(master, options)

    • master: This parameter is used to represents the parent window.
    • options: There are many options which are available and they can be used as key-value pairs separated by commas:
        

Scrollbar Options

Option Description
activebackground This option is used to represent the background color of the widget when it has the focus.
bg This option is used to represent the background color of the widget.
bd This option is used to represent the border width of the widget.
command This option can be set to the procedure associated with the list which can be called each time when the scrollbar is moved.
cursor In this option, the mouse pointer is changed to the cursor type set to this option which can be an arrow, dot, etc.
elementborderwidth This option is used to represent the border width around the arrow heads and slider. The default value is -1.
Highlightbackground This option is used to focus highlighcolor when the widget doesn’t have the focus.
highlighcolor This option is used to focus highlighcolor when the widget has the focus.
highlightthickness This option is used to represent the thickness of the focus highlight.
jump This option is used to control the behavior of the scroll jump. If it set to 1, then the callback is called when the user releases the mouse button.
orient This option can be set to HORIZONTAL or VERTICAL depending upon the orientation of the scrollbar.
repeatdelay This option tells the duration up to which the button is to be pressed before the slider starts moving in that direction repeatedly. The default is 300 ms.
repeatinterval The default value of the repeat interval is 100.
takefocus You can tab the focus through a scrollbar widget.
troughcolor This option is used to represent the color of the trough.
width This option is used to represent the width of the scrollbar.

Methods:

Example:

    from tkinter import *

    root = tk()
    root.geometry("150x200") 
   
    w = Label(root, text ='CodingForGeeks', font = "50")  
    w.pack() 

    scroll_bar = Scrollbar(root) 
    scroll_bar.pack( side = RIGHT, fill = Y) 

    mylist = Listbox(root, yscrollcommand = scroll_bar.set)
    
    for line in range(1, 26):
        mylist.insert(END, "Geeks " + str(line))
    mylist.pack( side = LEFT, fill = BOTH)
    
    scroll_bar.config( command = mylist.yview) 

    root.mainloop()
        

Menus are the important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data.

    Syntax: menu = Menu(master, **options)

    • master: This represents the parent window.
    • options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas:
        

Menu Options

Option Description
activebackground The background color that will appear on a choice when it is under the mouse.
activeborderwidth Specifies the width of a border drawn around a choice when it is under the mouse. Default is 1 pixel.
activeforeground The foreground color that will appear on a choice when it is under the mouse.
Bg The background color for choices not under the mouse.
Bd The width of the border around all the choices. Default is 1.
Cursor The cursor that appears when the mouse is over the choices, but only when the menu has been torn off.
disabledforeground The color of the text for items whose state is DISABLED.
Font The default font for textual choices.
Fg The foreground color used for choices not under the mouse.
Postcommand You can set this option to a procedure, and that procedure will be called every time someone brings up this menu.
Relief The default 3-D effect for menus is relief=RAISED.
Image To display an image on this menubutton.
Selectcolor Specifies the color displayed in checkbuttons and radiobuttons when they are selected.
Tearoff Normally, a menu can be torn off, the first position (position 0) in the list of choices is occupied by the tear-off element, and the additional choices are added starting at position 1. If you set tearoff=0, the menu will not have a tear-off feature, and choices will be added starting at position 0.
Title Normally, the title of a tear-off menu window will be the same as the text of the menubutton or cascade that lead to this menu. If you want to change the title of that window, set the title option to that string.

Methods:

Example:

    from tkinter import *
    from tkinter.ttk import *
    from time import strftime

    root = tk()
    root.title('Menu Demonstration')

    # Creating Menubar
    menubar = Menu(root)

    # Adding File Menu and commands
    file = Menu(menubar, tearoff = 0) 
    menubar.add_cascade(label ='File', menu = file) 
    file.add_command(label ='New File', command = None) 
    file.add_command(label ='Open...', command = None) 
    file.add_command(label ='Save', command = None) 
    file.add_separator() 
    file.add_command(label ='Exit', command = root.destroy) 

    # Adding Edit Menu and commands
    edit = Menu(menubar, tearoff = 0) 
    menubar.add_cascade(label ='Edit', menu = edit) 
    edit.add_command(label ='Cut', command = None) 
    edit.add_command(label ='Copy', command = None) 
    edit.add_command(label ='Paste', command = None) 
    edit.add_command(label ='Select All', command = None) 
    edit.add_separator() 
    edit.add_command(label ='Find...', command = None) 
    edit.add_command(label ='Find again', command = None) 

    # Adding Help Menu
    help_ = Menu(menubar, tearoff = 0) 
    menubar.add_cascade(label ='Help', menu = help_) 
    help_.add_command(label ='Tk Help', command = None) 
    help_.add_command(label ='Demo', command = None) 
    help_.add_separator() 
    help_.add_command(label ='About Tk', command = None) 

    # display Menu
    root.config(menu = menubar)

    root.mainloop()
        

Note: In above application, commands are set to None but one may add different commands to different labels to perform the required task.

Canvas

The Canvas widget lets us display various graphics on the application. It can be used to draw simple shapes to complicated graphs. We can also display various kinds of custom widgets according to our needs.

    Syntax: C = Canvas(root, height, width, bd, bg, ..)
        

Canvas Options

Option Description
root root window.
height height of the canvas widget.
width width of the canvas widget.
bg background colour for canvas.
bd border of the canvas window.
scrollregion (w, n, e, s)tuple defined as a region for scrolling left, top, bottom and right.
highlightcolor colour shown in the focus highlight.
cursor It can be defined as a cursor for the canvas which can be a circle, a do, an arrow etc.
confine decides if canvas can be accessed outside the scroll region.
relief type of the border which can be SUNKEN, RAISED, GROOVE and RIDGE.

Some common drawing methods:
• Creating an Oval

oval = C.create_oval(x0, y0, x1, y1, options)

• Creating an Arc

arc = C.create_arc(20, 50, 190, 240, start=0, extent=110, fill="red")

• Creating a Line

line = C.create_line(x0, y0, x1, y1, ..., xn, yn, options)

• Creating an Polygon

polygon = C.create_polygon(x0, y0, x1, y1, ...xn, yn, options)

Example 1: Simple Shapes Drawing

    from tkinter import *

    root = tk()

    C = Canvas(root, bg="yellow", height=250, width=300)

    line = C.create_line(108, 120, 320, 40, fill="green")
    arc = C.create_arc(180, 150, 80, 210, start=0, extent=220, fill="red")
    oval = C.create_oval(80, 30, 140, 150, fill="blue")
    C.pack()

    root.mainloop()
        

Example 2: Simple Paint App

    from tkinter import *

    root = tk()
    root.geometry("500x350")
    root.title("Paint App")

    # define function when  mouse double click is enabled
    def paint(event):
    # Co-ordinates
        x1, y1, x2, y2 = ( event.x - 3 ),( event.y - 3 ), ( event.x + 3 ),( event.y + 3 ) 
    # Colour
        Colour = "#000fff000"
    # specify type of display
        w.create_line( x1, y1, x2, y2, fill = Colour )

    # create canvas widget
    w = Canvas(root, width = 400, height = 250)

    # call function when double click is enabled.
    w.bind("<B1-Motion>", paint)

    l = Label( root, text = "Double Click and Drag to draw." )
    l.pack()
    w.pack()

    root.mainloop()
        

Moving objects using Canvas.move() method:

    Syntax: Canvas.move(canvas_object, x, y) 

    Parameters:
	    • canvas_object: Any valid image or drawing created with the help of Canvas class.
        • x: Horizontal distance from upper-left corner. 
        • y: Vertical distance from upper-left corner.
        

Example:

    from tkinter import *

    class MoveCanvas(Canvas):
        def __init__(cvs, *args, **kwargs):
            super().__init__(*args, **kwargs)

            cvs.dx, cvs.dy = 0, 0
    
            cvs.box = self.create_rectangle(0, 0, 10, 10, fill="black")
    
            cvs.dt = 25
            cvs.tick()

        def tick(cvs):
            cvs.move(cvs.box, cvs.dx, cvs.dy)
            cvs.after(self.dt, self.tick)

        def change_heading(cvs, dx, dy):
            cvs.dx = dx
            cvs.dy = dy

    if __name__ == "__main__":
        root = Tk()
        root.geometry("300x300")
 
        cvs = MoveCanvas(root)
        cvs.pack(fill="both", expand=True)
    
        ds = 3
    
        root.bind("<KeyPress-Left>", lambda _: cvs.change_heading(-ds, 0))
        root.bind("<KeyPress-Right>", lambda _: cvs.change_heading(ds, 0))
        root.bind("<KeyPress-Up>", lambda _: cvs.change_heading(0, -ds))
        root.bind("<KeyPress-Down>", lambda _: cvs.change_heading(0, ds))
        
        root.mainloop()
        

Combobox

Combobox is a combination of Listbox and an entry field. It is one of the Tkinter widgets where it contains a down arrow to select from a list of options.

    Syntax: combobox = Combobox(master, option=value, ...)
        

Example 1: Combobox widget without setting a default value.

    from tkinter import *
    from tkinter.ttk import *

    root = tk()
    root.title('Combobox') 
    root.geometry('500x250')

    title = Label(root, text ="CFG Combobox Widget", background = 'green', foreground ="white", font = ("Times New Roman", 15)).grid(row = 0, column = 1)
    month = Label(window, text = "Select the Month :", font = ("Times New Roman", 10)).grid(column = 0, row = 5, padx = 10, pady = 25)

    # Combobox creation
    n = StringVar() 
    monthchoosen = Combobox(root, width = 27, textvariable = n) 

    # Adding combobox drop down list
    monthchoosen['values'] = ('January',  
                              'February', 
                              'March', 
                              'April', 
                              'May', 
                              'June', 
                              'July', 
                              'August', 
                              'September', 
                              'October', 
                              'November', 
                              'December') 
    monthchoosen.grid(column = 1, row = 5) 
    monthchoosen.current() 

    root.mainloop()
        

Example 2: Combobox with initial default values.

    from tkinter import *
    from tkinter.ttk import *

    root = tk()
    root.title('Combobox') 
    root.geometry('500x250')

    title = Label(root, text ="CFG Combobox Widget", background = 'green', foreground ="white", font = ("Times New Roman", 15)).grid(row = 0, column = 1)
    month = Label(window, text = "Select the Month :", font = ("Times New Roman", 10)).grid(column = 0, row = 5, padx = 10, pady = 25)

    # Combobox creation
    n = StringVar() 
    monthchoosen = Combobox(root, width = 27, textvariable = n) 

    # Adding combobox drop down list
    monthchoosen['values'] = ('January',  
                              'February', 
                              'March', 
                              'April', 
                              'May', 
                              'June', 
                              'July', 
                              'August', 
                              'September', 
                              'October', 
                              'November', 
                              'December') 
    monthchoosen.grid(column = 1, row = 5) 
    
    # Shows february as a default value 
    monthchoosen.current(1) 

    root.mainloop()
        

Scale

The Scale widget is used whenever we want to select a specific value from a range of values. It provides a sliding bar through which we can select the values by sliding from left to right or top to bottom depending upon the orientation of our sliding bar.

    Syntax: S = Scale(root, bg, fg, bd, command, orient, from_, to, ..)
        

Scale Options

Option Description
root root window.
bg background colour.
fg foreground colour.
bd border.
orient orientation(vertical or horizontal).
from_ starting value.
to ending value.
troughcolor set colour for trough.
state decides if the widget will be responsive or unresponsive.
sliderlength decides the length of the slider.
label to display label in the widget.
highlightbackground the colour of the focus when widget is not focused.
cursor The cursor on the widget which could be arrow, circle, dot etc.

Methods:

Example 1: Creating a horizontal bar

    from tkinter import *

    root = tk()
    root.geometry("400x300")

    v1 = DoubleVar()

    def show1():
        sel = "Horizontal Scale Value = " + str(v1.get()) 
        l1.config(text = sel, font =("Courier", 14))

    s1 = Scale( root, variable = v1, from_ = 1, to = 100, orient = HORIZONTAL)    
    l3 = Label(root, text ="Horizontal Scaler") 
  
    b1 = Button(root, text ="Display Horizontal", command = show1, bg = "yellow")   
    l1 = Label(root) 
    s1.pack(anchor = CENTER)  
    l3.pack() 
    b1.pack(anchor = CENTER) 
    l1.pack()

    root.mainloop()
        

Example 2: Creating a vertical slider

    from tkinter import *

    root = tk()
    root.geometry("400x300")

    v2 = DoubleVar()

    def show2():
        sel = "Horizontal Scale Value = " + str(v2.get()) 
        l2.config(text = sel, font =("Courier", 14))

    s2 = Scale( root, variable = v2, from_ = 50, to = 1, orient = VERTICAL)    
  
    l4 = Label(root, text ="Vertical Scaler") 
  
    b2 = Button(root, text ="Display Vertical", command = show2, bg = "purple", fg = "white")   
    l2 = Label(root) 
    s2.pack(anchor = CENTER)  
    l4.pack() 
    b2.pack(anchor = CENTER) 
    l2.pack()

    root.mainloop()
        

Toplevel

A Toplevel widget is used to create a window on top of all other windows. The Toplevel widget is used to provide some extra information to the user and also when our program deals with more than one application. These windows are directly organized and managed by the Window Manager and do not need to have any parent window associated with them every time.

    Syntax: toplevel = Toplevel(root, bg, fg, bd, height, width, font, ..)
        

Toplevel Options

Option Description
root root window.
bg background colour.
fg foreground colour.
bd border.
height height of the widget.
width width of the widget.
font Font type of the text.
cursor cursor that appears on the widget which can be an arrow, a dot etc.

Methods:

Example:

    from tkinter import *

    root = tk()
    root.geometry("200x300")
    root.title("main")

    label1 = Label(root, text = "This is root window")
    
    top = Toplevel()
    top.geometry("180x100")
    top.title("toplevel")

    label2 = Label(top, text = "This is toplevel window")
 
    label1.pack()
    label2.pack()

    root.mainloop()
        

Example: Creating Multiple toplevels over one another.

    from tkinter import *

    root = tk()
    root.geometry("200x300")
    root.title("main")

    label = Label(root, text = "This is root window")

    # define a function for 2nd toplevel window which is not associated with any parent window.
    def open_Toplevel2():
        top2 = Toplevel()
        top2.title("Toplevel2")
        top2.geometry("200x100")

        label2 = Label(top2, text = "This is a Toplevel2 window")
        button2 = Button(top2, text = "Exit", command = top2.destroy)

        label2.pack()
        button2.pack()

        top2.mainloop()


    # define a function for 1st toplevel which is associated with root window.
    def open_Toplevel1():
        top1 = Toplevel(root)
        top1.title("Toplevel1")
        top1.geometry("200x200")

        label1 = Label(top1, text = "This is a Toplevel1 window")
        button1 = Button(top1, text = "Exit", command = top1.destroy)
        button3 = Button(top1, text = "open toplevel2", command = open_Toplevel2)

        label1.pack()
        button1.pack()
        button3.pack()

        top1.mainloop()

    
    button = Button(root, text = "open toplevel1", command = open_Toplevel1)

    label.pack()
    button.place(x = 155, y = 50)

    root.mainloop()
        

Message

The Message widget is used to show the message to the user regarding the behavior of the python application. The message text contains more than one line.

    Syntax: w = Message(master, options)

        • This parameter is used to represents the parent window.
        • There are many options which are available and they can be used as key-value pairs separated by commas:
        

Message Options

Option Description
anchor This option is used to decide the exact position of the text within the space .Its default value is CENTER.
bg This option used to represent the normal background color.
bitmap This option used to display a monochrome image.
bd This option used to represent the size of the border and the default value is 2 pixels.
cursor: By using this option, the mouse cursor will change to that pattern when it is over type.
font This option used to represent the font used for the text.
fg This option used to represent the color used to render the text.
height This option used to represent the number of lines of text on the message.
image This option used to display a graphic image on the widget.
justify This option used to control how the text is justified: CENTER, LEFT, or RIGHT.
padx This option used to represent how much space to leave to the left and right of the widget and text. It’s default value is 1 pixel.
pady This option used to represent how much space to leave above and below the widget. It’s default value is 1 pixel.
relief The type of the border of the widget. It’s default value is set to FLAT.
text This option used use newlines (“ ”) to display multiple lines of text.
variable This option used to represents the associated variable that tracks the state of the widget.
width This option used to represents the width of the widget. and also represented in the number of characters that are represented in the form of texts.
wraplength This option will be broken text into the number of pieces.

Example:

    from tkinter import *

    root = tk()
    root.geometry("300x200")
    w = Label(root, text ='CodingForGeeks', font = "50")  
    w.pack()

    msg = Message(root, text = "A computer science portal for geeks")
    msg.pack()   

    root.mainloop()
	    

The Menubutton widget can be defined as the drop-down menu that is shown to the user all the time. The Menubutton is used to implement various types of menus in the python application.

    Syntax: w = Menubutton (master, options)

        • This parameter is used to represents the parent window.
        • There are many options which are available and they can be used as key-value pairs separated by commas:
        

Menu Button Options

Option Description
activebackground This option used to represent the background color when the Menubutton is under the cursor.
activeforeground This option used to represent the foreground color when the Menubutton is under the cursor.
bg This option used to represent the normal background color displayed behind the label and indicator.
bitmap This option used to display a monochrome image on a button.
bd This option used to represent the size of the border around the indicator and the default value is 2 pixels.
anchor This option specifies the exact position of the widget content when the widget is assigned more space than needed.
cursor By using this option, the mouse cursor will change to that pattern when it is over the Menubutton.
disabledforeground The foreground color used to render the text of a disabled Menubutton. The default is a stippled version of the default foreground color.
direction It direction can be specified so that menu can be displayed to the specified direction of the button.
fg This option used to represent the color used to render the text.
height This option used to represent the number of lines of text on the Menubutton and it’s default value is 1.
highlightcolor This option used to represent the color of the focus highlight when the Menubutton has the focus.
image This option used to display a graphic image on the button.
justify This option used to control how the text is justified: CENTER, LEFT, or RIGHT.
menu It represents the menu specified with the Menubutton.
padx This option used to represent how much space to leave to the left and right of the Menubutton and text. It’s default value is 1 pixel.
pady This option used to represent how much space to leave above and below the Menubutton and text. It’s default value is 1 pixel.
relief The type of the border of the Menubutton. It’s default value is set to FLAT.
state It represents the state of the Menubutton. By default, it is set to normal. We can change it to DISABLED to make the Menubutton unresponsive. The state of the Menubutton is ACTIVE when it is under focus.
text This option used use newlines (“ ”) to display multiple lines of text.
underline This option used to represent the index of the character in the text which is to be underlined. The indexing starts with zero in the text.
textvariable This option used to represents the associated variable that tracks the state of the Menubutton.
width This option used to represents the width of the Menubutton. and also represented in the number of characters that are represented in the form of texts.
wraplength This option will be broken text into the number of pieces.

Example:

    from tkinter import *

    root = tk()
    root.geometry("300x200") 
  
    w = Label(root, text ='CodingForGeeks', font = "50")  
    w.pack() 
  
    menubutton = Menubutton(root, text = "Menu")    
    menubutton.menu = Menu(menubutton)   
    menubutton["menu"]= menubutton.menu   
  
    var1 = IntVar() 
    var2 = IntVar() 
    var3 = IntVar() 
  
    menubutton.menu.add_checkbutton(label = "Courses", variable = var1)   
    menubutton.menu.add_checkbutton(label = "Students", variable = var2) 
    menubutton.menu.add_checkbutton(label = "Careers", variable = var3) 
    
    menubutton.pack()

    root.mainloop()
        

Progressbar

The purpose of this widget is to reassure the user that something is happening. It can operate in one of two modes:
• In determinate mode, the widget shows an indicator that moves from beginning to end under program control.
• In indeterminate mode, the widget is animated so the user will believe that something is in progress. In this mode, the indicator bounces back and forth between the ends of the widget.

            Syntax: widget_object = Progressbar(parent, **options)
        

Progressbar Options

Option Description
container is the parent component of the progressbar.
orient can be either 'horizontal' or 'vertical'.
length represents the width of a horizontal progress bar or the height of a vertical progressbar.
mode can be either 'determinate' or 'indeterminate'

Methods:

Example1: Determinate mode

    from tkinter import *
    from tkinter.ttk import *

    root = tk()

    progress = Progressbar(root, orient = HORIZONTAL, length = 100, mode = 'determinate')
    
    Function responsible for the updation of the progress bar value 
    def bar():
        import time
        progress['value'] = 20
        root.update_idletasks() 
        time.sleep(1) 
    
        progress['value'] = 40
        root.update_idletasks() 
        time.sleep(1) 
    
        progress['value'] = 50
        root.update_idletasks() 
        time.sleep(1) 
    
        progress['value'] = 60
        root.update_idletasks() 
        time.sleep(1) 
    
        progress['value'] = 80
        root.update_idletasks() 
        time.sleep(1) 
        progress['value'] = 100
    
    progress.pack(pady = 10)

    # This button will initialize the progress bar
    Button(root, text ='Start', command =bar).pack(pady = 10)

    root.mainloop()
        

Example2: Indeterminate mode

    from tkinter import *
    from tkinter.ttk import *

    root = tk()

    progress = Progressbar(root, orient = HORIZONTAL, length = 100, mode = 'indeterminate')
    
    Function responsible for the updation of the progress bar value 
    def bar():
        import time
        progress['value'] = 20
        root.update_idletasks() 
        time.sleep(0.5) 
    
        progress['value'] = 40
        root.update_idletasks() 
        time.sleep(0.5) 
    
        progress['value'] = 50
        root.update_idletasks() 
        time.sleep(0.5) 
    
        progress['value'] = 60
        root.update_idletasks() 
        time.sleep(0.5) 
    
        progress['value'] = 80
        root.update_idletasks() 
        time.sleep(0.5) 
    
        progress['value'] = 100
        root.update_idletasks() 
        time.sleep(0.5) 
    
        progress['value'] = 80
        root.update_idletasks() 
        time.sleep(0.5) 
    
        progress['value'] = 60
        root.update_idletasks() 
        time.sleep(0.5) 
    
        progress['value'] = 50
        root.update_idletasks() 
        time.sleep(0.5) 
    
        progress['value'] = 40
        root.update_idletasks() 
        time.sleep(0.5) 
    
        progress['value'] = 20
        root.update_idletasks() 
        time.sleep(0.5) 
        progress['value'] = 0
    
    progress.pack(pady = 10)

    # This button will initialize the progress bar
    Button(root, text ='Start', command = bar).pack(pady = 10)

    root.mainloop()
        

Spinbox

The Spinbox widget in Tkinter is a numerical input field that allows users to select a value from a predefined range by either typing directly into the widget or by using up and down arrow buttons to increment or decrement the value.

    Syntax: Spinbox ( master, options)

    • master: This parameter is used to represents the parent window.
    • options:There are many options which are available and they can be used as key-value pairs separated by commas:
        

Spinbox Options

Option Description
activebackground This option used to represent the background color when the slider and arrowheads is under the cursor.
bg This option used to represent the normal background color displayed behind the label and indicator.
bd This option used to represent the size of the border around the indicator and the default value is 2 pixels.
command This option is associated with a function to be called when the state is changed.
cursor By using this option, the mouse cursor will change to that pattern when it is over the type.
disabledforeground This option used to represent the foreground color of the widget when it is disabled.
disabledbackground This option used to represent the background color of the widget when it is disabled.
font This option used to represent the font used for the text.
fg This option used to represent the color used to render the text.
format This option used to formatting the string and it’s has no default value.
from_ This option used to represent the minimum value.
justify This option used to control how the text is justified: CENTER, LEFT, or RIGHT.
relief This option used to represent the type of the border and It’s default value is set to SUNKEN.
repeatdelay This option is used to control the button auto repeat and its default value is in milliseconds.
repeatinterval This option is similar to repeatdelay.
state This option used to represent the represents the state of the widget and its default value is NORMAL.
textvariable This option used to control the behaviour of the widget text.
to It specify the maximum limit of the widget value. The other is specified by the from_ option.
validate This option is used to control how the widget value is validated.
validatecommand This option is associated to the function callback which is used for the validation of the widget content.
values This option used to represent the tuple containing the values for this widget.
vcmd This option is same as validation command.
width This option is used to represents the width of the widget.
wrap This option wraps up the up and down button the Spinbox.
xscrollcommand This options is set to the set() method of scrollbar to make this widget horizontally scrollable.

Methods:

Example:

    from tkinter import *

    root = tk()
    root.geometry("300x200")

    def on_spinbox_change():
        value = spinbox.get()
        print("Value changed to:", value)

    # Creating a Spinbox.
    spinbox = Spinbox(root, from_=0, to=100, width=10, relief="sunken", repeatdelay=500, repeatinterval=100,
                      font=("Arial", 12), bg="lightgrey", fg="blue", command=on_spinbox_change)

    # Setting options for the Spinbox.
    spinbox.config(state="normal", cursor="hand2", bd=3, justify="center", wrap=True)

    spinbox.pack(padx=20, pady=20)

    root.mainloop()
        

ScrolledText Widget

ScrolledText widget is a text widget with a scroll bar. The tkinter.scrolledtext module provides the text widget along with a scroll bar. This widget helps the user enter multiple lines of text with convenience. Instead of adding a Scroll bar to a text widget, we can make use of a scrolledtext widget that helps to enter any number of lines of text.

    from tkinter import *
    from tkinter.ttk import *
    from tkinter import scrolledtext

    root = tk()
    root.title("ScrolledText Widget")

    label1 = Label(root, text = "ScrolledText Widget Example", font = ("Times New Roman", 15), background = 'green',  
                   foreground = "white").grid(column = 0, row = 0) 
    # Creating scrolled text area widget.
    text_area = scrolledtext.ScrolledText(root, wrap = WORD, width = 40, height = 10, font = ("Times New Roman", 15)) 
    text_area.grid(column = 0, pady = 10, padx = 10) 

    text_area.focus()

    root.mainloop()
	    

Example 2 : ScrolledText widget making tkinter text Read only.

    from tkinter import *
    from tkinter.ttk import *
    from tkinter import scrolledtext

    root = tk()
    root.title("ScrolledText Widget")

    label1 = Label(root, text = "ScrolledText Widget Example", font = ("Times New Roman", 15), background = 'green',  
                   foreground = "white").grid(column = 0, row = 0) 
    # Creating scrolled text area widget.
    text_area = scrolledtext.ScrolledText(root, wrap = WORD, width = 40, height = 10, font = ("Times New Roman", 15)) 
    text_area.grid(column = 0, pady = 10, padx = 10) 

    # Inserting Text which is read only.
    text_area.insert(INSERT, """This is a scrolledtext widget to make tkinter text read only. 
                                Hi 
                                Geeks !!! 
                                Geeks !!! 
                                Geeks !!!  
                                Geeks !!! 
                                Geeks !!! 
                                Geeks !!! 
                                Geeks !!! 
    """) 

    text_area.configure(state ='disabled') 

    root.mainloop()
	    

In the first example, as you can see the cursor, the user can enter any number of lines of text. In the second example, the user can just read the text which is displayed in the text box and cannot edit/enter any lines of text. We may observe that the scroll bar disappears automatically if the text entered by the user is less than the size of the widget.

MessageBox Widget

MessageBox Widget is used to display the message boxes in the python applications. This module is used to display a message using provides a number of functions.

            Syntax: messagebox.Function_Name(title, message [, options]) 
        

There are various parameters:

There are two options that can be used are:

Methods or Function_Names:

Example:

        from tkinter import *
        from tkinter import messagebox

        root = tk()
        root.geometry("300x200") 
  
        w = Label(root, text ='CodingForGeeks', font = "50")  
        w.pack() 

        Various Messageboxes
        messagebox.showinfo("showinfo", "Information") 
  
        messagebox.showwarning("showwarning", "Warning") 
        
        messagebox.showerror("showerror", "Error") 
        
        messagebox.askquestion("askquestion", "Are you sure?") 
        
        messagebox.askokcancel("askokcancel", "Want to continue?") 
        
        messagebox.askyesno("askyesno", "Find the value?") 
        
        messagebox.askretrycancel("askretrycancel", "Try again?")

        root.mainloop()
            

Treeview

This widget is helpful in visualizing and permitting navigation over a hierarchy of items. It can display more than one feature of every item in the hierarchy. It can build a tree view as a user interface like in Windows explorer.

Example:

    from tkinter import *
    from tkinter.ttk import *

    root = tk()
    root.title("GUI Application of Python")

    label1 = Label(root, text ="Treeview(hierarchical)").pack()

    # Creating treeview window.
    treeview = Treeview(root)
    treeview.pack() 

    # Define item attributes
    items = [
        ('item2', 'Algorithm'),
        ('item2', 'Data structure'),
        ('item3', '2018 paper'),
        ('item3', '2019 paper'),
        ('item4', 'Python'),
        ('item4', 'Java')
    ]

    items_to_move = ['item2', 'item3', 'item4']

    # Inserting items to the treeview (parent)
    treeview.insert('', '0', 'item1', text ='CodingforGeeks') 
    
    # Inserting items to the treeview (child)
    for parent, text in items:
        treeview.insert(parent, 'end', text, text=text)

    # Placing each child items in parent widget
    for item in items_to_move:
        treeview.move(item, 'item1', 'end')

    root.mainloop()
	    

Treeview scrollbar Widget

A treeview widget is helpful in displaying more than one feature of every item listed in the tree to the right side of the tree in the form of columns. However, it can be implemented using tkinter in python with the help of some widgets and geometry management methods as supported by tkinter.

Example:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()
    root.resizable(width = 1, height = 1)

    treev = Treeview(root, selectmode ='browse')
    treev.pack(side ='right')

    # Constructing vertical scrollbar.
    verscrlbar = Scrollbar(root, orient ="vertical", command = treev.yview)
    verscrlbar.pack(side='right', fill='y')
    treev.configure(xscrollcommand = verscrlbar.set)

    # Defining Treeview Parameters
    treev.config(show='headings', columns=("1", "2", "3"))
    columns = [("1", "Name", 'c'), ("2", "Sex", 'se'), ("3", "Age", 'se')]
    for col_id, heading, anchor in columns:
        treev.column(col_id, width=90, anchor=anchor)
        treev.heading(col_id, text=heading)

    # List of data to insert
    data = [
        ("Nidhi", "F", "25"), ("Nisha", "F", "23"), ("Preeti", "F", "27"),
        ("Rahul", "M", "20"), ("Sonu", "F", "18"), ("Rohit", "M", "19"),
        ("Geeta", "F", "25"), ("Ankit", "M", "22"), ("Mukul", "F", "25"),
        ("Mohit", "M", "16"), ("Vivek", "M", "22"), ("Suman", "F", "30")
    ]

    for i, (name, sex, age) in enumerate(data, start=1):
        treev.insert("", 'end', text=f"L{i}", values=(name, sex, age))

    root.mainloop()
        

Text

Text Widget is used where a user wants to insert multiline text fields. This widget can be used for a variety of applications where the multiline text is required such as messaging, sending information or displaying information and many other tasks. We can insert media files such as images and links also in the Textwidget.

            Syntax: T = Text(root, bg, fg, bd, height, width, font, ..)
        

Text Options

Option Description
root root window.
bg background colour.
fg foreground colour.
bd border of widget.
height height of the widget.
width width of the widget.
font Font type of the text.
cursor The type of the cursor to be used.
insetofftime The time in milliseconds for which the cursor blink is off.
insertontime the time in milliseconds for which the cursor blink is on.
padx horizontal padding.
pady vertical padding.
state defines if the widget will be responsive to mouse or keyboards movements.
highlightthickness defines the thickness of the focus highlight.
insertionwidth defines the width of insertion character.
relief type of the border which can be SUNKEN, RAISED, GROOVE and RIDGE.
yscrollcommand to make the widget vertically scrollable.
xscrollcommand to make the widget horizontally scrollable.

Common Methods:

Tag Handling Methods:

Mark Handling Methods:

Example 1:

    from tkinter import *

    root = Tk()
    root.geometry("250x170")

    T = Text(root, height = 5, width = 52)
    l = Label(root, text = "Fact of the Day")
    l.config(font =("Courier", 14))

    Fact = """A man can be arrested in Italy for wearing a skirt in public."""

    b1 = Button(root, text = "Next", )
    b2 = Button(root, text = "Exit", command = root.destroy)

    l.pack()
    T.pack()
    b1.pack()
    b2.pack()

    T.insert(tk.END, Fact)
    
    root.mainloop()
        

Example 2: Saving Text and performing operations.

    from tkinter import *

    root = Tk()
    root.geometry("300x300")
    root.title(" Q&A ")

    def Take_input():
        INPUT = inputtxt.get("1.0", "end-1c")
        print(INPUT)
        if (INPUT == "120"):
            Output.insert(END, 'Correct')
        else:
            Output.insert(END, "Wrong answer")
    
    l = Label(text = "What is 24 * 5 ? ")
    inputtxt = Text(root, height = 10, width = 25, bg = "light yellow")
    Output = Text(root, height = 5, width = 25, bg = "light cyan")

    Display = Button(root, height = 2, width = 20, text ="Show", command = lambda:Take_input())

    l.pack()
    inputtxt.pack()
    Display.pack()
    Output.pack()
    
    root.mainloop()
        

Example 3: Display a Text File

    from tkinter import *

    root = Tk()
    root.geometry("300x300")

    def load_text():
        with open('file.txt', 'r') as file:
            data = file.read()
            text_widget.insert(tk.END, data)
    
    text_widget = Text(root, height=10, width=50)
    text_widget.pack()

    load_text()
    
    root.mainloop()
        

Geometry Management

Efficiently managing the geometry of Tkinter windows and widgets is essential for creating polished user interfaces. In this section, we’ll cover everything from setting window dimensions to handling resizing, padding, and widget positioning.

Let's look at these methods in more detail:

Managing the window:

Place Method

The Place geometry manager is the simplest of the three general geometry managers provided in Tkinter. It allows you explicitly set the position and size of a window, either in absolute terms, or relative to another window.

    Syntax: widget.place(relx = 0.5, rely = 0.5, anchor = CENTER)
        

Note: place() method can be used with grid() method as well as with pack() method.

Place Options

Option Description
anchor The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass directions indicating the corners and sides of widget; default is NW (the upper left corner of widget).
bordermode INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the parent's border); OUTSIDE otherwise.
height, width Height and width in pixels.
relheight, relwidth Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
relx, rely Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width of the parent widget.
x, y Horizontal and vertical offset in pixels.

Example 1:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()
    root.geometry("200x200")

    b1 = Button(root, text = "Click me !")
    b1.place(relx = 1, x =-2, y = 2, anchor = NE)

    l = Label(root, text = "I'm a Label")
    l.place(anchor = NW)

    b2 = Button(root, text = "CFG")
    b2.place(relx = 0.5, rely = 0.5, anchor = CENTER)

    root.mainloop()
        

When we use pack() or grid() managers, then it is very easy to put two different widgets separate to each other but putting one of them inside other is a bit difficult. But this can easily be achieved by place() method.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()
    root.geometry("200x200")

    b2 = Button(root, text = "CFG")
    b2.pack(fill = X, expand = True, ipady = 10)

    b1 = Button(root, text = "Click me !")
    # This is where b1 is placed inside b2 with in_ option.
    b1.place(in_= b2, relx = 0.5, rely = 0.5, anchor = CENTER)

    l = Label(root, text = "I'm a Label")
    l.place(anchor = NW)

    root.mainloop()
        

Pack Method

The Pack geometry manager packs widgets relative to the earlier widget. Tkinter literally packs all the widgets one after the other in a window. We can use options like fill, expand, and side to control this geometry manager.
Compared to the grid manager, the pack manager is somewhat limited, but it’s much easier to use in a few, but quite common situations:
• Put a widget inside a frame (or any other container widget), and have it fill the entire frame.
• Place a number of widgets on top of each other.
• Place a number of widgets side by side.

    Syntax: pane.pack(fill = BOTH, expand = True)
        

Pack Options

Option Description
expand When set to true, widget expands to fill any space not otherwise used in widget's parent.
fill Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both horizontally and vertically).
side Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT.

Example 1:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    # creating a Frame which can expand according to the size of the window
    pane = Frame(root)
    pane.pack(fill = BOTH, expand = True)

    # button widgets which can also expand and fill in the parent widget entirely
    b1 = Button(pane, text = "Click me !")
    b1.pack(fill = BOTH, expand = True)

    b2 = Button(pane, text = "Click me too")
    b2.pack(fill = BOTH, expand = True)

    root.mainloop()
        

Example 2: Placing widgets on top of each other.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    # creating a Frame which can expand according to the size of the window
    pane = Frame(root)
    pane.pack(fill = BOTH, expand = True)

    # button widgets which can also expand and fill in the parent widget entirely
    b1 = Button(pane, text = "Click me !", background = "red", fg = "white")
    b1.pack(side = TOP, expand = True, fill = BOTH)

    b2 = Button(pane, text = "Click me too", background = "blue", fg = "white")
    b2.pack(side = TOP, expand = True, fill = BOTH)

    b3 = Button(pane, text = "I'm also button", background = "green", fg = "white")
    b3.pack(side = TOP, expand = True, fill = BOTH)

    root.mainloop()
        

Example 3: Placing widgets side by side.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    # creating a Frame which can expand according to the size of the window
    pane = Frame(root)
    pane.pack(fill = BOTH, expand = True)

    # button widgets which can also expand and fill in the parent widget entirely
    b1 = Button(pane, text = "Click me !", background = "red", fg = "white")
    b1.pack(side = LEFT, expand = True, fill = BOTH)

    b2 = Button(pane, text = "Click me too", background = "blue", fg = "white")
    b2.pack(side = LEFT, expand = True, fill = BOTH)

    b3 = Button(pane, text = "I'm also button", background = "green", fg = "white")
    b3.pack(side = LEFT, expand = True, fill = BOTH)

    root.mainloop()
        

Grid Method

The Grid geometry manager puts the widgets in a 2-dimensional table. The master widget is split into a number of rows and columns, and each “cell” in the resulting table can hold a widget. The grid manager is the most flexible of the geometry managers in Tkinter.

    Syntax: l2.grid(row = 1, column = 0, sticky = W, pady = 2)
        

Grid Options

Option Description
column The column to put widget in; default 0 (leftmost column).
columnspan How many columns widgetoccupies; default 1.
ipadx, ipady How many pixels to pad widget, horizontally and vertically, inside widget's borders.
padx, pady How many pixels to pad widget, horizontally and vertically, outside v's borders.
row The row to put widget in; default the first row that is still empty.
rowspan How many rowswidget occupies; default 1.
sticky What to do if the cell is larger than widget. By default, with sticky='', widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks.

Example 1:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    l1 = Label(root, text = "First:")
    l2 = Label(root, text = "Second:")

    # grid method to arrange labels & entries in respective rows and columns as specified
    l1.grid(row = 0, column = 0, sticky = W, pady = 2)
    l2.grid(row = 1, column = 0, sticky = W, pady = 2)

    e1 = Entry(root)
    e2 = Entry(root)

    e1.grid(row = 0, column = 1, pady = 2)
    e2.grid(row = 1, column = 1, pady = 2)

    root.mainloop()
        

Example 2:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    l1 = Label(root, text = "Height:")
    l2 = Label(root, text = "Width:")

    # grid method to arrange labels & entries in respective rows and columns as specified
    l1.grid(row = 0, column = 0, sticky = W, pady = 2)
    l2.grid(row = 1, column = 0, sticky = W, pady = 2)

    e1 = Entry(root)
    e2 = Entry(root)

    e1.grid(row = 0, column = 1, pady = 2)
    e2.grid(row = 1, column = 1, pady = 2)

    # checkbutton widget
    c1 = Checkbutton(root, text = "Preserve")
    c1.grid(row = 2, column = 0, sticky = W, columnspan = 2)

    # adding image (remember image should be PNG and not JPG)
    img = PhotoImage(file = r"C:\Users\Admin\Pictures\capture1.png")
    img1 = img.subsample(2, 2)

    # setting image with the help of label
    l3 = Label(root, image = img1)
    l3.grid(row = 0, column = 2, columnspan = 2, rowspan = 2, padx = 5, pady = 5)

    b1 = Button(root, text = "Zoom in")
    b2 = Button(root, text = "Zoom out")

    b1.grid(row = 2, column = 2, sticky = E)
    b2.grid(row = 2, column = 3, sticky = E)

    root.mainloop()
        

Warning: Never mix grid() and pack() in the same master window.

Grid Methods:

• grid_location()

    Syntax: widget.grid_location(x, y)
    
    Parameters: x and y are the positions, relative to the upper left corner of the widget (parent widget).
        

Example:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    def click(event):
    # Here retrieving the size of the parent widget relative to master widget
        x = event.x_root - f.winfo_rootx()
        y = event.y_root - f.winfo_rooty()

    # Here grid_location() method is used to retrieve the relative position on the parent widget
        z = f.grid_location(x, y)

        print(z)

    f = Frame(root)
    f.pack()

    b = Button(f, text = "Button")
    b.grid(row = 2, column = 3)
    c = Button(f, text = "Button2")
    c.grid(row = 1, column = 0)

    # Here binding click method with mouse
    root.bind("<Button-1>", click)

    root.mainloop()
        

• grid_size()

    Syntax: x (columns, rows) = widget.grid_size()
    
    Return Value: It returns total numbers of columns and rows (grids).
        

Example:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    def grids(event):
    # Here, grid_size() method is used to get the total number grids available in frame widget
        x = f.grid_size()
        print(x)

    f = Frame(root)
    f.pack()

    b = Button(f, text = "Button")
    b.grid(row = 2, column = 3)
    c = Button(f, text = "Button2")
    c.grid(row = 1, column = 0)

    # Here binding click method with mouse
    root.bind("<Button-1>", grids)

    root.mainloop()
        

Geometry Method

This method is used to set the dimensions of the Tkinter window and is used to set the position of the main window on the user’s desktop.

Example 1: without using geometry method.

    from tkinter import Tk, mainloop, TOP
    from tkinter.ttk import Button

    root = Tk()
    
    button = Button(root, text = 'Geeks')
    button.pack(side = TOP, pady = 5)

    root.mainloop()
        

▸ As soon as you run the application, you’ll see the position of the Tkinter window is at the northwest position of the screen and the size of the window is also small.

Example 2: Using the geometry method to set the dimensions of the window.

    from tkinter import Tk, mainloop, TOP
    from tkinter.ttk import Button

    root = Tk()
    root.geometry('200x150')
    
    button = Button(root, text = 'Geeks')
    button.pack(side = TOP, pady = 5)

    root.mainloop()
        

▸ After running the application, you’ll see that the size of the Tkinter window has changed, but the position on the screen is the same.

Example 3: Using the geometry method to set the dimensions and positions of the window.

    from tkinter import Tk, mainloop, TOP
    from tkinter.ttk import Button

    root = Tk()
    root.geometry('200x150+400+300')
    
    button = Button(root, text = 'Geeks')
    button.pack(side = TOP, pady = 5)

    root.mainloop()
        

▸ When you run the application, you’ll observe that the position and size both are changed. Now the Tkinter window is appearing at a different position (400 shifted on X-axis and 300 shifted on Y-axis).

Note: We can also pass a variable argument in the geometry method, but it should be in the form (variable1) x (variable2); otherwise, it will raise an error.

Resize Method

This method method is used to allow Tkinter root window to change it’s size according to the users need as well we can prohibit resizing of the Tkinter window.

    Syntax: root.resizable(height = None, width = None)

    • To make the window resizable user can pass either positive integer or True.
    • To make window non-resizable user can pass 0 or False.
        

Example 1: Allowing root window to change it’s size.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    root.title('Resizable') 
    root.geometry('250x100') 
    
    Label(root, text = 'It\'s resizable').pack(side = TOP, pady = 10) 

    # Allowing root window to change it's size according to user's need 
    root.resizable(True, True)

    root.mainloop()
        

Example 2: Restricting root window to change it’s size (fixed size window).

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    root.title('Resizable') 
    root.geometry('250x100') 
    
    Label(root, text = 'It\'s resizable').pack(side = TOP, pady = 10) 

    # Allowing root window to change it's size according to user's need 
    root.resizable(0, 0)

    root.mainloop()
        

Padding

Padding enhances the layout of the widgets in an application. While developing an application in Tkinter, you can set the padding in two or more ways. The geometry manager in Tkinter allows you to define padding (padx and pady) for every widget (label, text, button, etc).

    Syntax:
        label1 = Widget_Name(app, text="text_to_be_written_in_label")
        label1.grid(row=0, column=0,
                    padx=(padding_from_left_side, padding_from_right_side), 
                    pady=(padding_from_top, padding_from_bottom))
        

Example 1: Padding at left-side to a widget.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()
    root.title("Vinayak App")

    # Maximize the window screen.
    width = root.winfo_screenwidth() 
    height = root.winfo_screenheight() 
    root.geometry("%dx%d" % (width, height)) 

    l1 = Label(app, text='Coding For Geeks')

    # Give the leftmost padding.
    l1.grid(padx=(200, 0), pady=(0, 0))

    root.mainloop()
        

Example 2: Padding from top to a widget.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()
    root.title("Vinayak App")

    # Maximize the window screen.
    width = root.winfo_screenwidth() 
    height = root.winfo_screenheight() 
    root.geometry("%dx%d" % (width, height)) 

    b1 = Button(app, text='Click Here!')

    # Give the topmost padding.
    b1.grid(padx=(0, 0), pady=(200, 0))

    root.mainloop()
        

Panned Window

The PanedWindow widget is a geometry manager widget, which can contain one or more child widgets panes. The child widgets can be resized by the user, by moving separator lines sashes using the mouse.

    Syntax: PanedWindow(master, **options)

    Parameters: 
            master: parent widget or main Tk() object.
            options: which are passed in config method or directly in the constructor.
        

Panned Window Options

Option Description
bg The color of the slider and arrowheads when the mouse is not over them.
bd The width of the 3-d borders around the entire perimeter of the trough, and also the width of the 3-d effects on the arrowheads and slider. Default is no border around the trough, and a 2-pixel border around the arrowheads and slider.
borderwidth Width of the border around the outside of the widget. Default is 2 pixels.
cursor The cursor that appears when the mouse is over the window.
handlepad To specify the distance between the handle and the end of the sash. Default is 8 pixels.
handlesize To specify the size of the handle, which is always a square. Default is 8 pixels.
height The height of the widget. No default value.
opaqueresize Controls how a resizing operation works.
orient To stack child widgets side by side. Default is HORIZONTAL.
relief Selects the relief style of the border around the widget. Default is FLAT.
sashpad To allocate extra space on either side of each sash. Default is zero
sashcursor No default value.
sashrelief Specifies the relief style used to render the sashes. Default is RAISED.
sashwidth Specifies the width of the sash. Default is 2 pixels.
showhandle To display the handles. No default value.
width Width of the widget. No default value.

Methods:

Example 1: PanedWindow with only two panes.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    # panedwindow object.
    pw = PanedWindow(orient ='vertical')

    top = ttk.Button(pw, text ="Click Me !\nI'm a Button") 
    top.pack(side = TOP)

    # This will add button widget to the panedwindow.
    pw.add(top)

    bot = Checkbutton(pw, text ="Choose Me !") 
    bot.pack(side = TOP) 

    # This will add Checkbutton to panedwindow.
    pw.add(bot)

    # expand is used so that widgets can expand fill is used to let widgets adjust itself according to the size of main window 
    pw.pack(fill = BOTH, expand = True)

    # This method is used to show sash.
    pw.configure(sashrelief = RAISED)

    root.mainloop()
        

Example 2: PanedWindow with multiple panes.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    # panedwindow object.
    pw = PanedWindow(orient ='vertical')

    top = ttk.Button(pw, text ="Click Me !\nI'm a Button") 
    top.pack(side = TOP)

    # This will add button widget to the panedwindow.
    pw.add(top)

    bot = Checkbutton(pw, text ="Choose Me !") 
    bot.pack(side = TOP) 

    # This will add Checkbutton to panedwindow.
    pw.add(bot)

    label = Label(pw, text ="I'm a Label") 
    label.pack(side = TOP) 
  
    # This will add a Label to panedwindow.
    pw.add(label) 

    string = StringVar()
    entry = Entry(pw, textvariable = string, font =('arial', 15, 'bold')) 
    entry.pack()
    
    # Focus force is used to focus on particular widget that means widget is already selected for operations 
    entry.focus_force() 

    # This will add a Entry to panedwindow.
    pw.add(entry)    

    # expand is used so that widgets can expand fill is used to let widgets adjust itself according to the size of main window 
    pw.pack(fill = BOTH, expand = True)

    # This method is used to show sash.
    pw.configure(sashrelief = RAISED)

    root.mainloop()
        

Event Handling

Events are generally used to provide an interface that works as a bridge between the User and the application logic. We can use Events in any Tkinter application to make it operable and functional.

    Syntax: widget.bind(event, event handler)

    Parameters:
            • Event – occurrence caused by the user that might reflect changes.
            • Event Handler – function in your application that gets invoked when the event takes place.
            • Bind – configuring an event handler (python function) that is called when an event occurs to a widget.
        

Event Object

The event object is passed to the callback function when an event occurs.It contains useful information about the event, such as:
• event.keysym: The key symbol (e.g., ‘a’, ‘Enter’).
• event.x and event.y: The x and y coordinates of the mouse event.
• event.widget: The widget that triggered the event.

Here is a list of some common Tkinter events which are generally used for making the application interactive.

Button

We have to manage the action and events which need to be executed at the time of running the application. The Button widget is useful for handling such events. We can use Button widget to perform a certain task or event by passing the callback in the command.

    from tkinter import *
    from tkinter import messagebox
    from tkinter.ttk import *

    root = Tk()
    root.geometry("700x350")

    def show_msg():
        messagebox.showinfo("Message","Hey There! I hope you are doing well.")

    l1 = Label(root, text= "Welcome Folks!", font= ('Aerial 17 bold italic'))
    l1.pack(pady= 30)

    b1 = Button(root, text= "Click Here", command=show_msg)
    b1.pack(pady= 20)

    root.mainloop()
        

ButtonRelease

To execute the events, we can bind a button or a key with the callback function.Consider an application where we need to trigger an event whenever we release the mouse button. This can be achieved by passing the Button Release parameter in the bind(ButtonRelease, callback) method.

    from tkinter import *

    root = Tk()
    root.geometry("700x350")

    # Define a function on mouse button clicked.
    def on_click(event):
        label["text"]="Button Released!"

    # Define a function on mouse button released.
    def on_release(event):
    label=Label(root, text="Click anywhere..", font=('Calibri 18 bold'))
    label.pack(pady=60)

    root.bind("<ButtonPress-1>", on_click)
    root.bind("<ButtonRelease-1>", on_release)

    root.mainloop()
        

Configure

The config() method is used to change the properties of any widget. Note that in config() method bg and background are two different options and background represents background-color.

    Syntax: widget.config(**options)
        

Example:

    from tkinter import *

    root = Tk()
    root.geometry("400x200")

    def on_configure(event):
        label["text"] = f"Width: {event.width}, Height: {event.height}"

    label = Label(root, text="Resize the window", font=("Calibri", 14))
    label.pack(pady=20)

    # Bind the <Configure> event to the root window.
    root.bind("<Configure>", on_configure)

    root.mainloop()
        

• This example will dynamically update the label text to show the current window dimensions as you resize the window.

Destroy

destroy() is a universal widget method i.e. we can use this method with any of the available widgets as well as with the main tkinter window.

    Syntax: widget_object = Widget(parent, command = widget_class_object.destroy)
        

Example: destroy() method passed as command:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    # Creating button. In this destroy method is passed as command, so as soon as button 1 is pressed root window will be destroyed 
    btn1 = Button(root, text ="Button 1", command = root.destroy) 
    btn1.pack(pady = 10) 
    
    root.mainloop()
        

Note: This method can be used with after() method.

Example: destroy() method with after() method:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    btn1 = Button(root, text ="Button 1") 
    btn1.pack(pady = 10)
    
    btn2 = Button(root, text ="Button 2") 
    btn2.pack(pady = 10)
    
    # after method destroying button-1 and button-2 after certain time.
    btn1.after(3000, btn1.destroy) 
    btn2.after(6000, btn2.destroy) 

    root.mainloop()
        

Note: There is another method available quit() which do not destroy widgets, but it exits the tcl/tk interpreter i.e. it stops the mainloop().

Example:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    def quit_program():
            root.quit()

        btn = Button(root, text ="Quit", command =quit_program) 
        btn.pack(pady = 10)

    root.mainloop()
        

Enter

Use to place the mouse pointer over a widget’s visible area. (This is distinct from the enter key, which is a KeyPress event for a key). The <Leave> event triggers when the mouse pointer leaves a widget's area.

Example: A simple mouseover effect for a Tkinter widget.

    from tkinter import *
    
    root = Tk()
    root.title("Basic MouseOver Example")
    root.geometry("720x250")

    def on_enter(event):
        label.config(text="")

    l1 = Label(root, text="Hover over me!")
    l1.pack(pady=20)

    # Bind function to the <Enter> and <Leave> events
    l1.bind("<Enter>", on_enter)
    l1.bind("<Leave>", on_leave)

    root.mainloop()
        

Example: Expanding Mouseover Events to Buttons

    from tkinter import *
    
    root = Tk()
    root.title("Basic MouseOver Example")
    root.geometry("720x250")

    def on_enter(event):
        widget = event.widget
        widget.config(text="")

    def on_button_click(event):
        widget = event.widget
        widget.config(text="Clicked!")

    l1 = Label(root, text="Hover over me!")
    l1.pack(pady=20)
    l1.bind("<Enter>", on_enter)
    l1.bind("<Leave>", on_leave)

    # Create a button and bind mouseover and click events.
    b1 = Label(root, text="Click me!")
    b1.pack(pady=20)
    b1.bind("<Enter>", on_enter)
    b1.bind("<Leave>", on_leave)
    b1.bind("<Button-1>", on_button_click)

    root.mainloop()
        

Expose

The <Expose> event is triggered when a widget is redrawn, such as when a window is uncovered after being hidden by another window.

    from tkinter import *
    
    root = Tk()
    root.geometry("400x200")

    def on_expose(event):
        label["text"] = "Window exposed!"

    l1 = Label(root, text="Minimize and restore the window", font=("Calibri", 14))
    l1.pack(pady=20)

    # Bind the <Expose> event to the root window.
    root.bind("<Expose>", on_expose)

    root.mainloop()
        

Focus In & Focus Out

This may occur in response to user interaction (such as using the tab key to switch across widgets) or programmatically (for instance, when your software invokes the .focus set() method on a widget).

    from tkinter import *
    
    root = Tk()
    root.geometry("400x200")

    def on_focus_in(event):
        label["text"] = "Entry widget has focus!"

    def on_focus_out(event):
        label["text"] = "Entry widget lost focus."

    e1 = Entry(root, font=("Calibri", 14))
    e1.pack(pady=20)

    l1 = Label(root, text="Minimize and restore the window", font=("Calibri", 14))
    l1.pack(pady=20)

    # Bind the <FocusIn> & <FocusOut> events to the entry widget.
    e1.bind("<FocusIn>>", on_focus_in)
    e1.bind("<FocusOut>>", on_focus_out)

    root.mainloop()
        

Methods:
• focus_set()

    Syntax: widget.focus_set()
        

Example:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    e1 = Entry(root) 
    e1.pack(expand = 1, fill = BOTH)
    
    e2 = Button(root, text ="Button")
    # Here focus_set() method is used to set the focus.
    e2.focus_set() 
    e2.pack(pady = 5) 

    e3 = Radiobutton(root, text ="Hello") 
    e3.pack(pady = 5) 

    root.mainloop()
        

• focus_get()

    Syntax: widget.focus_get()
        

Example:

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    # This method is used to get the name of the widget which currently has the focus by clicking Mouse Button-1 
    def focus(event):
        widget = root.focus_get()
        print(widget, "has focus")

    e1 = Entry(root) 
    e1.pack(expand = 1, fill = BOTH)
    
    e2 = Button(root, text ="Button")
    # Here focus_set() method is used to set the focus.
    e2.focus_set() 
    e2.pack(pady = 5) 

    e3 = Radiobutton(root, text ="Hello") 
    e3.pack(pady = 5) 

    # Here function focus() is binded with Mouse Button-1 so every time you click mouse, it will call the focus method, defined above 
    root.bind_all("<Button-1>", lambda e: focus(e))

    root.mainloop()
        

Every time you click on any widget OR if you click the mouse button-1 above program will print the name of the widget which has the focus.

KeyPress & KeyRelease

Events like <Key Press> and <KeyRelease> are used to call a specific function only when a key is pressed or released.

    from tkinter import *

    root = Tk()
    root.geometry("700x350")

    def key_press(e):
        label.config(text="Key Pressed")

    def key_released(e):
        label.config(text="Key Released")

    l1 = Label(win, text= "", font= ('Helvetica 17 bold'))
    l1.pack(pady= 50)

    root.bind("<KeyPress>", key_press)
    root.bind("<KeyRelease>", key_released)

    root.mainloop()
        

Map

The <Map> event triggers when a widget is mapped, meaning it becomes visible on the screen (e.g., after being hidden or initially created).

    fromtkinter import *
     
    root = Tk()
    root.geometry("400x200")

    def on_map(event):
        label["text"] = "Window is now visible!"

    l1 = Label(root, text="Minimize and restore the window.", font=("Calibri", 14))
    l1.pack(pady=20)

    root.bind("<Map>", on_map)

    root.mainloop()
        

Motion

The <Motion> event triggers whenever the mouse moves within a widget's area.

    from tkinter import *
    
    root = Tk()
    root.geometry("400x200")

    def on_motion(event):
        label["text"] = f"Mouse at X: {event.x}, Y: {event.y}"

    l1 = Label(root, text="Move the mouse inside the window.", font=("Calibri", 14))
    l1.pack(pady=20)

    root.bind("<Motion>", on_motion)

    root.mainloop()
        

MouseWheel

The <MouseWheel> event detects mouse wheel scrolling and provides information about the scroll direction.

    from tkinter import *
    
    root = Tk()
    root.geometry("400x200")

    def on_mousewheel(event):
        if event.delta > 0:
            label["text"] = "Mouse wheel scrolled up!"
        else:
            label["text"] = "Mouse wheel scrolled down!"

    l1 = Label(root, text="Scroll the mouse wheel.", font=("Calibri", 14))
    l1.pack(pady=20)

    root.bind("<MouseWheel>", on_mousewheel)

    root.mainloop()
        

Use these events to determine mousewheel direction:
• event.delta > 0: Scroll up
• event.delta < 0: Scroll down

Note: On Linux, the <MouseWheel> event may not work. Instead, use <Button-4> for scrolling up and <Button-5> for scrolling down:

    root.bind("<Button-4>", lambda event: label.config(text="Scroll Up!"))
    root.bind("<Button-5>", lambda event: label.config(text="Scroll Down!"))
        

Unmap

If we want to unmap any widget from the screen or toplevel then forget() method is used. There are two types of forget method pack_forget() ( similar to forget() ) and grid_forget() which are used with pack() and grid() method respectively.
• pack_forget() method:

    Syntax: widget.pack_forget()
        

Note: widget can be any valid widget which is visible.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    # This will remove the widget from toplevel basically widget do not get deleted it just becomes invisible and loses its position and can be retrieve
    def forget(widget):
        widget.forget()

    # method to make widget visible.
    def retrieve(widget):
        widget.pack(fill = BOTH, expand = True)

    b1 = Button(root, text = "Btn 1") 
    b1.pack(fill = BOTH, expand = True) 

    b2 = Button(root, text = "Btn 2", command = lambda : forget(b1)) 
    b2.pack(fill = BOTH, expand = True)  
    
    b3 = Button(root, text = "Btn 3", command = lambda : retrieve(b1)) 
    b3.pack(fill = BOTH, expand = True) 
    
    root.mainloop()
        

Notice the difference in the position of Button 1 before and after forget as well as after retrieval.

• grid_forget() method:

    Syntax: widget.grid_forget()
        

Note: This method can be used only with grid() geometry methods.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()

    # This will remove the widget from toplevel basically widget do not get deleted it just becomes invisible and loses its position and can be retrieve
    def forget(widget):
        widget.grid_forget() 

    # method to make widget visible.
    def retrieve(widget):
        widget.grid(row = 0, column = 0, ipady = 10, pady = 10, padx = 5) 

    b1 = Button(root, text = "Btn 1") 
    b1.grid(row = 0, column = 0, ipady = 10, pady = 10, padx = 5)

    b2 = Button(root, text = "Btn 2", command = lambda : forget(b1)) 
    b2.grid(row = 0, column = 1, ipady = 10, pady = 10, padx = 5) 
    
    b3 = Button(root, text = "Btn 3", command = lambda : retrieve(b1)) 
    b3.grid(row = 0, column = 2, ipady = 10, pady = 10, padx = 5) 
    
    root.mainloop()
        

Notice that the position of Button 1 remains same after forget and retrieval. With grid_forget() method, you can place it at any grid after retrieval but generally, the original grid is chosen.

Visibility

The <Visibility> event is triggered when a widget becomes visible or changes its visibility status (like being obscured or revealed).

    from tkinter import *
    
    root = Tk()
    root.geometry("400x200")

    def on_visibility(event):
        label["text"] = "Widget visibility changed!"

    l1 = Label(root, text="Change the visibility of this window.", font=("Calibri", 14))
    l1.pack(pady=20)

    root.bind("<Visibility>", on_visibility)

    root.mainloop()
        

Mouse Events

Capturing mouse events inside tkinter:

• Moving: - We can bind to mouse movement by using widget.bind("<Motion>", motion_handler).

    from tkinter import *
    
    root = Tk()
    root.geometry("400x200")

    def on_motion(event):
        label["text"] = f"Mouse at X: {event.x}, Y: {event.y}"

    l1 = Label(root, text="Move the mouse inside the window.", font=("Calibri", 14))
    l1.pack(pady=20)

    root.bind("<Motion>", on_motion)

    root.mainloop()
        

• Clicking: - There’s multiple ways to bind to a mouse click event:

    from tkinter import *

    root = Tk()
    root.geometry("700x350")

    def single_click(event):
        print("SINGLE CLICK")

    def double_click(event):
        print("DOUBLE CLICK")

    root.bind("<Button-1>", single_click)
    root.bind("<Double-Button-1>>", double_release)

    root.mainloop()
        

All of these options can be suffixed with -{num} where num is a single digit.
• 1=left click, • 2=right click • 3=middle click (scroll wheel click).
An alternative to this is using the .num attribute on the event object.

    from tkinter import *
    
    root = Tk()
    root.geometry("700x350")

    def click_handler(event):
        if event.num == 2:
            print("RIGHT CLICK")

    root.bind(<Button-1>, lambda x: print("LEFT CLICK"))
    root.bind(<Button>, click_handler)

    root.mainloop()
        

• Dragging: - To capture a click-and-drag event use any of the <B1-Motion> (left-click), <B2-Motion> (right click) or <B3-Motion> (middle mouse button click). Note that when dragging outside of an element the event still fires.

    from tkinter import *

    root = Tk()
    root.geometry("700x350")

    def drag_handler(event):
            print(event.x, event.y)

    label = tkinter.Label(root, text="HEY")
    label.pack()

    root.bind(<B1-Motion>, drag_handler)
    
    root.mainloop()
        

• Hovering: - Hovering over an element sends out two events in sequence, <Enter> and <Leave>

    from tkinter import *

    root = Tk()
    root.geometry("700x350")

    label = tkinter.Label(root, text="HELLO", bg="white", fg="navy")
    label.bind(<enter>, lambda event: event.widget.config(bg="navy", fg="white"))
    label.bind(<leave>, lambda event: event.widget.config(bg="white", fg="navy"))
    label.pack()

    root.mainloop()    
        

Hovering the text shows it with a blue background and leaving it sets it back to default.

Styling

Fonts

Fonts in Tkinter are used to customize the appearance of text displayed in various widgets such as labels, buttons, entry widgets, and more. They allow you to control the font family, size, weight, style, and other properties of the text. Here are some common use cases:

    Syntax: font = tkFont.Font(option, ...)
        

The available options include:

Example: Font Styles

    from tkinter import *
    from tkinter.font import *

    root = Tk()
    root.title("Font Example")

    # Create fonts with different weights and slants.
    normal_font = Font(family="Arial", size=12, weight=NORMAL)
    bold_font   = Font(family="Arial", size=12, weight="bold")
    italic_font = Font(family="Arial", size=12, slant="italic")
    underline_font = Font(family="Arial", size=12, underline=1)
    roman_font = Font(family="Arial", size=12, slant=ROMAN)

    # Create labels using different font styles.
    l1 = Label(root, text="Normal Text", font=normal_font)
    l1.pack()

    l2 = Label(root, text="Bold Text", font=bold_font)
    l2.pack(pady=5)

    l3 = Label(root, text="Italic Text", font=italic_font)
    l3.pack(pady=5)

    l4 = Label(root, text="Underlined Text", font=underline_font)
    l4.pack(pady=5)

    l5 = Label(root, text="Roman Text", font=roman_font)
    l5.pack(pady=5)

    root.mainloop()
        

Example: Resizable Text and Font Size Adjustment

    from tkinter import *
    from tkinter.font import *

    def increase_font_size():
        font.config(size=font.actual()['size'] + 2)

    def decrease_font_size():
        font.config(size=max(8, font.actual()['size'] - 2))

        root = Tk()
        font = Font(family="Times", size=12)

        increase_button = Button(root, text="Increase Font Size", command=increase_font_size)
        increase_button.pack()

        decrease_button = Button(root, text="Decrease Font Size", command=decrease_font_size)
        decrease_button.pack()

        root.mainloop()
        

Color Customization

Colors are essential for enhancing the visual appeal and user experience of graphical user interfaces (GUIs). Let's delve into the common color options and how they are utilized in Tkinter.

• Active Background and Foreground Colors:

    from tkinter import *

    root = Tk()
    root.geometry("400x200")

    b1 = Button(root, text="Hover or Click Me!", font=("Calibri", 14),
                bg="lightblue",               # Normal background color
                fg="black",                   # Normal text color
                activebackground="blue",      # Background when active (hovered or clicked)
                activeforeground="white"      # Text color when active
                )
    b1.pack(pady=50)

    root.mainloop()
	    

• Background and Foreground Colors:

    from tkinter import *

    root = Tk()
    root.geometry("400x200")

    l1 = Label(root, text="Hello World", font=("Calibri", 14),
               bg="lightblue",         # Background color
                fg="black",            # Foreground or Text color
                )

    root.mainloop()
	    

• Disabled State Colors:

    from tkinter import *

    root = Tk()
    root.geometry("400x200")

    def toggle_button():
        if button["state"] == NORMAL:
            button["state"] = DISABLED 
        else:
            button["state"] = NORMAL

    b1 = Button(root, text="Click Me!", font=("Calibri", 14),
                state=DISABLED,                # Initially disabled
                disabledforeground="grey",     # Text color when disabled
                highlightbackground="red",     # Border color when not focused (MacOS)
                highlightcolor="green"         # Border color when focused
                )
    b1.pack(pady=50)

    # Toggle button to enable/disable the above button.
    toggle_btn = Button(root, text="Toggle Button State", command=toggle_button)
    toggle_btn.pack()

    root.mainloop()
	    

Note: On Windows, highlightbackground and highlightcolor might not be very noticeable. They are more effective on macOS or when using custom themes.

• Selection Colors:

    from tkinter import *

    root = Tk()
    root.geometry("400x200")

    listbox = Listbox(root, font=("Calibri", 14),
                      selectbackground="blue",      # Background color when selected
                      selectforeground="white"      # Text color when selected
                      )
    listbox.pack(pady=30)

    # Adding items to the listbox.
    items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
    for item in items:
        listbox.insert(END, item)

    root.mainloop()
	    

Note: These options are commonly used with widgets like Listbox or Text to control the background and text color when an item is selected.

Themes & Styles

Tkinter supports both traditional and modern graphics support with the help of Tk themed widgets.

    Syntax: style = ttk.Style()
        

Example 1: Apply style to one button.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()
    root.geometry('100x100')

    # This will create style object.
    style = Style()

    # This will be adding style.
    style.configure('W.TButton', font = ('calibri', 10, 'bold', 'underline'), foreground = 'red')

    # Style will be reflected only on this button because we are providing style only on this Button.
    btn1 = Button(root, text = 'Quit !', style = 'W.TButton', command = root.destroy)
    btn1.grid(row = 0, column = 3, padx = 100)

    btn2 = Button(root, text = 'Click me !', command = None)
    btn2.grid(row = 1, column = 3, pady = 10, padx = 100)

    root.mainloop()
        

Only one button will get styled because in the above code we are providing styling only in one Button.

Example 2: Aplly style to all buttons.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()
    root.geometry('100x100')

    # This will create style object.
    style = Style()

    # Will add style to every available button even though we are not passing style to every button widget.
    style.configure('TButton', font = ('calibri', 10, 'bold', 'underline'), foreground = 'red')

    # Style will be reflected only on this button because we are providing style only on this Button.
    btn1 = Button(root, text = 'Quit !', style = 'TButton', command = root.destroy)
    btn1.grid(row = 0, column = 3, padx = 100)

    btn2 = Button(root, text = 'Click me !', command = None)
    btn2.grid(row = 1, column = 3, pady = 10, padx = 100)

    root.mainloop()
        

Example 3: Change color on mouse hover.

    from tkinter import *
    from tkinter.ttk import *

    root = Tk()
    root.geometry('500x500')

    # This will create style object.
    style = Style()

    style.configure('TButton', font = ('calibri', 20, 'bold'), borderwidth = '4')

    # Changes will be reflected by the movement of mouse.
    style.map('TButton', foreground = [('active', '!disabled', 'green')], background = [('active', 'black')])

    btn1 = Button(root, text = 'Quit !', style = 'TButton', command = root.destroy)
    btn1.grid(row = 0, column = 3, padx = 100)

    btn2 = Button(root, text = 'Click me !', command = None)
    btn2.grid(row = 1, column = 3, pady = 10, padx = 100)

    root.mainloop()
        

Python Tkinter Color Chooser

Tkinter provides a color chooser dialog, allowing users to pick colors interactively.

    Syntax:  color = colorchooser.askcolor(title="Choose color")
        

Example:

    from tkinter import *
    from tkinter.ttk import colorchooser

    root = Tk()
    root.title("Tkinter Color Chooser Example")

    def choose_color():
        color = colorchooser.askcolor(title="Choose color")
        print("Selected color:", color[1]) # Print the hexadecimal color value

    b1 = Button(root, text="Choose Color", command=choose_color)
    b1.pack()

    root.mainloop()
        

Images

In Tkinter, there is no in-built method or any package to work with images.To use images in Tkinter we use a module called Pillow. If it's not present in the system then it can be installed using the below command:

    pip install Pillow
        

In Pillow there are 2 functions; Image & ImageTk. Let's look at these functions more closely.

• 1. Image

Methods:

• Image.open():
Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method). See new().

    Syntax: PIL.Image.open(fp, mode=’r’) 

    Parameters:
	    • fp – A filename (string), pathlib.Path object or a file object. The file object must implement read(), seek(), and tell() methods, and be opened in binary mode. 
        • mode – The mode. If given, this argument must be “r”.
        

Example:

    from PIL import Image

    im = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg")
        

Note: Location of image should be relative only if the image is in the same directory as the Python program, otherwise absolute (full) path of the image should be provided.

• Image.show():
Displays this image. This method is mainly intended for debugging purposes.

    Syntax: Image.show(title=None, command=None) 

    Parameters:
        • title – Optional title to use for the image window, where possible.
        • command – command used to show the image.
        

Example:

    from PIL import Image

    im = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg")
    im.show()
        

• mode:
The mode attribute of the image tells the type and depth of the pixel in the image. A 1-bit pixel has a range of 0-1, and an 8-bit pixel has a range of 0-255. There are different modes provided by this module. Few of them are:

Example:

    from PIL import Image

    im = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg")
    print(img.mode)
        

• size: This attribute provides the size of the image. It returns a tuple that contains width and height.

Example:

    from PIL import Image

    im = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg")
    print(img.size)
        

• format: This method returns the format of the image file.

Example:

    from PIL import Image

    im = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg")
    print(img.format)
        

• rotate: This method rotates the image. After rotating the image, the sections of the image having no pixel values are filled with black (for non-alpha images) and with completely transparent pixels (for images supporting transparency)

Example:

    from PIL import Image
    
    angle = 40
    im = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg")
    r_img = img.rotate(angle)
        

• resize: This method resizes the image. Interpolation happens during the resize process, due to which the quality of image changes whether it is being upscaled (resized to a higher dimension than original) or downscaled (resized to a lower Image then original). Therefore resize() should be used cautiously and while providing suitable value for resampling argument.

    from PIL import Image
    
    size = (40, 40)
    im = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg")
    r_img = img.resize(size)
        

• Image.save(): Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. While using the save() method Destination_path must have the image filename and extension as well. The extension could be omitted in Destination_path if the extension is specified in the format argument.

    Syntax:  Image.save(fp, format=None, **params)

    Parameters:
        • fp – A filename (string), pathlib.Path object or file object.
        • format – Optional format override.
        • options – Extra parameters to the image writer.
        

Example:

    from PIL import Image

    im = Image.open(r"C:\Users\System-Pc\Desktop\flower1.jpg")
    # save a image using extension.
    im = im.save("geeks.jpg")
        

• Image.new(): This method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels. The color is given as a single value for single-band images, and a tuple for multi-band images (with one value for each band).

    Syntax: PIL.Image.new(mode, size, color)

    Parameters:
        • mode: The mode to use for the new image. (It could be RGB, RGBA)
        • size: A tuple containing (width, height) in pixels.
        • color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes.
        

Example 1:

    from PIL import Image

    im = PIL.Image.new(mode="RGB", size=(200, 200))
        

Example 2: With color specified.

    from PIL import Image

    im = PIL.Image.new(mode = "RGB", size = (200, 200), color = (153, 153, 255))
        

• Image.point(): Maps this image through a lookup table or function.

    Syntax: im.point(lambda p:)

    Parameters:
        • lut – A lookup table, containing 256 (or 65336 if self.mode==”I” and mode == “L”) values per band in the image.
        • mode – Output mode (default is same as input). In the current version, this can only be used if the source image has mode “L” or “P”, and the output has mode “1” or the source image mode is “I” and the output mode is “L”.
        

Example:

    from PIL import Image
    
    im = Image.open(r"C:\Users\System-Pc\Desktop\home.png")

    # using point function.
    threshold = 191  
    im = im.point(lambda p: p >value threshold and 255) 
        

• Image.seek(): Seeks to the given frame in this sequence file. If you seek beyond the end of the sequence, the method raises an EOFError exception. When a sequence file is opened, the library automatically seeks to frame 0.

    Syntax: mage.seek(frame)

    Parameters:
        • frame – Frame number, starting at 0.
        

Example:

    from PIL import Image

    # creating gif image object.
    img = Image.open(r"C:\Users\System-Pc\Desktop\time.gif") 
    img1 = img.tell() 
    print(img1)

    # using seek() method.
    img2 = img.seek(img.tell() + 1) 
    img3 = img.tell() 
    print(img3)
        

• Image.crop(): This method is used to crop a rectangular portion of any image.

    Syntax: PIL.Image.crop(box = None)

    Parameters:
        • box – a 4-tuple defining the left, upper, right, and lower pixel coordinate.
        

Example:

    from PIL import Image

    im = Image.open(r"C:\Users\Admin\Pictures\geeks.png")

    # Size of the image in pixels (size of original image) (This is not mandatory).
    width, height = im.size

    # Setting the points for cropped image.
    left = 5
    top = height / 4
    right = 164
    bottom = 3 * height / 4

    # Cropped image of above dimension (It will not change original image)
    im1 = im.crop((left, top, right, bottom))
        

• Image.draft(): Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size.

    Syntax: Image.draft(mode, size)

    Parameters:
        • mode – The requested mode.
        • size – The requested size.
        

Example:

    from PIL import Image

    im = Image.open(r"C:\Users\System-Pc\Desktop\rose.jpg")

    # print the original image object.
    print(im)

    # using draft function convert mode and size as well.
    im1 = im.draft("L", (im.width // 2, im.height // 2))
    im2 = im1.decoderconfig, im1.mode, im.size, im1.tile
    print(im1)
    print(im2)
        

• Image.split(): method is used to split the image into individual bands. This method returns a tuple of individual image bands from an image. Splitting an “RGB” image creates three new images each containing a copy of one of the original bands (red, green, blue).

    Syntax: var = Image.Image.split(image_object) OR var = Image.Image.split(path_of_image)
        

Example:

    from PIL import Image

    im = Image.open(r"C:\Users\Admin\Pictures\network.png") 

    # split() method this will split the image in individual bands and return a tuple.
    im1 = Image.Image.split(im) 

    # showing each band.
    im1[0].show() 
    im1[1].show() 
    im1[2].show() 
        

• Image.merge(): Merge a set of single band images into a new multiband image.

    Syntax: PIL.Image.merge(mode, bands)

    Parameters:
        • mode – The mode to use for the output image. See: Modes.
        • bands – A sequence containing one single-band image for each band in the output image. All bands must have the same size.
        

Example:

    from PIL import Image

    # creating a object.
    image = Image.open(r"C:\Users\System-Pc\Desktop\home.png")
    image.load() 
    r, g, b, a = image.split() 

    # merge funstion used.
    im1 = Image.merge( 'RGB', (r, g, b))
        

• 2. ImageTK

• Reading Images:

Example 1: How to read images with tkinter using PIL.

    from tkinter import *
    from PIL import ImageTk, Image
    import  os

    root = Tk()

    # loading the image.
    img = ImageTk.PhotoImage(Image.open("cfg.jpeg"))

    # readding the image.
    panel = Label(root, image = img)
    panel.pack(side = "bottom", fill = "both", expand = "yes") 

    root.mainloop()
        

Example 2: Arrange the image parameters along with application parameters.

    from tkinter import *
    from PIL import ImageTk, Image

    root = Tk()

    # arranging application parameters.
    canvas = Canvas(root, width = 500, height = 250)
    canvas.pack() 

    # loading the image.
    img = ImageTk.PhotoImage(Image.open("cfg.jpeg"))

    # arranging image parameters in the application.
    canvas.create_image(135, 20, anchor = NW, image = img)  

    root.mainloop()
        

• Loading Images:

Example:

    from tkinter import *
    from PIL import ImageTk, Image
    from PIL import filedialog

    root = Tk()
    root.title("Image Loader")
    root.geometry("550x300 + 300 + 150")
    root.resizable(width = True, height = True)

    # Function to place the image onto the window.
    def open_img():
        x = openfilename()
        img = Image.open(x)
        # resize the image and apply a high-quality down sampling filter.
        img = img.resize((250, 250), Image.LANCZOS)
        img = ImageTk.PhotoImage(img)

        panel = Label(root, image = img)
        panel.image = img
        panel.grid(row = 2)

    # Function to return the file name chosen from a dialog box.
    def openfilename():
        filename = filedialog.askopenfilename(title ='"pen')
        return filename

    btn = Button(root, text ='open image', command = open_img)
    btn.grid(row = 1, columnspan = 4) 

    root.mainloop()
        

• Set the titlebar icon of any tkinter/toplevel window:
iconphoto() method is used to set the titlebar icon of any tkinter/toplevel window. But to set any image as the icon of titlebar, image should be the object of PhotoImage class.

    Syntax: iconphoto(self, default = False, *args)
        

Example 1: When PhotoImage object is provided:

    from tkinter import *
    from tkinter.ttk import *
    from PIL import ImageTk, Image

    root = Tk()

    # Creating object of photoimage class.
    p1 = PhotoImage(file = 'info.png')
    
    # Setting icon of master window.
    root.iconphoto(False, p1)

    b = Button(root, text = 'Click me !') 
    b.pack(side = TOP) 

    root.mainloop()
        

Example 2: When PhotoImage object is not provided:

    from tkinter import *
    from tkinter.ttk import *
    from PIL import ImageTk, Image

    root = Tk()
    
    # Setting icon of master window.
    root.iconphoto(False, 'info.png') 

    b = Button(root, text = 'Click me !') 
    b.pack(side = TOP) 

    root.mainloop()
        

Exception: f you provide an image directly instead of PhotoImage object then it will show the following error:

    Traceback (most recent call last):
    File "C:\Users\Admin\Documents\GUI_python\geeks.py", line 14, in 
    root.iconphoto(False, 'info.png')
    File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1910, in wm_iconphoto
    self.tk.call('wm', 'iconphoto', self._w, *args)
    _tkinter.TclError: can't use "info.png" as iconphoto: not a photo image
        

• Resize Image:

    Syntax: Image.resize((width,height) , resample=3, **attr)
        

Example:

    from tkinter import *
    from PIL import ImageTk, Image

    root = Tk()
    
    image = Image.open("Image File Path")

    # Resize the image.
    resize_image = image.resize((width, height))

    img = ImageTk.PhotoImage(resize_image)

    label1 = Label(image=img)
    label1.image = img
    label1.pack()

    root.mainloop()
        

• Images as Backgrounds:

Method 1: Using photoimage methods.

    from tkinter import *
    
    root = Tk()
    root.geometry("400x400")

    bg = PhotoImage(file = "Your_image.png") 

    l1 = Label( root, image = bg) 
    l1.place(x = 0, y = 0) 
    
    l2 = Label( root, text = "Welcome") 
    l2.pack(pady = 50)
    
    frame1 = Frame(root) 
    frame1.pack(pady = 20 ) 

    b1 = Button(frame1,text="Exit") 
    b1.pack(pady=20) 
    
    b2 = Button( frame1, text = "Start") 
    b2.pack(pady = 20) 
    
    b3 = Button( frame1, text = "Reset") 
    b3.pack(pady = 20) 

    root.mainloop()
        

As you can see the background color of buttons and labels have different from the image color. The solution is to set the background color of buttons and label it as the color of the image.

    from tkinter import *
    
    root = Tk()
    root.geometry("400x400")

    bg = PhotoImage(file = "Your_image.png") 

    l1 = Label( root, image = bg) 
    l1.place(x = 0, y = 0) 
    
    l2 = Label( root, text = "Welcome", bg = "#88cffa") 
    l2.pack(pady = 50)
    
    frame1 = Frame(root, bg = "#88cffa") 
    frame1.pack(pady = 20 ) 

    b1 = Button(frame1,text="Exit") 
    b1.pack(pady=20) 
    
    b2 = Button( frame1, text = "Start") 
    b2.pack(pady = 20) 
    
    b3 = Button( frame1, text = "Reset") 
    b3.pack(pady = 20) 

    root.mainloop()
        

Note: This method will not work for multiple colors in image.

Method 2: Using Canvas methods.

    from tkinter import *
    
    root = Tk()
    root.geometry("400x400")

    # Add image file
    bg = PhotoImage(file = "Your_image.png") 

    # Create Canvas
    canvas1 = Canvas( root, width = 400, height = 400) 
    canvas1.pack(fill = "both", expand = True) 

    # Display image
    canvas1.create_image( 0, 0, image = bg, anchor = "nw") 
    
    # Create Text
    canvas1.create_text( 200, 250, text = "Welcome")
    
    # Create Buttons
    b1 = Button(frame1,text="Exit") 
    b2 = Button( frame1, text = "Start") 
    b3 = Button( frame1, text = "Reset") 
    
    # Display Buttons
    button1_canvas = canvas1.create_window( 100, 10, anchor = "nw", window = button1) 
    button2_canvas = canvas1.create_window( 100, 40, anchor = "nw", window = button2) 
    button3_canvas = canvas1.create_window( 100, 70, anchor = "nw", window = button3) 

    root.mainloop()
        

pyQT

22. Cryptography

BCrypt

What is hashing?

It’s a process of converting one string to another using a hash function. There are various types of hash functions but there are some basic similarities that are satisfied by all of them is that hashing is an irreversible process. i.e. conversion should be only one way, the length of hash should be fixed, and an input string should uniquely correspond with a hash so that we can compare them later, this makes it ideal for passwords and authentication.

Functions

• bcrypt.gensalt() - It is used to generate salt. Salt is a pseudorandom string that is added to the password. Since hashing always gives the same output for the same input so if someone has access to the database, hashing can be defeated. for that salt is added at end of the password before hashing. It doesn’t need any arguments and returns a pseudorandom string.
• bcrypt.hashpw() - It is used to create the final hash which is stored in a database.

Hashing passwords

The bcrypt.hashpw() function takes 2 arguments: A string (bytes) and Salt. Salt is random data used in the hashing function.

    import bcrypt

    password = 'password123'
    bytes = password.encode('utf-8')
    salt = bcrypt.gensalt()
    hash = bcrypt.hashpw(bytes, salt)

    print(hash)
    returns b'$2b$12$X541rM/jehMU5VANBoH9LOOT21NzmejB0hS6aO.g4IXYZWvod3cLq'
        

Checking passwords

Here we will check whether the user has entered the correct password or not, for that we can use bcrypt.checkpw(password, hash).

    import bcrypt

    password = 'passwordabc'
    bytes = password.encode('utf-8')
    salt = bcrypt.gensalt()
    hash = bcrypt.hashpw(bytes, salt)

    # Taking user entered password  
    userPassword =  'password000'
    userBytes = userPassword.encode('utf-8')

    result = bcrypt.checkpw(userBytes, hash)
    print(result)
    returns False
        

Fernet

Definition

The fernet module of the cryptography package has inbuilt functions for the generation of the key, encryption of plaintext into ciphertext, and decryption of ciphertext into plaintext using the encrypt and decrypt methods respectively.

Methods

• generate_key(): This method generates a new fernet key. The key must be kept safe as it is the most important component to decrypt the ciphertext. If the key is lost then the user can no longer decrypt the message. Also if an intruder or hacker gets access to the key they can not only read the data but also forge the data.
• encrypt(data): It encrypts data passed as a parameter to the method. The outcome of this encryption is known as a “Fernet token” which is basically the ciphertext. The encrypted token also contains the current timestamp when it was generated in plaintext. The encrypt method throws an exception if the data is not in bytes.
• decrypt(token,ttl=None): his method decrypts the Fernet token passed as a parameter to the method. On successful decryption the original plaintext is obtained as a result, otherwise an exception is thrown.

    from cryptography.fernet import Fernet

    key = Fernet.generate_key()
    f = Fernet(key)
    token = f.encrypt(b"welcome to codingforgeeks")
    print(token)

    d = f.decrypt(token)
    print(d)

    returns b'gAAAAABnjgC53fmZZ5OCqPXxradmfbFPljuzbw94BXzBPhFSUMZIhFcTXO_d2142cIs6CaMCjTP5XHjEr0FvCXWsaD0dcUUofXxoAYnQ09P5u2AAQCZHWHA='
            b'welcome to codingforgeeks'
    
        

The decrypted output has a ‘b’ in front of the original message which indicates the byte format. However, this can be removed using the decode() method while printing the original message. The program below implements the decode() method.

    from cryptography.fernet import Fernet

    key = Fernet.generate_key()
    f = Fernet(key)
    token = f.encrypt(b"welcome to codingforgeeks")
    print(token)

    d = f.decrypt(token)
    print(d.decode())

    returns b'gAAAAABnjgC53fmZZ5OCqPXxradmfbFPljuzbw94BXzBPhFSUMZIhFcTXO_d2142cIs6CaMCjTP5XHjEr0FvCXWsaD0dcUUofXxoAYnQ09P5u2AAQCZHWHA='
            welcome to codingforgeeks
    
        
Jump to Top