Learning Python#

Python has become the language for many as the first language they learn as it available on a lot of places like on Linux when you’re using a Raspberry Pi. It is also being used for data analytics purposes, developing websites, and embedded devices. The Python language specification has for all these purposes also different implementation like CPython, Jython, MicroPython and CircuitPython, but everyone references to CPython when they talk about Python.

Your first Python application#

Let start directly with the famous Hello World application in the Python shell. The Python shell can be used for very short applications like to run print(“Hello World”).

Running the Python interpreter on Linux#
$ python
Python 3.9.1 (default, Jan 12 2021, 16:56:42)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World.")
Hello World.
>>>

Python can also use file as the source to run the Hello World application and if we create a file hello.py with the content below we can execute it later.

The content of file hello.py#
1print("Hello World.")

Python can now use the file hello.py as a source and it nicely prints Hello World. to the screen.

Run hello.py with the Python interpreter#
$ python hello.py
Hello World.

Now that we have a quick and dirty way of running Hello World. we can take it to the next level and turn it a proper Python program you can execute on every Unix-like system with Python 3 installed. If we replace the content of hello.py with the example below then we can run it it again and should still give Hello World.

Example of a full Hello World program#
1#!/usr/bin/env python3
2
3def main():
4    print("Hello World.")
5
6
7if __name__ == "__main__":
8    main()

If we also add the execute bit to the file hello.py we can directly start it without prefexing it the Python interpreter. And again we get Hello World. on the screen.

Run hello.py directly from the commandline#
$ chmod +x hello.py
$ hello.py
Hello World

But what does this all mean? Let start with the first line where tell unix via a shebang to look the python3 interpreter via the env command. This guarantees that we always find the Python interpreter while we don’t set any hardcoded paths. In the Packages and virtual environments chapter we will go deeping into why this important when we start working with virtual environments.

1#!/usr/bin/env python3

Secondly we define a function called main and we put the print statement for Hello World. in this function. One thing that is different from other languages is that indentation is important and gives context to the statement.

3def main():
4    print("Hello World.")

The third section is that we call the function called main if we execute the file hello.py. The exact reason for why we do this is explained in the Modules chapter.

7if __name__ == "__main__":
8    main()

Note

Most examples will be based on this example and the main function will be modified.

Python Syntax#

Reserved keywords#

The Python language reserves a small set of keywords that cannot be used as variable names, function names, or any other identifiers:

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, the 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, the 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 end a function returns a generator

Indentation#

Python depends on indentation to follow the correct flow of execution. In the example below, we see that there is a possible error as Hello Jack. is being printed before anything else. Many will assume it will be printed after Hello John. as it is directly after it, but indentation wise it isn’t part of the main function.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     if 1 > 2:
 5         print("Hello World.")
 6     print("Hello John.")
 7
 8 print("Hello Jack.")
 9
10
11 if __name__ == "__main__":
12     main()
Output#
1 Hello Jack.
2 Hello John.

If we try to correct this error by adding a space before the print statement, then Python still gives an error as the indentation doesn’t match all other levels. Python is very similar to YAML and all the indentations needs to be the same. See PEP 8#indentation for a complete set of rules about indentation.

Example:#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     if 1 > 2:
 5         print("Hello World.")
 6     print("Hello John.")
 7 print("Hello Jack.")
 8
 9
10 if __name__ == "__main__":
11     main()
Output#
1   File "/workspaces/mastering-python/hello.py", line 7
2     print("Hello Jack.")
3                         ^
4 IndentationError: unindent does not match any outer indentation level

Note

Python has no hard guideline on indentation and while most developer choose to use 4 spaces, the requirements is to have at least 1 space for each level of indentation.

Comments#

Any line that starts with # will be ignored by Python.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     if 1 > 2:
 5         print("Hello World.")
 6     print("Hello John.")
 7     # print("Hello Jack.")
 8
 9
10 if __name__ == "__main__":
11     main()
Output#
1 Hello John.

Multiline comments can be done by starting every line with the #-sign.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     if 1 > 2:
 5         print("Hello World.")
 6     print("Hello John.")
 7     # print("Hello Jack.")
 8     # print("Hello James.")
 9
10
11 if __name__ == "__main__":
12     main()
Output#
1 Hello John.

For multiline comments Python also supports comments between triple quotes as in the example below.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     if 1 > 2:
 5         print("Hello World.")
 6     print("Hello John.")
 7     """
 8     print("Hello Jack.")
 9     print("Hello James.")
10     """
11
12
13 if __name__ == "__main__":
14     main()
Output#
1 Hello John.

Variables and Types#

No programs works without variables to store data values in while the program runs. Variables in Python are strong dynamically typed which mean you can change a variable from a number to a string by assignment, but a variable will not become a number when a string contains a number for example. This also means you may have to cast variable from a number to a string in some cases or vice versa.

Python has the following data types built-in by default, listed per category in the table below:

Category

Data type

Text Type:

str

Numeric Types:

int, float, complex

Sequence Types:

list, tuple, range

Mapping Type:

dict

Set Types:

set, frozenset

Boolean Type:

bool

Binary Types:

bytes, bytearray, memoryview

The basics about variables#

Let start with basic example based on our Hello World. application where we have two lines. And in this example we still present print directly with a string telling about two people called John and Jack, and their age.

Example: Printing strings directly#
1 #!/usr/bin/env python3
2
3 def main():
4     print("My name is John and I am 42.")
5     print("My name is Jack and I am also 42.")
6
7
8 if __name__ == "__main__":
9     main()
Output: Printing strings directly#
1 My name is John and I am 42.
2 My name is Jack and I am also 42

Lets put the name and age both in their own variable as a string and update the strings to concatenate the whole string together. Here we that Python used the +-sign to concatenate strings together.

Example: Printing concatenated strings#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     name = "John"
 5     age = "42"
 6     print("My name is " + name + " and I am " + age + ".")
 7     name = "Jack"
 8     print("My name is " + name + " and I am also " + age + ".")
 9
10
11 if __name__ == "__main__":
12     main()
Output: Printing concatenated strings#
1 My name is John and I am 42.
2 My name is Jack and I am also 42

Getting a variable type#

Python can also determine the data type of a variable with type(). This can become useful when importing data from unknown source and needs validation, or to determine if a variable needs to be casted.

Example: Determine the variable type#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     name = "John"
 5     age = 42
 6     print(type(name))
 7     print(type(age))
 8
 9
10 if __name__ == "__main__":
11     main()
Output: Determine the variable type#
1 <class 'str'>
2 <class 'int'>

Casting variables#

Python is flexible with its data types for variables, but Python does require type casting in some cases. Using a variable that contains a number that needs to concatenated with a string needs to be casted from an integer to a string. In the example below we forget to type cast a string and it fails.

Example: Invalid casting of an integer#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     name = "John"
 5     age = 42
 6     print("My name is " + name + " and I am " + age + ".")
 7
 8
 9 if __name__ == "__main__":
10     main()
Output: Invalid casting of an integer#
1 Traceback (most recent call last):
2   File "/workspaces/mastering-python/example.py", line 10, in <module>
3     main()
4   File "/workspaces/mastering-python/example.py", line 6, in main
5     print("My name is " + name + " and I am " + age + ".")
6 TypeError: can only concatenate str (not "int") to str

If we type cast the variable age from integer to string with the str() function it works perfectly. Other functions to type cast are int() and float().

Example: Casting an integer to a string#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     name = "John"
 5     age = 42
 6     print("My name is " + name + " and I am " + str(age) + ".")
 7
 8
 9 if __name__ == "__main__":
10     main()

Variable scope#

Variables are scope sensitive and in the example below we define the variable on a global level and can be read scopes of functions and methods. Having global variables isn’t a good idea as it leads to messy programming. For constants this is fine, but the variables should only be read from and not updated.

Example#
 1 #!/usr/bin/env python3
 2
 3 phrase = "Hello World."
 4
 5 def main():
 6     print(phrase)
 7
 8
 9 if __name__ == "__main__":
10     main()
Output#
1 Hello World.

Variables can have a global and local scope. In the example below we set the variable on a global level, but override it with a different value as a local variable.

Example#
 1 #!/usr/bin/env python3
 2
 3 phrase = "Hello World."
 4
 5 def main():
 6     phrase = "Hello People."
 7     print(phrase)
 8
 9
10 if __name__ == "__main__":
11     main()
Output#
1 Hello People.

Python also has the option to turn local variables in global variables as in the example below. The extra function setup() uses the keyword global to make the variable x a global variable.

Example#
 1 #!/usr/bin/env python3
 2
 3 phrase = "Hello World."
 4
 5 def setup():
 6     global phrase
 7     phrase = "Hello People."
 8
 9
10 def main():
11     print(phrase)
12
13
14 if __name__ == "__main__":
15     setup()
16     main()
Output#
1 Hello People.

Warning

Using global variables is considert bad programming and a risk as it can have unforeseen effects.

Variables are references#

Variables in Python don’t store the value assigned to them, but are a reference to where the value is stored in memory. With the function id() an unique identifier is returend for every object stored in memory, and for the CPython implementation this identifier matches the address in memory.

As Python works with references, copying a variable is in reality copying the reference towards the value and not the value itself. The example below shows this as the reference for var1 and var2 are the same after copying, and only changes for var2 when a new value is assigned.

Example: Copying variables and assigning a new value.#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     var1 = 'test string 1'
 5     var2 = var1
 6     print(id(var1))
 7     print(id(var2))
 8     var2 = 'test string 2'
 9     print(id(var2))
10
11
12 if __name__ == "__main__":
13     main()
Output: Copying variables and assigning a new value.#
1 140676515962032
2 140676515962032
3 140676516592816

Strings#

Strings in Python are an array of bytes representing Unicode characters and the length can be a single character or a sequence of characters. The elements of a string have no data type and can be accessed using the index operator. In Python strings are surrounds by either single quotation marks, or double quotation marks. PEP 8 describes no standard on how to use single or double-quotes:

Note

In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257.

Some tools like Black have a preference to have all strings and comments in double quotes, but both ways are correct.

The basics about strings#

The most basic form of a litereal string is one that is given directly to print().

Example: Print a litereal string.#
1 #!/usr/bin/env python3
2
3 def main():
4     print("Hello World.")
5
6
7 if __name__ == "__main__":
8     main()
Output: Print a litereal string.#
1 Hello World.

The second form is to assign a variable to a string and can be used by print() as a reference to the string.

Example: Print a string referenced by a variable.#
1 #!/usr/bin/env python3
2
3 def main():
4     phrase = "Hello World."
5     print(phrase)
6
7
8 if __name__ == "__main__":
9     main()
Output: Print a string referenced by a variable.#
 Hello World.

As seen in chapter Variables, variables can be joined with the +-sign and a string can also be concatenated with a variable.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     phrase_one = "Hello World."
 5     phrase_two = "And Goodbye."
 6     # Concatenate two variables
 7     print(phrase_one + phrase_two)
 8     # Concatenate two variables with a string
 9     print(phrase_one + " " + phrase_two)
10
11
12 if __name__ == "__main__":
13     main()
Output#
1 Hello World.And Goodbye.
2 Hello World. And Goodbye.

Strings can also be a multiline string with a newline character as part of the value. Python does take the indentation of a multiline string not into account and will the indentation will be part of the string. On Stack Overflow in question 2504411 possible solutions to work around this issue are discusses.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     phrase = """Hello World.
 5     And Goodbye."""
 6     print(phrase)
 7
 8
 9 if __name__ == "__main__":
10     main()
Output#
1 Hello World.
2     And Goodbye.

Strings are arrays#

Strings are like in other languages arrays and can be address in that way. The working of arrays is described in Arrays, but for now we read the second element of the array and print it.

1#!/usr/bin/env python3
2
3def main():
4    phrase = "Hello World."
5    print(phrase[1])
6
7
8if __name__ == "__main__":
9    main()
1e

As a strings is an array you can easily loop over all elements and get every element separately.

Example#
1 #!/usr/bin/env python3
2
3 def main():
4     for x in "Hello World.":
5         print(x)
6
7
8 if __name__ == "__main__":
9     main()
Output#
 1 H
 2 e
 3 l
 4 l
 5 o
 6
 7 W
 8 o
 9 r
10 l
11 d
12 .

String length#

The built-in function len() return the length of an object and used the internal method __len__() of the object to determine the length.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     phrase = "Hello World."
 5     # Using the built-in version
 6     print(len(phrase))
 7     # Using the internal method of an object
 8     print(phrase.__len__())
 9
10
11 if __name__ == "__main__":
12     main()
Output#
1 12
2 12

Checking a string#

With the in operator you can check if a string is in another string. On line 6 we check if the string "Hello" is in the string "Hello World." and the result is True. The second check on line 8 is checking if the string "Hello" isn’t in the string "Hello World." and the result is No, Hello World.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     phrase = "Hello World."
 5
 6     print("Hello" in phrase)
 7
 8     if "Hello" not in phrase:
 9         print("Yes, Hello World.")
10     else:
11         print("No, Hello World.")
12
13
14 if __name__ == "__main__":
15     main()
Output#
1 True
2 No, Hello World.

Slicing strings#

Example: Slicing strings#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     phrase = "Hello World."
 5     print(phrase[2:5])
 6     print(phrase[:5])
 7     print(phrase[2:])
 8     print(phrase[-5:-2])
 9
10
11 if __name__ == "__main__":
12     main()
Output: Slicing strings#
1 llo
2 Hello
3 llo World.
4 orl

String methods#

Convert a string to upper or lower case#

With String methods upper() and lower() a copy of the string is returned after all chareacters are converted to uppercase or lowercase.

Example: Converting a string to both upper- and lowercase#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     phrase = "Hello World."
 5     print(phrase.upper())
 6     print(phrase.lower())
 7
 8
 9 if __name__ == "__main__":
10     main()
Output: Converting a string to both upper- and lowercase#
1 HELLO WORLD.
2 hello world.

Note

Both methods follow the Unicode Standard and may for example still contain a lowercase character after calling upper() if that is defined in the Unicode Standard.

Trim a string#

The method strip() removes by default whitespace character from the string on both sides. With lstrip() or rstrip() the string is only being trimmed on the left or ride side.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     phrase = " Hello World. "
 5     print(phrase)
 6     print(phrase.strip())
 7     print(phrase.lstrip())
 8     print(phrase.rstrip())
 9
10
11 if __name__ == "__main__":
12     main()
Output#
1  Hello World.
2 Hello World.
3 Hello World.
4  Hello World.

The method strip() by default trims whitespace characters, but can also use other characters to trim a string.

Example#
1 #!/usr/bin/env python3
2
3 def main():
4     phrase = "Hello World."
5     print(phrase.strip("HeldW."))
6
7
8 if __name__ == "__main__":
9     main()
Output#
1 o Wor

Replacing a string#

The method replace() replaces a string with another string.

Example#
1 #!/usr/bin/env python3
2
3 def main():
4     phrase = "Hello World."
5     print(phrase.replace("W", "w"))
6
7
8 if __name__ == "__main__":
9     main()
Output#
1 Hello world.

Split and join#

The method split() splits a string into a list of strings.

Example#
1 #!/usr/bin/env python3
2
3 def main():
4     phrase = "Hello World."
5     print(phrase.split(" "))
6
7
8 if __name__ == "__main__":
9     main()
Output#
1 ['Hello', 'World.']

The method join() joins a list of strings into a string.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     phrases = ["Hello", "World."]
 5     separator = " "
 6     print(separator.join(phrases))
 7
 8
 9 if __name__ == "__main__":
10     main()
Output#
1 Hello World.

The method join() can also be used to join a list of strings into a string with a separator.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     phrases = {"wordOne": "Hello", "wordTwo": "World."}
 5     separator = "-"
 6     print(separator.join(phrases))
 7
 8
 9 if __name__ == "__main__":
10     main()
Output#
1 wordOne-wordTwo

Formatting strings#

The method format() formats a string with placeholders.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     name = "World"
 5     phrase = "Hello {}."
 6     print(phrase.format(name))
 7
 8
 9 if __name__ == "__main__":
10     main()
Output#
1 Hello World.

The method format() can also be used to format a string with a list for the placeholders.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     name_one = "Jack"
 5     name_two = "John"
 6     phrase = "Hello {} and {}."
 7     print(phrase.format(name_one, name_two))
 8
 9
10 if __name__ == "__main__":
11     main()
Output#
1 Hello Jack and John.

The placeholders for the method format() can also be used as keys in a dictionary.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     name_one = "Jack"
 5     name_two = "John"
 6     phrase = "Hello {1} and {0}."
 7     print(phrase.format(name_one, name_two))
 8
 9
10 if __name__ == "__main__":
11     main()
Output#
1 Hello John and Jack.

Escape characters#

Example#
1 #!/usr/bin/env python3
2
3 def main():
4     phrase = "Hello "World"."
5     print(phrase)
6
7
8 if __name__ == "__main__":
9     main()
Output#
1   File "/workspaces/mastering-python/example.py", line 4
2     phrase = "Hello "World"."
3                      ^
4 SyntaxError: invalid syntax
Example#
1 #!/usr/bin/env python3
2
3 def main():
4     phrase = "Hello \"World\"."
5     print(phrase)
6
7
8 if __name__ == "__main__":
9     main()
Output#
1 Hello "World".

Code

Result

\’

Single Quote

\\

Backslash

\n

New Line

\r

Carriage Return

\t

Tab

\b

Backspace

\f

Form Feed

\ooo

Octal value

\xhh

Hex value

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     phrase = "Hello\n \"World\"."
 5     print(phrase)
 6     phrase = 'Hello\n \"World\".'
 7     print(phrase)
 8
 9
10 if __name__ == "__main__":
11     main()
Output#
1 Hello
2  "World".

Numbers#

  • int

  • float

  • complex

The basics about numbers#

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     q = -1
 5     x = 1
 6     y = 3.14
 7     z = 1j
 8     print(type(q))
 9     print(type(x))
10     print(type(y))
11     print(type(z))
12
13
14 if __name__ == "__main__":
15     main()
Output#
1 <class 'int'>
2 <class 'int'>
3 <class 'float'>
4 <class 'complex'>

Type conversion#

Complex numbers cannot be converted into another number type

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     x = 1
 5     y = 3.14
 6     z = 1j
 7
 8     a = float(x)
 9     b = float(y)
10
11     print(a)
12     print(b)
13
14     print(type(a))
15     print(type(b))
16
17
18 if __name__ == "__main__":
19     main()

Generate a random number#

The module random can be used to genera

Example#
 1 #!/usr/bin/env python3
 2
 3 import random
 4
 5 def main():
 6     print(random.randrange(1, 10))
 7
 8
 9 if __name__ == "__main__":
10     main()

randint and seed

Note

The behavior of random.randrange() has changed and will only accept integer paramaters since Python 3.10 otherwise a ValueError or TypeError will be generated.

Absolute value#

Example#
 1 #!/usr/bin/env python3
 2
 3 import random
 4
 5 def main():
 6     print(abs(-1))
 7
 8
 9 if __name__ == "__main__":
10     main()
Output#
1 1

Using the math module#

A [math](https://docs.python.org/3/library/math.html) modules ships with Python for advanced calculations.

Example#
 1 #!/usr/bin/env python3
 2
 3 import math
 4
 5 def main():
 6     # print Pi
 7     print(math.pi)
 8     # Determine the smallest integer greater than or equal
 9     print(math.ceil(8.3))
10     # Determine the largest integer smaller than or equal
11     print(math.floor(8.3))
12     # Print the square root
13     print(math.sqrt(9))
14
15
16 if __name__ == "__main__":
17     main()
Output#
1 3.141592653589793
2 9
3 8
4 3.0

Converting between decimal, binary, octal, and hexadecimal#

Example#
 1 #!/usr/bin/env python3
 2
 3 import math
 4
 5 def main():
 6     value_dec = 128
 7     value_bin = 0b10000000
 8     value_oct = 0o200
 9     value_hex = 0x80
10
11     print("The value_decimal value of", value_dec, "is:")
12     print(bin(value_dec), "in binary.")
13     print(oct(value_dec), "in octal.")
14     print(hex(value_dec), "in hexadecimal.")
15
16     print("The binary value of", (value_bin), "is:")
17     print(int(value_bin), "in decimal.")
18     print(oct(value_bin), "in octal.")
19     print(hex(value_bin), "in hexadecimal.")
20
21     print("The octal value of", oct(value_oct), "is:")
22     print(int(value_oct), "in decimal.")
23     print(bin(value_oct), "in binary.")
24     print(hex(value_oct), "in hexadecimal.")
25
26     print("The hexvalue_decimal value of", hex(value_hex), "is:")
27     print(int(value_hex), "in decimal.")
28     print(bin(value_hex), "in binary.")
29     print(oct(value_hex), "in octal.")
30
31
32 if __name__ == "__main__":
33     main()
Output#
 1 The value_decimal value of 128 is:
 2 0b10000000 in binary.
 3 0o200 in octal.
 4 0x80 in hexadecimal.
 5 The binary value of 128 is:
 6 128 in decimal.
 7 0o200 in octal.
 8 0x80 in hexadecimal.
 9 The octal value of 0o200 is:
10 128 in decimal.
11 0b10000000 in binary.
12 0x80 in hexadecimal.
13 The hexvalue_decimal value of 0x80 is:
14 128 in decimal.
15 0b10000000 in binary.
16 0o200 in octal.

Booleans#

One of the built-in data types in Python is the Boolean data type and also follows Boolean algebra (see Boolean Algebra).

The basics about booleans#

A boolean is a value of either True or False. This value can be assigned to a variable or the result of an expression. In the following example the expressions are evaluated by Python on lines 4 to 6 and the result is printed. On lines 7 to 9 the result of the value is evaluated by bool() and printed. Python sees the value 0 as False and all other values as True.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     print(1 > 2)
 5     print(1 == 2)
 6     print(1 < 2)
 7     print(bool(0))
 8     print(bool(1))
 9     print(bool(2))
10
11
12 if __name__ == "__main__":
13     main()
Output#
1 False
2 False
3 True
4 False
5 True
6 True

The most common use of booleans is to check conditions. The following example checks if an expression is True or False and prints the result of the branch of the check condition.

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     x = 10
 5     y = 5
 6
 7     if x > y:
 8         print("x is greater than y")
 9     else:
10         print("x is not greater than y")
11
12
13 if __name__ == "__main__":
14     main()
Output#
1 x is greater than y

Some values are false#

Example#
 1 #!/usr/bin/env python3
 2
 3 class myClass():
 4     def __len__(self):
 5         return 0
 6
 7
 8 def main():
 9     myobj = myClass()
10     print(bool(myobj))
11
12
13 if __name__ == "__main__":
14     main()
Output#
1 False

Functions can also return a boolean#

Example#
 1 #!/usr/bin/env python3
 2
 3 def trueFunction():
 4     return True
 5
 6
 7 def main():
 8     if trueFunction():
 9         print("True")
10     else:
11         print("False")
12
13
14 if __name__ == "__main__":
15     main()
Output#
1 True

Boolean operators basics#

The rudimentary symmetric Boolean functions (logical connectives or logic gates) are:

  • NOT, negation or complement - which receives one input and returns true when that input is false (“not”)

  • AND or conjunction - true when all inputs are true (“both”)

  • OR or disjunction - true when any input is true (“either”)

  • XOR or exclusive disjunction - true when one of its inputs is true and the other is false (“not equal”)

Constructed Boolean operators:

  • NAND or Sheffer stroke - true when it is not the case that all inputs are true (“not both”)

  • NOR or logical nor - true when none of the inputs are true (“neither”)

  • XNOR or logical equality - true when both inputs are the same (“equal”)

The NOT operator#

Note

If A is NOT true, then Q is true

Value A

Result

0

1

1

0

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     value = True
 5
 6     if not value:
 7         print("True")
 8     else:
 9         print("False")
10
11
12 if __name__ == "__main__":
13     main()

The AND operator#

Note

If both A and B are true, then Q is true

Value A

Value B

Result

0

0

0

0

1

0

1

0

0

1

1

1

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     value_a = True
 5     value_b = False
 6
 7     if value_a and value_b:
 8         print("True")
 9     else:
10         print("False")
11
12
13 if __name__ == "__main__":
14     main()
Output#
1 False

The OR operator#

Note

If either A or B is true, then Q is true

Value A

Value B

Result

0

0

0

0

1

1

1

0

1

1

1

1

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     value_a = True
 5     value_b = False
 6
 7     if value_a or value_b:
 8         print("True")
 9     else:
10         print("False")
11
12
13 if __name__ == "__main__":
14     main()
Output#
1 True

The XOR operator#

Value A

Value B

Result

0

0

0

0

1

1

1

0

1

1

1

0

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     value_a = True
 5     value_b = False
 6
 7     if value_a xor value_b:
 8         print("True")
 9     else:
10         print("False")
11
12
13 if __name__ == "__main__":
14     main()
Output#
1 True

The NAND operator#

Value A

Value B

Result

0

0

1

0

1

1

1

0

1

1

1

0

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     value_a = True
 5     value_b = False
 6
 7     if not (value_a and value_b):
 8         print("True")
 9     else:
10         print("False")
11
12
13 if __name__ == "__main__":
14     main()
Output#
1 True

The NOR operator#

Value A

Value B

Result

0

0

1

0

1

0

1

0

0

1

1

0

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     value_a = True
 5     value_b = False
 6
 7     if not (value_a or value_b):
 8         print("True")
 9     else:
10         print("False")
11
12
13 if __name__ == "__main__":
14     main()
Output#
1 False

The XNOR operator#

Value A

Value B

Result

0

0

1

0

1

0

1

0

0

1

1

1

Example#
 1 #!/usr/bin/env python3
 2
 3 def main():
 4     value_a = True
 5     value_b = False
 6
 7     if not (value_a xor value_b):
 8         print("True")
 9     else:
10         print("False")
11
12
13 if __name__ == "__main__":
14     main()
Output#
1 False

Operators#

Arithmetic operators#

Unary operators

Operator

Name

Example

+

Addition

x + y

-

Subtraction

x - y

*

Multiplication

x * y

/

Division

x / y

%

Modulus

x % y

**

Exponentiation

x ** y

//

Floor division

x // y

Comparison operators#

Operator

Name

Example

==

Equal

x == y

!=

Not equal

x != y

>

Greater than

x > y

<

Less than

x < y

>=

Greater than or equal to

x >= y

<=

Less than or equal to

x <= y

Logical operators#

Operator

Description

Example

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#

Operator

Description

Example

is

Returns True if both variables are the same object

x is y

is not

Returns True if both variables are not the same object

x is not y

Membership operators#

Operator

Description

Example

in

Returns True if a sequence with the specified value is present in the object

x in y

not in

Returns True if a sequence with the specified value is not present in the object

x not in y

Bitwise operators#

A Bitwise operator operates on a bit string, a bit array or binary numeral and are basic actions that can directly be done by the processor itself. The processor uses the basic [boolean operators](#84-boolean-operators-basics) on bit level and can shift the bit string.

Operator

Name

Description

&

AND

Sets each bit to 1 if both bits are 1

|

OR

Sets each bit to 1 if one of two bits is 1

^

XOR

Sets each bit to 1 if only one of two bits is 1

~

NOT

Inverts all the bits

<<

Zero fill left shift

Shift left by pushing zeros in from the right and let the leftmost bits fall off

>>

Signed right shift

Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

The first example is applying AND on two signed integers. The processor converts the integers to bit strings and then applies the AND-table to every position between the two string. For 3 & 4 the result is 0 as there are no overlapping bits between the two integers. For 3 & 7 the result is 3 as the bits for number 3 are also in number 7 and will result matching number 3.

Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    # 3 = 0000 0011
 5    # 4 = 0000 0100 AND
 6    # 0 = 0000 0000
 7    print(3 & 4)
 8    # 3 = 0000 0011
 9    # 7 = 0000 0111 AND
10    # 3 = 0000 0011
11    print(3 & 7)
12
13
14if __name__ == "__main__":
15    main()

The next example is applying OR on two signed integers. The processor converts the integers to bit strings and then applies the OR-table to every position between the two string. For 3 | 4 the result is 7 as all bits that are 1 will end up in the result. For 3 | 7 the result is also 7 as the bits for number 3 are also in number 7 and will result matching number 7.

Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    # 3 = 0000 0011
 5    # 4 = 0000 0100 OR
 6    # 7 = 0000 0111
 7    print(3 | 4)
 8    # 3 = 0000 0011
 9    # 7 = 0000 0111 OR
10    # 7 = 0000 0111
11    print(3 | 7)
12
13
14if __name__ == "__main__":
15    main()

The next example is applying XOR on two signed integers. The processor converts the integers to bit strings and then applies the XOR-table to every position between the two string. For 3 | 4 the result is 7 as all bits that are 1 will end up in the result. For 3 | 7 the result is also 7 as the bits for number 3 are also in number 7 and will result matching number 7.

Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    # 3 = 0000 0011
 5    # 4 = 0000 0100 XOR
 6    # 7 = 0000 0111
 7    print(3 ^ 4)
 8    # 3 = 0000 0011
 9    # 7 = 0000 0111 XOR
10    # 4 = 0000 0100
11    print(3 ^ 7)
12
13
14if __name__ == "__main__":
15    main()
Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    #     3 = 0000 0011 NOT
 5    #    -4 = 1111 1100
 6    print(~3)
 7    #  127 = 0111 1111 NOT
 8    # -128 = 1000 0000
 9    print(~127)
10
11
12if __name__ == "__main__":
13    main()
Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    # 3 = 0000 0011 SHIFT RIGHT 1
 5    # 1 = 0000 0001
 6    print(3 >> 1)
 7    # Shift left
 8    # 3 = 0000 0011 SHIFT LEFT 1
 9    # 6 = 0000 0110
10    print(3 << 1)
11
12
13if __name__ == "__main__":
14    main()

Assignment operators#

Operator

Description

Example

Long form

=

Assignment

x = 2

x = 2

+=

Arithmetic Addition

x += 2

x = x + 2

-=

Arithmetic Subtraction

x -= 2

x = x - 2

*=

Arithmetic Multiplication

x *= 2

x = x * 2

/=

Arithmetic Division

x /= 2

x = x / 2

%=

Arithmetic Modulus

x %= 2

x = x % 2

//=

Arithmetic Exponentiation

x //= 2

x = x // 2

**=

Arithmetic Floor division

x **= 2

x = x ** 2

&=

Bitwise AND

x &= 2

x = x & 2

|=

Bitwise OR

x |= 2

x = x | 2

^=

Bitwise XOR

x ^= 2

x = x ^ 2

>>=

Bitwise Shift Left

x >>= 2

x = x >> 2

<<=

Bitwise Shift Right

x <<= 2

x = x << 2

Operator Precedence#

  • Highest precedence at top, lowest at bottom.

  • Operators in the same box evaluate left to right.

Operator

Description

()

Parentheses (grouping)

f(args...)

Function call

x[index:index]

Slicing

x[index]

Subscription

x.attribute

Attribute reference

**

Exponentiation

~x

Bitwise not

+x, -x

Positive, negative

*, /, %

Multiplication, division, remainder

+, -

Addition, subtraction

<<, >>

Bitwise shifts

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

in, not in, is, is not, <, <=, >, >=, <>, !=, ==

Comparisons, membership, identity

not x

Boolean NOT

and

Boolean AND

or

Boolean OR

lambda

Lambda expression

Collections#

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members

  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.

  • Set is a collection which is unordered and unindexed. No duplicate members.

  • Dictionary is a collection which is ordered* and changeable. No duplicate members.

Lists#

List basics#

Lists are used to store multiple items in a single variable. Lists can have duplicates and are ordered.

List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry", "apple", "cherry"]
 5    print(type(mylist))
 6    print(len(mylist))
 7    print(mylist)
 8
 9
10if __name__ == "__main__":
11    main()

List length len()

Output#
1<class 'list'>
25
3mylist = ["apple", "banana", "cherry", "apple", "cherry"]

A lists can contain different data types

Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4mylist1 = ["apple", "banana", "cherry"]
 5mylist2 = [1, 5, 7, 9, 3]
 6mylist3 = [True, False, False]
 7mylist4 = ["abc", 34, True, 40, "male"]
 8
 9    print(mylist1)
10    print(mylist2)
11    print(mylist3)
12    print(mylist4)
13
14
15if __name__ == "__main__":
16    main()

Using the list() constructor

List example#
1#!/usr/bin/env python3
2
3def main():
4    mylist = list(("apple", "banana", "cherry"))
5    print(mylist)
6
7
8if __name__ == "__main__":
9    main()

Addressing List items#

List items can directly be addressed

List example#
1#!/usr/bin/env python3
2
3def main():
4    mylist = ["apple", "banana", "cherry"]
5    print(mylist[1])
6
7
8if __name__ == "__main__":
9    main()
Output#
1banana
List example#
1#!/usr/bin/env python3
2
3def main():
4    mylist = ["apple", "banana", "cherry"]
5    print(mylist[-1])
6
7
8if __name__ == "__main__":
9    main()
Output#
1cherry

Indexes#

List example#
1#!/usr/bin/env python3
2
3def main():
4    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
5    print(mylist[2:5])
6
7
8if __name__ == "__main__":
9    main()
List example#
1#!/usr/bin/env python3
2
3def main():
4    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
5    print(mylist[:4])
List example#
1#!/usr/bin/env python3
2
3def main():
4    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
5    print(mylist[2:])
6
7
8if __name__ == "__main__":
9    main()

Negative indexes

List example#
1#!/usr/bin/env python3
2
3def main():
4    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
5    print(mylist[-4:-1])
6
7
8if __name__ == "__main__":
9    main()

Check if item exists

List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    if "apple" in mylist:
 6        print("Yes, 'apple' is in the fruits list")
 7
 8
 9if __name__ == "__main__":
10    main()

Changing an item

List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    mylist[1] = "blackcurrant"
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()

Changing a range of items

List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
 5    mylist[1:3] = ["blackcurrant", "watermelon"]
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()
List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
 5    mylist[1:2] = ["blackcurrant", "watermelon"]
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()
List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    mylist[1:3] = ["watermelon"]
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()

Append an item

List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    mylist.append("orange")
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()

Insert items

List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    mylist.insert(2, "watermelon")
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()

Extending a list

List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    tropical = ["mango", "pineapple", "papaya"]
 6    mylist.extend(tropical)
 7    print(mylist)
 8
 9
10if __name__ == "__main__":
11    main()

Adding

List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    mytuple = ("kiwi", "orange")
 6    mylist.extend(mytuple)
 7    print(mylist)
 8
 9
10if __name__ == "__main__":
11    main()

Remove a specified item

List example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    mylist.remove("banana")
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()
Remove a specified index item#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    mylist.pop(1)
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()
Remove the last item#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    mylist.pop()
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()
Remove the first item#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    del mylist[0]
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()
Sort the list#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    mylist.sort()
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()
Delete the entire list#
1#!/usr/bin/env python3
2
3def main():
4    mylist = ["apple", "banana", "cherry"]
5    del mylist
6
7
8if __name__ == "__main__":
9    main()
Clear the list#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mylist = ["apple", "banana", "cherry"]
 5    mylist.clear()
 6    print(mylist)
 7
 8
 9if __name__ == "__main__":
10    main()

Tuples#

Tuples are used to store multiple items in a single variable, and are ordered, allow duplicates

Example:

1#!/usr/bin/env python3
2
3def main():
4    mytuple = ("apple", "banana", "cherry", "apple")
5    print(mytuple)
6
7
8if __name__ == "__main__":
9    main()

Output:

1('apple', 'banana', 'cherry', 'apple')

The number of itmem in a tuple

Example:

1#!/usr/bin/env python3
2
3def main():
4    mytuple = ("apple", "banana", "cherry")
5    print(len(mytuple))
6
7
8if __name__ == "__main__":
9    main()

Output:

14

Determining the type

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple")
 5    print(type(mytuple))
 6    mytuple = ("apple",)
 7    print(type(mytuple))
 8
 9
10if __name__ == "__main__":
11    main()

Output:

1<class 'str'>
2<class 'tuple'>

Creating a tuple using the constructor

Example:

1#!/usr/bin/env python3
2
3def main():
4    mytuple = tuple(("apple", "banana", "cherry"))
5    print(mytuple)
6
7
8if __name__ == "__main__":
9    main()

Output:

1('apple', 'banana', 'cherry')

Accessing items

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple", "banana", "cherry")
 5    print(mytuple[1])
 6    print(mytuple[:1])
 7    print(mytuple[1:])
 8    print(mytuple[:-1])
 9
10
11if __name__ == "__main__":
12    main()

Check if an item exist in a tuple

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple", "banana", "cherry")
 5    if "apple" in mytuple:
 6        print("The apple is in mytuple")
 7
 8
 9if __name__ == "__main__":
10    main()

Adding an item

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple", "banana", "cherry")
 5    a = list(mytuple)
 6    a.append("cherry")
 7    mytuple = tuple(a)
 8    print(mytuple)
 9
10
11if __name__ == "__main__":
12    main()

Updating an item

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple", "banana", "cherry")
 5    a = list(mytuple)
 6    a[1] = "cherry"
 7    mytuple = tuple(a)
 8    print(mytuple)
 9
10
11if __name__ == "__main__":
12    main()

Remove an item

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple", "banana", "cherry")
 5    a = list(mytuple)
 6    a.remove("apple")
 7    mytuple = tuple(a)
 8    print(mytuple)
 9
10
11if __name__ == "__main__":
12    main()

Unpack a tuple

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple", "banana", "cherry")
 5    (a, b, c) = mytuple
 6    print(a)
 7    print(b)
 8    print(c)
 9
10
11if __name__ == "__main__":
12    main()

Unpack a tuple with an asterix

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple", "banana", "cherry", "orange", "lemon")
 5    (a, b, c*) = mytuple
 6    print(a)
 7    print(b)
 8    print(c)
 9    (a, b*, c) = mytuple
10    print(a)
11    print(b)
12    print(c)
13
14
15if __name__ == "__main__":
16    main()

Looping through a tuple

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple", "banana", "cherry")
 5    for a in mytuple:
 6        print(a)
 7
 8    for i in range(len(mytuple)):
 9        print(mytuple[i])
10
11    i = 0
12    while i < len(mytuple):
13        print(mytuple[i])
14        i = i + 1
15
16
17if __name__ == "__main__":
18    main()

Joining tuples

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple", "banana", "cherry")
 5    myothertuple = ("orange", "lemon")
 6    myfulltuple = mytuple + myothertuple
 7    print(myfulltuple)
 8
 9
10if __name__ == "__main__":
11    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("apple", "banana", "cherry")
 5    myfulltuple = mytuple * 2
 6    print(myfulltuple)
 7
 8
 9if __name__ == "__main__":
10    main()

Sets#

Sets are used to store multiple items in a single variable similar to lists, but doesn’t allow for duplicates in the set.

Example:

1#!/usr/bin/env python3
2
3def main():
4    myset = {"apple", "banana", "cherry", "apple"}
5    print(myset)
6
7
8if __name__ == "__main__":
9    main()

The number of items in a set

Example:

1#!/usr/bin/env python3
2
3def main():
4    myset = {"apple", "banana", "cherry"}
5    print(len(myset))
6
7
8if __name__ == "__main__":
9    main()

Which type is set?

Example:

1#!/usr/bin/env python3
2
3def main():
4    myset = {"apple", "banana", "cherry"}
5    print(type(myset))
6
7
8if __name__ == "__main__":
9    main()

Using the constructor for sets

Example:

1#!/usr/bin/env python3
2
3def main():
4    myset = set(("apple", "banana", "cherry"))
5    print(type(myset))
6
7
8if __name__ == "__main__":
9    main()

Add an item to a set

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    print(myset)
 6    myset.append("peach")
 7    print(myset)
 8
 9
10if __name__ == "__main__":
11    main()

Add a set to a set

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myotherset = {"peach", "strawberry"}
 6    print(myset)
 7    myset.update(myotherset)
 8    print(myset)
 9
10
11if __name__ == "__main__":
12    main()

Add any iterable to a set

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myotherset = ["peach", "strawberry"]
 6    print(myset)
 7    myset.update(myotherset)
 8    print(myset)
 9
10
11if __name__ == "__main__":
12    main()

Removing an existing item from a set

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myset.remove("banana")
 6    print(myset)
 7
 8
 9if __name__ == "__main__":
10    main()

Removing an possible existing item from a set

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myset.discard("peach")
 6    print(myset)
 7
 8
 9if __name__ == "__main__":
10    main()

Removing the last item from a set

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myset.pop()
 6    print(myset)
 7
 8
 9if __name__ == "__main__":
10    main()

Make the set empty

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myset.clear()
 6    print(myset)
 7
 8
 9if __name__ == "__main__":
10    main()

Delete a set

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    del myset
 6    print(myset)
 7
 8
 9if __name__ == "__main__":
10    main()

Looping

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    for a in myset:
 6        print(a)
 7
 8
 9if __name__ == "__main__":
10    main()

Joining sets with an union

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myotherset = {"peach", "strawberry"}
 6    myfullset = myset.union(myotherset)
 7    print(myfullset)
 8
 9
10if __name__ == "__main__":
11    main()

Merging a set into a sets

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myotherset = {"peach", "strawberry"}
 6    myset.update(myotherset)
 7    print(myset)
 8
 9
10if __name__ == "__main__":
11    main()

Update a set to keep only duplicates

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myotherset = {"apple", "peach", "strawberry"}
 6    myset.intersection_update(myotherset)
 7    print(myset)
 8
 9
10if __name__ == "__main__":
11    main()

Create a set to with only duplicates

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myotherset = {"apple", "peach", "strawberry"}
 6    deltaset = myset.intersection(myotherset)
 7    print(deltaset)
 8
 9
10if __name__ == "__main__":
11    main()

Update a set to keep all non-duplicates

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myotherset = {"apple", "peach", "strawberry"}
 6    myset.symmetric_difference_update(myotherset)
 7    print(myset)
 8
 9
10if __name__ == "__main__":
11    main()

Create a set to with all non-duplicates

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myset = {"apple", "banana", "cherry"}
 5    myotherset = {"apple", "peach", "strawberry"}
 6    deleaset = myset.symmetric_difference(myotherset)
 7    print(deltaset)
 8
 9
10if __name__ == "__main__":
11    main()

dictionaries#

Dictionaries are used to store values in key-value pairs. As of Python 3.7 dictionaries are ordered, and earlier Python versions are unordered. Also dictionaries are changable.

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    print(mydict)
11
12
13if __name__ == "__main__":
14    main()

Accessing an item

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    print(mydict["john"])
11
12
13if __name__ == "__main__":
14    main()

Dictionaries cannot have two items with the same key:

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "jack": "cherry",
 7        "john": "banana",
 8        "james": "apple"
 9        "jim": "banana"
10    }
11    print(mydict)
12
13
14if __name__ == "__main__":
15    main()

Determine the amount of items in a dictionary

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    print(len(mydict))
11
12
13if __name__ == "__main__":
14    main()

Data type within Python

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    print(type(mydict))
11
12
13if __name__ == "__main__":
14    main()

Output:

1<class 'dict'>

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    print(mydict)
11
12
13if __name__ == "__main__":
14    main()

Retrieve a value based on the key

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    a = mydict["jonn"]
11    print(a)
12
13
14if __name__ == "__main__":
15    main()

Retrieve a value based on the key with the get() method.

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    a = mydict.get("jonn")
11    print(a)
12
13
14if __name__ == "__main__":
15    main()

Retrieve all the keys

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    b = mydict.keys()
11    print(b)
12
13
14if __name__ == "__main__":
15    main()

Updating the dictionary will also update view on list of keys that was retrieved

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    b = mydict.keys()
11    print(b)
12    mydict["jane"] = "cherry"
13    print(b)
14
15
16if __name__ == "__main__":
17    main()

Retrieve all the values

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    c = mydict.values()
11    print(c)
12
13
14if __name__ == "__main__":
15    main()

Updating the dictionary will also update view on list of values that was retrieved

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    c = mydict.values()
11    print(c)
12    mydict["jim"] = "cherry"
13    mydict["jane"] = "cherry"
14    print(c)
15
16
17if __name__ == "__main__":
18    main()

Retrieve all the items

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    d = mydict.items()
11    print(d)
12
13
14if __name__ == "__main__":
15    main()

Updating the dictionary will also update view on list of items that was retrieved

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    c = mydict.items()
11    print(c)
12    mydict["jim"] = "cherry"
13    mydict["jane"] = "cherry"
14    print(c)
15
16
17if __name__ == "__main__":
18    main()

Check if an item exists

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    if "james" in mydict:
11        print("James exists")
12
13
14if __name__ == "__main__":
15    main()

Updating values and if the item doesn’t exist the item is created.

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    mydict["jim"] = "cherry"
11    print(mydict)
12    mydict.update({"jim", "apple"})
13    print(mydict)
14
15
16if __name__ == "__main__":
17    main()

Removing items

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    mydict.pop("jim")
11    print(mydict)
12    mydict.popitem()
13    print(mydict)
14    del mydict["john"]
15    print(mydict)
16    mydict.clear()
17    print(mydict)
18
19
20if __name__ == "__main__":
21    main()

Looping through a dictionary

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    for a in mydict:
11        print(a)
12    for a in mydict:
13        print(mydict[a])
14    for a in mydict.values():
15        print(a)
16    for a in mydict.keys():
17        print(a)
18    for a, b in mydict.items():
19        print(a, b)
20
21
22if __name__ == "__main__":
23    main()

Copying a dictionary

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    myotherdict = mydict.copy()
11    print(myotherdict)
12    myotherdict = dict(mydict)
13    print(myotherdict)
14
15
16if __name__ == "__main__":
17    main()

Make a reference of a dictionary

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": "apple",
 6        "john": "banana",
 7        "james": "apple"
 8        "jim": "banana"
 9    }
10    myotherdict = mydict
11    print(mydict)
12    print(myotherdict)
13    myotherdict["jane"] = "cherry"
14    print(mydict)
15    print(myotherdict)
16
17
18if __name__ == "__main__":
19    main()

Using nested dictionaries

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    mydict = {
 5        "jack": {
 6            "food": "apple"
 7            "drink": "water"
 8        },
 9        "john": {
10            "food": "banana"
11            "drink": "mildk"
12        }
13    }
14    print(mydict)
15
16
17if __name__ == "__main__":
18    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    order1 = {
 5        "food": "apple"
 6        "drink": "water"
 7    }
 8    order2 = {
 9        "food": "banana"
10        "drink": "mildk"
11    }
12    mydict = {
13        "jack": order1,
14        "john": order2
15    }
16    print(mydict)
17
18
19if __name__ == "__main__":
20    main()

Arrays#

Example:

1#!/usr/bin/env python3
2
3def main():
4    myarray = ["apple", "banana", "cherry"]
5    print(myarray)
6
7
8if __name__ == "__main__":
9    main()

List length len()

Example:

1#!/usr/bin/env python3
2
3def main():
4    myarray = ["apple", "banana", "cherry"]
5    print(len(myarray))
6
7
8if __name__ == "__main__":
9    main()

Looping an array

Example:

 1 #!/usr/bin/env python3
 2
 3 def main():
 4     myarray = ["apple", "banana", "cherry"]
 5     for a in myarray:
 6         print(a)
 7
 8
 9 if __name__ == "__main__":
10     main()

Adding an element

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myarray = ["apple", "banana", "cherry"]
 5    myarray.append("kiwi")
 6    print(myarray)
 7
 8
 9if __name__ == "__main__":
10    main()

Remove the first occurrence of an element

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myarray = ["apple", "banana", "cherry", "apple"]
 5    myarray.remove("apple")
 6    print(myarray)
 7
 8
 9if __name__ == "__main__":
10    main()

Remove an element of a position

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    myarray = ["apple", "banana", "cherry"]
 5    myarray.pop(1)
 6    print(myarray)
 7
 8
 9if __name__ == "__main__":
10    main()

Conditions#

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

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    a = 33
 5    b = 200
 6    if b > a:
 7        print("b is greater than a")
 8
 9
10if __name__ == "__main__":
11    main()

Indentation

 1#!/usr/bin/env python3
 2
 3def main():
 4    a = 33
 5    b = 200
 6    if b > a:
 7    print("b is greater than a") # you will get an error
 8
 9
10if __name__ == "__main__":
11    main()

if-then-elif#

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    a = 33
 5    b = 33
 6    if b > a:
 7        print("b is greater than a")
 8    elif a == b:
 9        print("a and b are equal")
10
11
12if __name__ == "__main__":
13    main()

if-then-else#

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    a = 200
 5    b = 33
 6    if b > a:
 7        print("b is greater than a")
 8    else:
 9        print("b is not greater than a")
10
11
12if __name__ == "__main__":
13    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    a = 200
 5    b = 33
 6    if b > a:
 7        print("b is greater than a")
 8    elif a == b:
 9        print("a and b are equal")
10    else:
11        print("a is greater than b")
12
13
14if __name__ == "__main__":
15    main()

Nested if-then-else#

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    x = 41
 5    if x > 10:
 6        print("Above ten,")
 7    if x > 20:
 8        print("and also above 20!")
 9    else:
10        print("but not above 20.")
11
12
13if __name__ == "__main__":
14    main()

Logical operators#

And

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    a = 200
 5    b = 33
 6    c = 500
 7    if a > b and c > a:
 8        print("Both conditions are True")
 9
10
11if __name__ == "__main__":
12    main()

Or

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    a = 200
 5    b = 33
 6    c = 500
 7    if a > b or a > c:
 8        print("At least one of the conditions is True")
 9
10
11if __name__ == "__main__":
12    main()

Shorthand and Conditional Expressions#

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    a = 2
 5    b = 330
 6    if a > b: print("a is greater than b")
 7
 8
 9if __name__ == "__main__":
10    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    a = 2
 5    b = 330
 6    print("A") if a > b else print("B")
 7
 8
 9if __name__ == "__main__":
10    main()

Ternary Conditional Operator

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    a = 2
 5    b = 330
 6    print("A") if a > b else print("B")
 7
 8
 9if __name__ == "__main__":
10    main()

Example:

1#!/usr/bin/env python3
2
3def main():
4    b = 330
5    print("A") if a > b else print("=") if a == b else print("B")
6
7
8if __name__ == "__main__":
9    main()

Functions#

The basics about functions#

Defining and calling a function

Example#
 1#!/usr/bin/env python3
 2
 3def my_function():
 4    print("Hello from a function")
 5
 6
 7def main():
 8    my_function()
 9
10
11if __name__ == "__main__":
12    main()

Calling a function multiple time and scope of the variables

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(fname):
 4    print(fname + " Refsnes")
 5
 6
 7def main():
 8    my_function("Emil")
 9    my_function("Tobias")
10    my_function("Linus")
11
12
13if __name__ == "__main__":
14    main()

Using return

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(x):
 4    return 5 * x
 5
 6
 7def main():
 8    print(my_function(3))
 9    print(my_function(5))
10    print(my_function(9))
11
12
13if __name__ == "__main__":
14    main()

Default values

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(country = "Norway"):
 4    print("I am from " + country)
 5
 6
 7def main():
 8    my_function("Sweden")
 9    my_function("India")
10    my_function()
11    my_function("Brazil")
12
13
14if __name__ == "__main__":
15    main()

Passing multiple arguments#

Index based with *args

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(*kids):
 4    print("The youngest child is " + kids[2])
 5
 6
 7def main():
 8    my_function("Emil", "Tobias", "Linus")
 9
10
11if __name__ == "__main__":
12    main()

Keyword based with **kwargs

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(**kid):
 4    print("His last name is " + kid["lname"])
 5
 6
 7def main():
 8    my_function(fname = "Tobias", lname = "Refsnes")
 9
10
11if __name__ == "__main__":
12    main()

Using yield instead of return#

Example#
 1#!/usr/bin/env python3
 2
 3def multi_yield():
 4    yield_str = "This will print the first string"
 5    yield yield_str
 6    yield_str = "This will print the second string"
 7    yield yield_str
 8
 9
10def main():
11    multi_obj = multi_yield()
12    print(next(multi_obj))
13    print(next(multi_obj))
14    print(next(multi_obj))
15
16
17if __name__ == "__main__":
18    main()

Map, Filter and Reduce#

The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(n):
 4    return len(n)
 5
 6
 7def main():
 8    x = map(my_function, ('apple', 'banana', 'cherry'))
 9    prin(x)
10    print(list(x))
11
12
13if __name__ == "__main__":
14    main()

The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.

Example#
 1#!/usr/bin/env python3
 2
 3def my_function(x):
 4    if x < 18:
 5        return False
 6    else:
 7        return True
 8
 9
10def main():
11    ages = [5, 12, 17, 18, 24, 32]
12    adults = filter(my_function, ages)
13    print(list(adults))
14
15
16if __name__ == "__main__":
17    main()

The functools.reduce()

Example#
 1#!/usr/bin/env python3
 2
 3from functools import reduce
 4
 5def my_function(a, b):
 6    result = a + b
 7    print(f"{a} + {b} = {result}")
 8    return result
 9
10
11def main():
12    numbers = [0, 1, 2, 3, 4]
13    reduce(my_function, numbers)
14
15
16if __name__ == "__main__":
17    main()

Introduction to Lambda#

A lambda function is an anonymous function

Syntax#
1lambda arguments : expression
Example#
1#!/usr/bin/env python3
2
3def main():
4    x = lambda a : a + 2
5    print(x(2))
6
7
8if __name__ == "__main__":
9    main()
Output#
14
Example#
1#!/usr/bin/env python3
2
3def main():
4    x = lambda a, b : a + b
5    print(x(2, 3))
6
7
8if __name__ == "__main__":
9    main()
Output#
15

Using Lambda functions#

Example#
 1#!/usr/bin/env python3
 2
 3def myDouble(x):
 4    return lambda a : a * x
 5
 6
 7def main():
 8    double = myDouble(2)
 9    print(double(3))
10    print(double(4))
11
12
13if __name__ == "__main__":
14    main()
Output#
16
28

Loops#

Programs are a sequence of instructions, but in some cases those sequences need to be repeated. For example to read all lines from a file, or do a calculation a certain number of times. Python supports both ways to execute a sequence of instructions until a criteria is met or for all elements in sequence.

While and For loops#

A while loop is a way to repeat a sequence of instructions until a certain condition is met. The example below will print i as long as it is smaller than 6. The condition is checked at the beginning of the loop and we need to manually increment i.

 1#!/usr/bin/env python3
 2
 3def main():
 4    i = 0
 5    while i < 6:
 6        print(i)
 7        i += 1
 8
 9
10if __name__ == "__main__":
11    main()

A second way is to use a for loop, but here we iterate over a sequence of values instead of evaluating a condition before the next loop. The example below will print the values of the sequence [0, 1, 2, 3, 4, 5] and will generate the same output as the previous example.

1#!/usr/bin/env python3
2
3def main():
4    for i in range(6):
5        print(i)
6
7
8if __name__ == "__main__":
9    main()

With

Old#

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    i = 1
 5    while i < 6:
 6        print(i)
 7        if i == 3:
 8            break
 9        i += 1
10
11
12if __name__ == "__main__":
13    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    i = 0
 5    while i < 6:
 6        i += 1
 7        if i == 3:
 8            continue
 9        print(i)
10
11
12if __name__ == "__main__":
13    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    i = 1
 5    while i < 6:
 6        print(i)
 7        i += 1
 8    else:
 9        print("i is no longer less than 6")
10
11
12if __name__ == "__main__":
13    main()

For loop#

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    fruits = ["apple", "banana", "cherry"]
 5    for x in fruits:
 6        print(x)
 7
 8
 9if __name__ == "__main__":
10    main()

Example:

1#!/usr/bin/env python3
2
3def main():
4    for x in "banana":
5        print(x)
6
7
8if __name__ == "__main__":
9    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    fruits = ["apple", "banana", "cherry"]
 5    for x in fruits:
 6        if x == "banana":
 7            break
 8        print(x)
 9
10
11if __name__ == "__main__":
12    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    fruits = ["apple", "banana", "cherry"]
 5    for x in fruits:
 6        if x == "banana":
 7            continue
 8        print(x)
 9
10
11if __name__ == "__main__":
12    main()

Example:

1#!/usr/bin/env python3
2
3def main():
4    for x in range(6):
5        print(x)
6
7
8if __name__ == "__main__":
9    main()

Example:

1#!/usr/bin/env python3
2
3def main():
4    for x in range(2, 6):
5        print(x)
6
7
8if __name__ == "__main__":
9    main()

Example:

1#!/usr/bin/env python3
2
3def main():
4    for x in range(2, 30, 3):
5        print(x)
6
7
8if __name__ == "__main__":
9    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    for x in range(6):
 5        print(x)
 6    else:
 7        print("Finally finished!")
 8
 9
10if __name__ == "__main__":
11    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    for x in range(6):
 5        if x == 3:
 6            break
 7        print(x)
 8    else:
 9        print("Finally finished!")
10
11
12if __name__ == "__main__":
13    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    adj = ["red", "big", "tasty"]
 5    fruits = ["apple", "banana", "cherry"]
 6
 7    for x in adj:
 8        for y in fruits:
 9            print(x, y)
10
11
12if __name__ == "__main__":
13    main()

User Input#

  • Python 3.6 uses the input() method.

  • Python 2.7 uses the raw_input() method

Example:

1 #!/usr/bin/env python3
2
3 def main():
4     username = input("Enter username:")
5     print("Username is: " + username)
6
7
8 if __name__ == "__main__":
9     main()

Note

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

Exception handling#

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    try:
 5        print(x)
 6    except:
 7        print("An exception occurred")
 8
 9
10if __name__ == "__main__":
11    main()

Output:

1An exception occurred

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    try:
 5        print(x)
 6    except SystemError:
 7        pass
 8
 9
10if __name__ == "__main__":
11    main()

Output:

1Traceback (most recent call last):
2  File "/workspaces/learning-python/test1.py", line 11, in <module>
3    main()
4  File "/workspaces/learning-python/test1.py", line 5, in main
5    print(x)
6NameError: name 'x' is not defined

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    x = 1
 5    try:
 6        print(x)
 7    except:
 8        print("System Error")
 9    else:
10        print("Everything fine")
11
12
13if __name__ == "__main__":
14    main()

Output:

11
2Everything fine

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    try:
 5        print(x)
 6    except:
 7        print("System Error")
 8    finally:
 9        print("The try-except works")
10
11
12if __name__ == "__main__":
13    main()

Output:

1System Error
2The try-except works

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    x = 1
 5    y = 0
 6
 7    if y == 0:
 8        raise Exception("Sorry, can not divide by zero")
 9    else:
10        print(x/y)
11
12if __name__ == "__main__":
13    main()

Output:

1Traceback (most recent call last):
2  File "/workspaces/learning-python/test1.py", line 13, in <module>
3    main()
4  File "/workspaces/learning-python/test1.py", line 8, in main
5    raise Exception("Sorry, can not divide by zero")
6Exception: Sorry, can not divide by zero

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    x = 1
 5    y = "zero"
 6
 7    if not type(y) is int:
 8        raise TypeError("Only integers are allowed")
 9    else:
10        if y == 0:
11            raise Exception("Sorry, can not divide by zero")
12        else:
13            print(x/y)
14
15
16if __name__ == "__main__":
17    main()

Output:

1Traceback (most recent call last):
2  File "/workspaces/learning-python/test1.py", line 16, in <module>
3    main()
4  File "/workspaces/learning-python/test1.py", line 8, in main
5    raise TypeError("Only integers are allowed")
6TypeError: Only integers are allowed

Working with Files#

Attribuut

Mode

Description

“r”

Read

Default value. 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

Default value. Text mode

“b”

Binary

Binary mode (e.g. images)

Example:

1#!/usr/bin/env python3
2
3def main():
4    f = open("demofile.txt")
5
6
7if __name__ == "__main__":
8    main()

Example:

1#!/usr/bin/env python3
2
3def main():
4    f = open("demofile.txt", "rt")
5
6
7if __name__ == "__main__":
8    main()

Example:

1#!/usr/bin/env python3
2
3def main():
4    f = open("demofile.txt", "r")
5    print(f.read())
6
7
8if __name__ == "__main__":
9    main()

Example:

1#!/usr/bin/env python3
2
3def main():
4    f = open("../demofile.txt", "r")
5    print(f.read())
6
7
8if __name__ == "__main__":
9    main()

Read only part of the file

Example:

1#!/usr/bin/env python3
2
3def main():
4    f = open("demofile.txt", "r")
5    print(f.read(5))
6
7
8if __name__ == "__main__":
9    main()

Read lines

Example:

1#!/usr/bin/env python3
2
3def main():
4    f = open("demofile.txt", "r")
5    print(f.readline())
6
7
8if __name__ == "__main__":
9    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    f = open("demofile.txt", "r")
 5    print(f.readline())
 6    print(f.readline())
 7
 8
 9if __name__ == "__main__":
10    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    f = open("demofile.txt", "r")
 5    for x in f:
 6        print(x)
 7
 8
 9if __name__ == "__main__":
10    main()

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    f = open("demofile.txt", "r")
 5    print(f.readline())
 6    f.close()
 7
 8
 9if __name__ == "__main__":
10    main()

open and read the file after the appending:

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    f = open("demofile2.txt", "a")
 5    f.write("Now the file has more content!")
 6    f.close()
 7
 8    #open and read the file after the appending:
 9    f = open("demofile2.txt", "r")
10    print(f.read())
11
12
13if __name__ == "__main__":
14    main()

open and read the file after the appending

Example:

 1#!/usr/bin/env python3
 2
 3def main():
 4    f = open("demofile3.txt", "w")
 5    f.write("Woops! I have deleted the content!")
 6    f.close()
 7
 8    f = open("demofile3.txt", "r")
 9    print(f.read())
10
11
12if __name__ == "__main__":
13    main()

“x”, “a”, “w”

Example:

1#!/usr/bin/env python3
2
3def main():
4    f = open("myfile.txt", "x")
5
6
7if __name__ == "__main__":
8    main()

Example:

1#!/usr/bin/env python3
2
3def main():
4    f = open("myfile.txt", "w")
5
6
7if __name__ == "__main__":
8    main()

Example:

 1#!/usr/bin/env python3
 2
 3import os
 4
 5def main():
 6    os.remove("demofile.txt")
 7
 8
 9if __name__ == "__main__":
10    main()

Example:

 1#!/usr/bin/env python3
 2
 3import os
 4
 5def main():
 6    if os.path.exists("demofile.txt"):
 7        os.remove("demofile.txt")
 8    else:
 9        print("The file does not exist")
10
11
12if __name__ == "__main__":
13    main()

Example:

 1#!/usr/bin/env python3
 2
 3import os
 4
 5def main():
 6    os.rmdir("demodir")
 7
 8
 9if __name__ == "__main__":
10    main()

Python Modules#

In Python, Modules are files with the .py extension that can be imported inside another Python file to reuse code between applications or break down a big application into smaller files for easier organization and more manageable code base. These modules contain constants, variables, functions and classes for example.

As modules in Python are files, they can be created and used in the same way as any other file. The only difference is that the module must be imported to be used. A module can also be a collection of files in a directory.

Create a file called mymodule.py with the following

Example module called mymodule.py#
1def greeting(name):
2    print("Hello, " + name)

In our main program we can import the module and can call the function defined in the module

Example program that imports module mymodule.py#
 1#!/usr/bin/env python3
 2
 3import mymodule
 4
 5def main():
 6    mymodule.greeting("John")
 7
 8
 9if __name__ == "__main__":
10    main()

A module can also contain functions and classes, but also variables of all types. If we extend the module with a variable, we can use it in our main program. As in the example below, we extend the module with a dictionary called person.

Example of variable in module mymodule.py#
4person = {
5    "name": "John",
6    "age": 42,
7    "country": "Ireland"
8}

We can now access the variable person and use age defined within person. The import of the module creates a namespace for the module, so we can access the variable via mymodule.person. This is also the reason why we can use the variable person in our main program or can be defined in another modules.

Example of accessing variable in module mymodule.py#
 1#!/usr/bin/env python3
 2
 3import mymodule
 4
 5def main():
 6    age = mymodule.person["age"]
 7    print(age)
 8
 9
10if __name__ == "__main__":
11    main()

Running the program that imports mymodule.py and uses the variable person shows that age is 42.

Output of printing variable age in module mymodule.py#
42

You can also import a certain section from a module

Example of importing a specified section from a module#
 1#!/usr/bin/env python3
 2
 3from mymodule import person
 4
 5def main():
 6    print(person["age"])
 7
 8
 9if __name__ == "__main__":
10    main()

We can rename a module during import

Example of renaming a module during import#
 1#!/usr/bin/env python3
 2
 3import mymodule as abc
 4
 5def main():
 6    age = abc.person["age"]
 7    print(age)
 8
 9
10if __name__ == "__main__":
11    main()
Example of importing a built-in module#
 1#!/usr/bin/env python3
 2
 3import platform
 4
 5def main():
 6    x = platform.system()
 7    print(x)
 8
 9
10if __name__ == "__main__":
11    main()
Example to show the content of a module#
 1#!/usr/bin/env python3
 2
 3import platform
 4
 5def main():
 6    x = dir(platform)
 7    print(x)
 8
 9
10if __name__ == "__main__":
11    main()
Output of dir(platform)#
['DEV_NULL', '_UNIXCONFDIR', '_WIN32_CLIENT_RELEASES', '_WIN32_SERVER_RELEASES', '__builtins__', '__cached__', '__copyright__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__version__', '_comparable_version', '_component_re', '_default_architecture', '_dist_try_harder', '_follow_symlinks', '_ironpython26_sys_version_parser', '_ironpython_sys_version_parser', '_java_getprop', '_libc_search', '_linux_distribution', '_lsb_release_version', '_mac_ver_xml', '_node', '_norm_version', '_parse_release_file', '_platform', '_platform_cache', '_pypy_sys_version_parser', '_release_filename', '_release_version', '_supported_dists', '_sys_version', '_sys_version_cache', '_sys_version_parser', '_syscmd_file', '_syscmd_uname', '_syscmd_ver', '_uname_cache', '_ver_output', '_ver_stages', 'architecture', 'collections', 'dist', 'java_ver', 'libc_ver', 'linux_distribution', 'mac_ver', 'machine', 'node', 'os', 'platform', 'popen', 'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation', 'python_revision', 'python_version', 'python_version_tuple', 're', 'release', 'subprocess', 'sys', 'system', 'system_alias', 'uname', 'uname_result', 'version', 'warnings', 'win32_ver']

Classes#

Example:

 1#!/usr/bin/env python3
 2
 3class MyClass:
 4    a = 42
 5
 6
 7def main():
 8    myobject = MyClass()
 9    print(myboject.a)
10
11
12if __name__ == "__main__":
13    main()

During the instantiation of a class the constructor method is called to initialize the object. In Python the method name __init__ is reserved for this purpose.

Example:

 1#!/usr/bin/env python3
 2
 3class Person:
 4    def __init__(self, name, age):
 5        self.name = name
 6        self.age = age
 7
 8
 9def main():
10    person1 = Person("John", 42)
11
12    print(person1.name)
13    print(person1.age)
14
15
16if __name__ == "__main__":
17    main()

Object methods are functions that belong to the object and operation withing the context of the current object.

Example:

 1#!/usr/bin/env python3
 2
 3class Person:
 4    def __init__(self, name, age):
 5        self.name = name
 6        self.age = age
 7
 8    def myfunc(self):
 9        print("My name is " + self.name)
10
11
12def main():
13    person1 = Person("John", 42)
14    person1.myfunc()
15
16
17if __name__ == "__main__":
18    main()

The self parameter is a reference to the current instance of the class and has been specified in [PEP-8][arguments], but isn’t a reserved keyword. The name of first argument can be anything you want.

Example:

 1#!/usr/bin/env python3
 2
 3class Person:
 4    def __init__(abc, name, age):
 5        abc.name = name
 6        abc.age = age
 7
 8    def myfunc(xyz):
 9        print("My name is " + xyz.name)
10
11
12def main():
13    person1 = Person("John", 42)
14    person1.myfunc()
15
16
17if __name__ == "__main__":
18    main()

Modify an object property

Example:

1person1.age = 40

Delete an object property

Example:

1del person1.age

Delete an object

Example:

1del person1

Example:

 1#!/usr/bin/env python3
 2
 3class Person:
 4    def __init__(self, name, age):
 5        self.name = name
 6        self.age = age
 7
 8    def myfunc(self):
 9        print("My name is " + self.name)
10
11class Engineer(Person):
12    pass
13
14
15def main():
16    person1 = Person("John", 42)
17    person1.myfunc()
18
19
20if __name__ == "__main__":
21    main()

Example:

 1#!/usr/bin/env python3
 2
 3class Person:
 4    def __init__(self, name, age):
 5        self.name = name
 6        self.age = age
 7
 8    def myfunc(self):
 9        print("My name is " + self.name)
10
11class Engineer(Person):
12    def __init__(self, name, age, field):
13        Person.__init__(name, age)
14        self.field = field
15
16
17def main():
18    engineer1 = Engineer("John", 42, "Electronics")
19    engineer1.myfunc()
20
21
22if __name__ == "__main__":
23    main()

Example:

 1#!/usr/bin/env python3
 2
 3class Person:
 4    def __init__(self, name, age):
 5        self.name = name
 6        self.age = age
 7
 8    def myfunc(self):
 9        print("My name is " + self.name)
10
11class Engineer(Person):
12    def __init__(self, name, age, field):
13        super().__init__(name, age)
14        self.field = field
15
16
17def main():
18    engineer1 = Engineer("John", 42, "Electronics")
19    engineer1.myfunc()
20
21
22if __name__ == "__main__":
23    main()

Example:

 1#!/usr/bin/env python3
 2
 3class Memory:
 4
 5    def __init__(self, size: int = 65536) -> None:
 6        self.size = size
 7        self.memory = [0] * self.size
 8        for i in range(self.size):
 9            self.memory[i] = 0x00
10
11    def get(self, address: int) -> int:
12        return self.memory[address]
13
14    def set(self, address: int, value: int) -> int:
15        self.memory[address] = value
16        return self.memory[address]
17
18
19def main():
20    memory = Memory()
21    memory.set(1, 2)
22    print(memory.get(1))
23
24if __name__ == "__main__":
25    main()

Example:

 1#!/usr/bin/env python3
 2
 3class Memory:
 4
 5    def __init__(self, size: int = 65536) -> None:
 6        self.size = size
 7        self.memory = [0] * self.size
 8        for i in range(self.size):
 9            self.memory[i] = 0x00
10
11    def __getitem__(self, address: int) -> int:
12        return self.memory[address]
13
14    def __setitem__(self, address: int, value: int) -> int:
15        self.memory[address] = value
16        return self.memory[address]
17
18
19def main():
20    memory = Memory()
21    memory[1] = 2
22
23
24if __name__ == "__main__":
25    main()

Magic Method

When it gets invoked (example)

Explanation

__new__(cls [,...])

instance = MyClass(arg1, arg2)

__new__ is called on instance creation

__init__(self [,...])

instance = MyClass(arg1, arg2)

__init__ is called on instance creation

__cmp__(self, other)

self == other, self > other, etc.

Called for any comparison

__pos__(self)

+self

Unary plus sign

__neg__(self)

-self

Unary minus sign

__invert__(self)

~self

Bitwise inversion

__index__(self)

x[self]

Conversion when object is used as index

__nonzero__(self)

bool(self)

Boolean value of the object

__getattr__(self, name)

self.name # name doesn’t exist

Accessing nonexistent attribute

__setattr__(self, name, val)

self.name = val

Assigning to an attribute

__delattr__(self, name)

del self.name

Deleting an attribute

__getattribute__(self, name)

self.name

Accessing any attribute

__getitem__(self, key)

self[key]

Accessing an item using an index

__setitem__(self, key, val)

self[key] = val

Assigning to an item using an index

__delitem__(self, key)

del self[key]

Deleting an item using an index

__iter__(self)

for x in self

Iteration

__contains__(self, value)

value in self, value not in self

Membership tests using in

__call__(self [,...])

self(args)

“Calling” an instance

__enter__(self)

with self as x:

with statement context managers

__exit__(self, exc, val, trace)

with self as x:

with statement context managers

__getstate__(self)

pickle.dump(pkl_file, self)

Pickling

__setstate__(self)

data = pickle.load(pkl_file)

Pickling

Iterators#

An interator is an object that contains a countable number of values and can be interated upon. Every object which implements the interator protocol with methods __iter__ and __next__.

Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("red", "big", "tasty")
 5    myit = iter(mytuple)
 6
 7    print(next(myit))
 8    print(next(myit))
 9    print(next(myit))
10
11
12if __name__ == "__main__":
13    main()
Output#
1red
2big
3tasty
Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mystr = "red"
 5    myit = iter(mystr)
 6
 7    print(next(myit))
 8    print(next(myit))
 9    print(next(myit))
10
11
12if __name__ == "__main__":
13    main()
Output#
1r
2e
3d
Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mytuple = ("red", "big", "tasty")
 5
 6    for x in mytuple:
 7        print(x)
 8
 9
10if __name__ == "__main__":
11    main()
Output#
1red
2big
3tasty
Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    mystr = "red"
 5
 6    for x in mystr:
 7        print(x)
 8
 9
10if __name__ == "__main__":
11    main()
Output#
1r
2e
3d
Example#
 1#!/usr/bin/env python3
 2
 3class MyCounter:
 4    def __iter__(self):
 5        self.i = 1
 6        return self
 7
 8    def __next__(self):
 9        j = self.i
10        self.i += 1
11        return j
12
13
14def main():
15    mycounter = MyCounter()
16    myit = iter(mycounter)
17
18    print(next(myit))
19    print(next(myit))
20    print(next(myit))
21    print(next(myit))
22
23
24if __name__ == "__main__":
25    main()
Output#
11
22
33
44
Example#
 1#!/usr/bin/env python3
 2
 3class MyCounter:
 4    def __iter__(self):
 5        self.i = 1
 6        return self
 7
 8    def __next__(self):
 9        if self.i <= 5:
10            j = self.i
11            self.i += 1
12            return j
13        else:
14            raise StopIteration
15
16
17def main():
18    mycounter = MyCounter()
19    myit = iter(mycounter)
20
21    for x in myit:
22        print(x)
23
24
25if __name__ == "__main__":
26    main()
Output#
11
22
33
44
55

JSON#

JSON, or JavaScript Object Notation, is a syntax for serializing different data types in human-readable text form. Within Python it is implemented as the json module and the data model is similar as a dictionary.

Python has a built-in JSON parser called the json module. This module can be used to convert JSON data to Python objects. In the example below a JSON string is converted to a Python dictionary with json.loads() and can be accessed as a Python dictionary.

Example#
 1#!/usr/bin/env python3
 2
 3import json
 4
 5def main():
 6    x =  '{"name":"jack","age":42,"city":"Chicago"}'
 7    y = json.loads(x)
 8    print(y["age"])
 9
10
11if __name__ == "__main__":
12    main()
Output#
142

The Python module json can be used to convert Python objects to JSON data. In the example below a Python dictionary is converted to a JSON string with json.dumps().

Example#
 1#!/usr/bin/env python3
 2
 3import json
 4
 5def main():
 6    x = {
 7        "name": "Jack",
 8        "age": 42,
 9        "city": "Chicago"
10    }
11    y = json.dumps(x)
12    print(y)
13
14
15if __name__ == "__main__":
16    main()
Output#
1"{ \"name\":\"jack\", \"age\":42, \"city\":\"Chicago\"}"

When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript) equivalent:

Python

JSON

dict

Object

list

Array

tuple

Array

str

String

int

Number

float

Number

True

true

False

false

None

null

Example#
 1#!/usr/bin/env python3
 2
 3import json
 4
 5def main():
 6    print(json.dumps({"name": "Jack", "age": 42}))
 7    print(json.dumps(["apple", "bananas"]))
 8    print(json.dumps(("apple", "bananas")))
 9    print(json.dumps("hello"))
10    print(json.dumps(42))
11    print(json.dumps(31.76))
12    print(json.dumps(True))
13    print(json.dumps(False))
14    print(json.dumps(None))
15
16
17if __name__ == "__main__":
18    main()
Output#
1"{"name":"Jack","age":42}"
2"[\"apple\",\"bananas\"]"
3"[\"apple\",\"bananas\"]"
4"\"hello\""
5"42"
6"31.76"
7"true"
8"false"
9"null"

Use the indent parameter to define the numbers of indents:

Example#
1json.dumps(x, indent=4)

Use the separators parameter to change the default separator:

Example#
1json.dumps(x, indent=4, separators=(". ", " = "))

Use the sort_keys parameter to specify if the result should be sorted or not:

Example#
1json.dumps(x, indent=4, sort_keys=True)

Regular Expressions#

A Regular Expression, also called RegEx, is a sequence of characters that forms a search pattern for text.

Python supports regular expressions with a built-in module called re. In the example below we will use the re module to search for a pattern in a string and print the result.

Example#
 1#!/usr/bin/env python3
 2
 3import re
 4
 5def main():
 6    txt = "Hello great world"
 7    x = re.search("^Hello.*world$", txt)
 8    if x:
 9        print("YES! We have a match!")
10    else:
11        print("No match")
12
13if __name__ == "__main__":
14    main()

Output:

1YES! We have a match!

In the previous example we used the ^ and $ metacharacters to search for a pattern at the beginning and end of a string. Beside these two metacharacters there are other metacharacters that we will use in the next examples and are listed in the table below.

Character

Description

Example

[]

A set of characters

"[a-m]"

\

Signals a special sequence (can also be used to escape special characters)

"\d"

.

Any character (except newline character)

"he..o"

^

Starts with

"^hello"

$

Ends with

"world$"

*

Zero or more occurrences

"aix*"

+

One or more occurrences

"aix+"

{}

Exactly the specified number of occurrences

"al{2}"

|

Either or

"error|failed"

()

Capture and group

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

Character

Description

Example

\A

Returns a match if the specified characters are at the beginning of the string

“AThe”

\b

Returns a match where the specified characters are at the beginning or at the end of a word(the “r” in the beginning is making sure that the string is being treated as a “raw string”)

r”bain” r”ainb”

\B

Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word (the “r” in the beginning is making sure that the string is being treated as a “raw string”)

r”Bain” r”ainB”

\d

Returns a match where the string contains digits (numbers from 0-9)

“d”

\D

Returns a match where the string DOES NOT contain digits

“D”

\s

Returns a match where the string contains a white space character

“s”

\S

Returns a match where the string DOES NOT contain a white space character

“S”

\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”

\W

Returns a match where the string DOES NOT contain any word characters

“W”

\Z

Returns a match if the specified characters are at the end of the string

“SpainZ”

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

Set

Description

[arn]

Returns a match where one of the specified characters (a, r, or n) are present

[a-n]

Returns a match for any lower case character, alphabetically between a and n

[^arn]

Returns a match for any character EXCEPT a, r, and n

[0123]

Returns a match where any of the specified digits (0, 1, 2, or 3) are present

[0-9]

Returns a match for any digit between 0 and 9

[0-5][0-9]

Returns a match for any two-digit numbers from 00 and 59

[a-zA-Z]

Returns a match for any character alphabetically between a and z, lower case OR upper case

[+]

In sets, +, *, .,  |, (), $, {} has no special meaning, so [+] means: return a match for any + character in the string

Example#
 1#!/usr/bin/env python3
 2
 3import re
 4
 5def main():
 6    txt = "Hello great world"
 7    x = re.findall("[arn]", txt)
 8    print(x)
 9
10if __name__ == "__main__":
11    main()

findall()#

Returns a list containing all matches

Example#
 1#!/usr/bin/env python3
 2
 3import re
 4
 5def main():
 6    txt = "Hello great world"
 7    x = re.findall("ea", txt)
 8    print(x)
 9
10if __name__ == "__main__":
11    main()

split()#

Returns a list where the string has been split at each match

Example#
 1#!/usr/bin/env python3
 2
 3import re
 4
 5def main():
 6    txt = "Hello great world"
 7    x = re.split("\s", txt)
 8    print(x)
 9
10if __name__ == "__main__":
11    main()

sub()#

Replaces one or many matches with a string

Example#
 1#!/usr/bin/env python3
 2
 3import re
 4
 5def main():
 6    txt = "Hello great world"
 7    x = re.sub("\s", "9", txt)
 8    print(x)
 9
10if __name__ == "__main__":
11    main()
Example#
 1#!/usr/bin/env python3
 2
 3import re
 4
 5def main():
 6    txt = "Hello great world"
 7    x = re.sub("\s", "9", txt, 2)
 8    print(x)
 9
10if __name__ == "__main__":
11    main()

matching#

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.

Example#
 1#!/usr/bin/env python3
 2
 3import re
 4
 5def main():
 6    txt = "Hello great world"
 7    x = re.search("ea", txt)
 8    print(x)
 9
10if __name__ == "__main__":
11    main()

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.

  • .string() returns the string passed into the function

  • .group() returns the part of the string where there was a match

span()#

Example#
 1#!/usr/bin/env python3
 2
 3import re
 4
 5def main():
 6    txt = "Hello great world"
 7    x = re.search(r"\bS\w+", txt)
 8    print(x.span())
 9
10if __name__ == "__main__":
11    main()

string()#

Example#
 1#!/usr/bin/env python3
 2
 3import re
 4
 5def main():
 6    txt = "Hello great world"
 7    x = re.search(r"\bS\w+", txt)
 8    print(x.string())
 9
10if __name__ == "__main__":
11    main()

group()#

Example#
 1#!/usr/bin/env python3
 2
 3import re
 4
 5def main():
 6    txt = "Hello great world"
 7    x = re.search(r"\bS\w+", txt)
 8    print(x.group())
 9
10if __name__ == "__main__":
11    main()

Packages and virtual environments#

PIP is a package manager for Python for packages or modules

Since Python 3.3, you can create and start a virtual environment as the venv module is now part of the standard library. We will use the venv module to create a virtual environment in the current directory.

1 $ python3 -m venv .venv
2 $

In the bin directory of the virtual environment, there is a file called activate. This file contains the command to activate the virtual environment with the Bash or Zsh shell.

1 $ source .venv/bin/activate
2 (.venv) $ python
3 Python 3.9.2 (default, Feb 20 2021, 00:00:00)
4 [GCC 10.2.1 20201125 (Red Hat 10.2.1-9)] on linux
5 Type "help", "copyright", "credits" or "license" for more information.
6 >>> import sys
7 >>> sys.path
8 ['', '/usr/lib64/python39.zip', '/usr/lib64/python3.9', '/usr/lib64/python3.9/lib-dynload', '/workspaces/python-examples/.venv/lib64/python3.9/site-packages', '/workspaces/python-examples/.venv/lib/python3.9/site-packages']
9 >>>

Since Python 3.4 the pip package is part of the standard library and can be called as a module or as an executable.

Example:

1 $ source .venv/bin/activate
2 (.venv) $ python -m pip search camelcase
3 (.venv) $ pip search camelcase

Note

The pip package can only be upgraded when it is called as a module.

Warning

Since late 2020 the search functionality of the pip package has been deprecated due to performance issues on PyPi infrastructure.

Example:

1 (.venv) $ pip install camelcase
2 Collecting camelcase
3 Using cached camelcase-0.2.tar.gz (1.3 kB)
4 Using legacy 'setup.py install' for camelcase, since package 'wheel' is not installed.
5 Installing collected packages: camelcase
6     Running setup.py install for camelcase ... done
7 Successfully installed camelcase-0.2

Example:

 1 (.venv) $ pip install camelcase==0.1
 2 Collecting camelcase==0.1
 3 Downloading camelcase-0.1.tar.gz (1.2 kB)
 4 Using legacy 'setup.py install' for camelcase, since package 'wheel' is not installed.
 5 Installing collected packages: camelcase
 6 Attempting uninstall: camelcase
 7     Found existing installation: camelcase 0.2
 8     Uninstalling camelcase-0.2:
 9     Successfully uninstalled camelcase-0.2
10     Running setup.py install for camelcase ... done
11 Successfully installed camelcase-0.1

Example:

 1 (.venv) $ pip install --upgrade camelcase
 2 Collecting camelcase
 3 Using cached camelcase-0.2.tar.gz (1.3 kB)
 4 Using legacy 'setup.py install' for camelcase, since package 'wheel' is not installed.
 5 Installing collected packages: camelcase
 6 Attempting uninstall: camelcase
 7     Found existing installation: camelcase 0.1
 8     Uninstalling camelcase-0.1:
 9     Successfully uninstalled camelcase-0.1
10     Running setup.py install for camelcase ... done
11 Successfully installed camelcase-0.2

Example:

 1 (.venv) $ pip show camelcase
 2 Name: camelcase
 3 Version: 0.2
 4 Summary: Converts a string to Camel Case
 5 Home-page: http://www.craigaddyman.com
 6 Author: Craig Addyman
 7 Author-email: [email protected]
 8 License: MIT
 9 Location: /workspaces/mastering-python/.venv/lib/python3.9/site-packages
10 Requires:
11 Required-by:

Output:

1 (.venv) $ pip list
2 Package    Version
3 ---------- -------
4 camelcase  0.2
5 pip        20.2.2
6 setuptools 49.1.3

Example:

1 (.venv) $ pip freeze > requirements.txt
2 (.venv) $ cat requirements.txt
3 camelcase==0.2

Example:

1 (.venv) $ pip uninstall camelcase
2 Found existing installation: camelcase 0.2
3 Uninstalling camelcase-0.2:
4 Would remove:
5     /workspaces/mastering-python/.venv/lib/python3.9/site-packages/camelcase-0.2-py3.9.egg-info
6     /workspaces/mastering-python/.venv/lib/python3.9/site-packages/camelcase/*
7 Proceed (y/n)? y
8 Successfully uninstalled camelcase-0.2

Example:

1 (.venv) $ pip install -r requirements.txt
2 Collecting camelcase==0.2
3 Using cached camelcase-0.2.tar.gz (1.3 kB)
4 Using legacy 'setup.py install' for camelcase, since package 'wheel' is not installed.
5 Installing collected packages: camelcase
6     Running setup.py install for camelcase ... done
7 Successfully installed camelcase-0.2