Nothing Special   »   [go: up one dir, main page]

A Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 103

Python

Contents:
 Python syntax --- page 5
 Python comments --- page 6
 Python variables --- page 6
 Python data types --- page 10
 Python numbers--- page 12
 Python casting --- page 14
 Python strings --- page 16
 Python modify text --- page 19
 Python booleans --- page 22
 Python operators --- page 25
 Python lists --- page 28
 Python tuples --- page 36
 Python sets --- page 39
 Python dictionaries --- page 45
 Python if… else --- page 51
 Python while loops --- page 54
 Python for loops --- page 57
 Python functions --- page 59
 Python lambda --- page 65
 Python objects/classes --- page 66
 The _init_() function --- page 67
 Python inheritance --- page 70

1
 Python iterators --- page 72
 Python scope --- page 76
 Python modules --- page 79
 Python dates --- page 81
 Python math --- page 83
 Python RegEx --- page 86
 Python try… except --- page 90
 Python user input --- page 93
 Python string formatting --- page 94
 Python file handling --- page 96

2
Introduction
3
It is used for:
 web development (server-side),
 software development,
 mathematics,
 system scripting.

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create
workflows.
 Python can connect to database systems. It can also read
and modify files.
 Python can be used to handle big data and perform
complex mathematics.
 Python can be used for rapid prototyping, or for
production-ready software development.

Python syntax
4
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code
is for readability only, the indentation in Python is very
important.

Python uses indentation to indicate a block of code.

if 5 > 2:
print("Five is greater than two!")

in Python, variables are created when you assign a value to it:

x=5
y = "Hello, World!"

Python has no command for declaring a variable.

Python comments
5
Python has commenting capability for the purpose of in-code
documentation.

Comments start with a #, and Python will render the rest of the
line as a comment:

#This is a comment.

Comments can be placed at the end of a line, and Python will


ignore the rest of the line
A comment does not have to be text that explains the code, it
can also be used to prevent Python from executing code

Python variables
Variables are containers for storing data values.
A variable is created the moment you first assign a value to it.
x=5

6
print(x)

Variables do not need to be declared with any particular type,


and can even change type after they have been set.

x=4
x = "Sally"
print(x)

If you want to specify the data type of a variable, this can be


done with casting.

x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0

You can get the data type of a variable with the type() function.

x=5
7
print(type(x))

A variable can have a short name or a more descriptive name.


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

Python allows you to assign values to multiple variables in one


line:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)
And you can assign the same value to multiple variables in one
line:
8
x = y = z = "Orange"
print(x)
print(y)
print(z)

If you have a collection of values in a list, tuple etc. Python


allows you to extract the values into variables. This is called
unpacking.

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)

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

9
x = "Python is awesome"
print(x)

In the print() function, you output multiple variables, separated


by a comma:

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

Python data types

Variables can store data of different types, and different types


can do different things.
Python has the following data types built-in by default, in these
categories:

10
 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
 None Type: NoneType

You can get the data type of any object by using the type()
function:

x=5
print(type(x))

In Python, the data type is set when you assign a value to a


variable:

 x = "Hello World" str


 x = 20 int
 x = 20.5 float

11
 x = 1j complex
 x = ["apple", "banana", "cherry"] list
 x = ("apple", "banana", "cherry") tuple
 x = range(6) range
 x = {"name" : "John", "age" : 36} dict
 x = {"apple", "banana", "cherry"} set
 x = frozenset({"apple", "banana", "cherry"}) frozenset
 x = True bool
 x = b"Hello" bytes
 x = bytearray(5) bytearray
 x = memoryview(bytes(5)) memoryview
 x = None NoneType

Python numbers
There are three numeric types in Python:
 int
 float
 complex
Variables of numeric types are created when you assign a value
to them:

12
x = 1 # int
y = 2.8 # float
z = 1j # complex

Int, or integer, is a whole number, positive or negative, without


decimals, of unlimited length.

x=1

Float, or "floating point number" is a number, positive or


negative, containing one or more decimals.

x = 1.18

Float can also be scientific numbers with an "e" to indicate the


power of 10.
x = 35e3

Complex numbers are written with a "j" as the imaginary part:

13
x = 3+5j

Python has a built-in module called random that can be used to


make random numbers:

import random
print(random.randrange(1, 10))

Python casting

There may be times when you want to specify a type on to a


variable. This can be done with casting. Python is an object-
orientated language, and as such it uses classes to define data
types, including its primitive types.
Casting in python is therefore done using constructor functions:

14
 int() - constructs an integer number from an integer literal,
a float literal (by removing all decimals), or a string literal
(providing the string represents a whole number)
 float() - constructs a float number from an integer literal, a
float literal or a string literal (providing the string
represents a float or an integer)
 str() - constructs a string from a wide variety of data types,
including strings, integer literals and float literals
Integers:

x = int(1) # x will be 1

Floats:

x = float(1) # x will be 1.0

Strings:
x = str("s1") # x will be 's1'

Python strings

15
Strings in python are surrounded by either single quotation
marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

print("Hello")

Assigning a string to a variable is done with the variable name


followed by an equal sign and the string:

a = "Hello"
print(a)

You can assign a multiline string to a variable by using three


quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,

16
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

However, Python does not have a character data type, a single


character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.

a = "Hello, World!"
print(a[1])

Since strings are arrays, we can loop through the characters in a


string, with a for loop.

for x in "banana":
print(x)

To get the length of a string, use the len() function.

17
a = "Hello, World!"
print(len(a))

You can return a range of characters by using the slice syntax.


Specify the start index and the end index, separated by a colon,
to return a part of the string.

b = "Hello, World!"
print(b[2:5])

By leaving out the start index, the range will start at the first
character:

b = "Hello, World!"
print(b[:5])

By leaving out the end index, the range will go to the end:
b = "Hello, World!"
print(b[2:])
18
Python modify text
Python has a set of built-in methods that you can use on
strings.
The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

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

a = "Hello, World!"

19
print(a.replace("H", "J"))

To concatenate, or combine, two strings you can use the +


operator.
Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)

To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)

20
The format() method takes the passed arguments, formats
them, and places them in the string where the placeholders {}
are:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

You can use index numbers {0} to be sure the arguments are
placed in the correct placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

To insert characters that are illegal in a string, use an escape


character.

21
An escape character is a backslash \ followed by the character
you want to insert.

txt = "We are the so-called \"Vikings\" from the north."

Python booleans

Booleans represent one of two values: True or False.

You can evaluate any expression in Python, and get one of two
answers, True or False.

When you run a condition in an if statement, Python returns


True or False:

a = 200
b = 33

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

The bool() function allows you to evaluate any value, and give
you True or False in return.
Evaluate a string and a number:

print(bool("Hello"))
print(bool(15))

Evaluate two variables:

x = "Hello"
print(bool(x))

Almost any value is evaluated to True if it has some sort of


content.
23
 Any string is True, except empty strings.
 Any number is True, except 0.
 Any list, tuple, set, and dictionary are True, except empty
ones.

You can create functions that returns a Boolean Value:

def myFunction() :
return True

print(myFunction())

You can execute code based on the Boolean answer of a


function:
Print "YES!" if the function returns True, otherwise print "NO!":

def myFunction() :
return True

24
if myFunction():
print("YES!")
else:
print("NO!")

Python also has many built-in functions that return a boolean


value, like the isinstance() function, which can be used to
determine if an object is of a certain data type:
Check if an object is an integer or not:

x = 200
print(isinstance(x, int))

Python operators

Operators are used to perform operations on variables and


values.

25
Arithmetic operators are used with numeric values to perform
common mathematical operations:
 + Addition x+y
 - Subtraction x-y
 * Multiplication x * y
 / Division x/y
 % Modulus x%y
 ** Exponentiation x ** y
 // Floor division x // y

Assignment operators are used to assign values to variables:


 = x=5 x=5
 += x += 3 x=x+3
 -= x -= 3 x=x-3
 *= x *= 3 x=x*3
 /= x /= 3 x=x/3
 %= x %= 3 x = x % 3
 //= x //= 3 x = x // 3
 **= x **= 3 x = x ** 3
 &= x &= 3 x = x & 3
 |= x |= 3 x=x|3
 ^= x ^= 3 x=x^3
 >>= x >>= 3 x = x >> 3

26
Comparison operators are used to compare two values:

 == 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 are used to combine conditional statements:

 Operator Description
 and Returns True if both statements are true
 or Returns True if one of the statements is true
 not Reverse the result, returns False if the result is
true

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

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


print(thislist)

List items are ordered, changeable, and allow duplicate values.


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

Lists allow duplicate values:

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


print(thislist)

List items can be of any data type:

28
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

From Python's perspective, lists are defined as objects with the


data type 'list':

There are four collection data types in the Python programming


language:

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

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


print(thislist[1])

When specifying a range, the return value will be a new list


with the specified items.

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

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


keyword:
Check if "apple" is present in the list:

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


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")

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


number.

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


thislist[1] = "blackcurrant"
print(thislist)

30
Change the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":

thislist = ["apple", "banana", "cherry", "orange", "kiwi",


"mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

To insert a new list item, without replacing any of the existing


values, we can use the insert() method.
The insert() method inserts an item at the specified index:

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


thislist.insert(2, "watermelon")
print(thislist)

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

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

The extend() method does not have to append lists, you can
add any iterable object (tuples, sets, dictionaries etc.).
Add elements of a tuple to a list:

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


thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

The remove() method removes the specified item.

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


thislist.remove("banana")
print(thislist)

32
The pop() method removes the specified index.
Remove the second item:

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


thislist.pop(1)
print(thislist)

The del keyword can delete the list completely.

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


del thislist

The clear() method empties the list.


The list still remains, but it has no content.

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


thislist.clear()
print(thislist)

33
You can loop through the list items by using a for loop:
Print all items in the list, one by one:

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


for x in thislist:
print(x)

Based on a list of fruits, you want a new list, containing only the
fruits with the letter "a" in the name.

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


newlist = [x for x in fruits if "a" in x]
print(newlist)

List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:
Sort the list alphabetically:
34
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)

Sort the list numerically:

thislist = [100, 50, 65, 82, 23]


thislist.sort()
print(thislist)

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


Sort the list descending:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort(reverse = True)
print(thislist)

35
There are ways to make a copy, one way is to use the built-in
List method copy().
Make a copy of a list with the copy() method:

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


mylist = thislist.copy()
print(mylist)

Python tuples

Tuples are used to store multiple items in a single variable.


A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

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


print(thistuple)

36
Tuple items are ordered (order not changeble), unchangeable,
and allow duplicate values.

It is also possible to use the tuple() constructor to make a tuple.


Using the tuple() method to make a tuple:

thistuple = tuple(("apple", "banana", "cherry"))


print(thistuple)

You can access tuple items by referring to the index number,


inside square brackets:

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


print(thistuple[1])

Tuples are unchangeable, meaning that you cannot change,


add, or remove items once the tuple is created.

37
But there are some workarounds.

You can convert the tuple into a list, change the list, and
convert the list back into a tuple.
Convert the tuple into a list to be able to change it:

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


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

The del keyword can delete the tuple completely:

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


del thistuple

Python sets

38
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable, and
unindexed.

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


print(thisset)

Sets are unordered, so you cannot be sure in which order the


items will appear.
Set items are unchangeable, but you can remove items and add
new items.
Sets cannot have two items with the same value.

You cannot access items in a set by referring to an index or a


key.

Once a set is created, you cannot change its items, but you can
add new items.
39
To add one item to a set use the add() method.

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


thisset.add("orange")
print(thisset)

To add items from another set into the current set, use the
update() method.
Add elements from tropical into thisset:

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


tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)

To remove an item in a set, use the remove(), or the discard()


method.

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

You can also use the pop() method to remove an item, but this
method will remove a random item, so you cannot be sure
what item that gets removed.

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


x = thisset.pop()
print(x)

The clear() method empties the set:

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


thisset.clear()
print(thisset)

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


41
You can use the union() method that returns a new set
containing all items from both sets, or the update() method
that inserts all the items from one set into another:
The union() method returns a new set with all items from both
sets:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

The intersection_update() method will keep only the items that


are present in both sets.
Keep the items that exist in both set x, and set y:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
x.intersection_update(y)

42
print(x)

The intersection() method will return a new set, that only


contains the items that are present in both sets.
Return a set that contains the items that exist in both set x, and
set y:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)

The symmetric_difference_update() method will keep only the


elements that are NOT present in both sets.
Keep the items that are not present in both sets:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)

43
print(x)

The symmetric_difference() method will return a new set, that


contains only the elements that are NOT present in both sets.

Return a set that contains all items from both sets, except items
that are present in both:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)

Python dictionaries

Dictionaries are used to store data values in key:value pairs.


44
A dictionary is a collection which is ordered, changeable and do
not allow duplicates.
Dictionaries are written with curly brackets, and have keys and
values:

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

Dictionary items are presented in key:value pairs, and can be


referred to by using the key name.
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

45
}
print(thisdict["brand"])

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


function:

print(len(thisdict))

You can access the items of a dictionary by referring to its key


name, inside square brackets:

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

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

x = thisdict.keys()

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

x = thisdict.values()

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


key name:
Change the "year" to 2018:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964

47
}
thisdict["year"] = 2018

The update() method will update the dictionary with the items
from the given argument.
The argument must be a dictionary, or an iterable object with
key:value pairs.
Update the "year" of the car by using the update() method:

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

Adding an item to the dictionary is done by using a new index


key and assigning a value to it:

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

The del keyword removes the item with the specified key
name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
49
The del keyword can also delete the dictionary completely:

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

The clear() method empties the dictionary:

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

50
print(thisdict)

Python if… else

Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly


in "if statements" and loops.
An "if statement" is written by using the if keyword.

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

The elif keyword is Python's way of saying "if the previous


conditions were not true, then try this condition".

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

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


preceding conditions.

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

The and keyword is a logical operator, and is used to combine


conditional statements:
Test if a is greater than b, AND if c is greater than a:

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

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


conditional statements:
Test if a is greater than b, OR if a is greater than c:
53
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Python while loops

With the while loop we can execute a set of statements as long


as a condition is true.
Print i as long as i is less than 6:

i=1
while i < 6:
print(i)
i += 1

54
With the break statement we can stop the loop even if the
while condition is true:
Exit the loop when i is 3:

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

With the continue statement we can stop the current iteration,


and continue with the next:
Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1
55
if i == 3:
continue
print(i)

With the else statement we can run a block of code once when
the condition no longer is true:
Print a message once the condition is false:

i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Python for loops

56
A for loop is used for iterating over a sequence (that is either a
list, a tuple, a dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc.

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

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

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

57
With the continue statement we can stop the current iteration
of the loop, and continue with the next:
Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

To loop through a set of code a specified number of times, we


can use the range() function,
The range() function returns a sequence of numbers, starting
from 0 by default, and increments by 1 (by default), and ends at
a specified number.
Using the range() function:

for x in range(6):
print(x)

58
The else keyword in a for loop specifies a block of code to be
executed when the loop is finished:
Print all numbers from 0 to 5, and print a message when the
loop has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")

Python functions

 A function is a block of code which only runs when it is


called.
 You can pass data, known as parameters, into a function.
 A function can return data as a result.

In Python a function is defined using the def keyword:

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

To call a function, use the function name followed by


parenthesis:

my_function()

Information can be passed into functions as arguments.


Arguments are specified after the function name, inside the
parentheses.
The following example has a function with one argument
(fname). When the function is called, we pass along a first
name, which is used inside the function to print the full name:

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

my_function("Emil")

60
If the number of arguments is unknown, add a * before the
parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

The following example shows how to use a default parameter


value.
If we call the function without argument, it uses the default
value:

def my_function(country = "Norway"):


print("I am from " + country)

my_function("Sweden")

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

def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]


my_function(fruits)

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

def my_function(x):
return 5 * x

62
print(my_function(3))

function definitions cannot be empty, but if you for some


reason have a function definition with no content, put in the
pass statement to avoid getting an error.

def myfunction():
pass

Python also accepts function recursion, which means a defined


function can call itself.
Recursion is a common mathematical and programming
concept. It means that a function calls itself. This has the
benefit of meaning that you can loop through data to reach a
result.
The developer should be very careful with recursion as it can
be quite easy to slip into writing a function which never
terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion
can be a very efficient and mathematically-elegant approach
to programming.

63
In this example, tri_recursion() is a function that we have
defined to call itself ("recurse"). We use the k variable as the
data, which decrements (-1) every time we recurse. The
recursion ends when the condition is not greater than 0 (i.e.
when it is 0).
To a new developer it can take some time to work out how
exactly this works, best way to find out is by testing and
modifying it.

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

print("\n\nRecursion Example Results")


tri_recursion(6)

64
Python lambda

A lambda function is a small anonymous function.


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

lambda arguments : expression

The expression is executed and the result is returned:

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

Lambda functions can take any number of arguments:


Multiply argument a with argument b and return the result:

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

65
The power of lambda is better shown when you use them as an
anonymous function inside another function.
Say you have a function definition that takes one argument,
and that argument will be multiplied with an unknown number:
Use that function definition to make a function that always
doubles the number you send in:

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

mydoubler = myfunc(2)
print(mydoubler(11))

Python Classes and Objects

 Python is an object oriented programming language.


 Almost everything in Python is an object, with its
properties and methods.

66
 A Class is like an object constructor, or a "blueprint" for
creating objects.

To create a class, use the keyword class:


Create a class named MyClass, with a property named x:

class MyClass:
x=5

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


Create an object named p1, and print the value of x:

p1 = MyClass()
print(p1.x)
The __init__() Function
The examples above are classes and objects in their simplest
form, and are not really useful in real life applications.
To understand the meaning of classes we have to understand
the built-in __init__() function.

67
 All classes have a function called __init__(), which is
always executed when the class is being initiated.
 Use the __init__() function to assign values to object
properties, or other operations that are necessary to do
when the object is being created.
Create a class named Person, use the __init__() function to
assign values for name and age:

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

p1 = Person("John", 36)
print(p1.name)
print(p1.age)

The __str__() function controls what should be returned when


the class object is represented as a string.

68
If the __str__() function is not set, the string representation of
the object is returned:
The string representation of an object WITH the __str__()
function:

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

def __str__(self):
return f"{self.name}({self.age})"

p1 = Person("John", 36)
print(p1)

69
Python inheritance

 Inheritance allows us to define a class that inherits all the


methods and properties from another class.
 Parent class is the class being inherited from, also called
base class.
 Child class is the class that inherits from another class, also
called derived class.

Any class can be a parent class, so the syntax is the same as


creating any other class:

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

def printname(self):
print(self.firstname, self.lastname)
70
x = Person("John", "Doe")
x.printname()

Create a class named Student, which will inherit the properties


and methods from the Person class:

class Student(Person):
pass

 Use the pass keyword when you do not want to add any
other properties or methods to the class.
 We want to add the __init__() function to the child class
(instead of the pass keyword).
 The __init__() function is called automatically every time
the class is being used to create a new object.
Add the __init__() function to the Student class:

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

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

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

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

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

Python iterators

 An iterator is an object that contains a countable number


of values.

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

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

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


myit = iter(mytuple)

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

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

73
Iterate the values of a tuple:

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

for x in mytuple:
print(x)

 To create an object/class as an iterator you have to


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

To prevent the iteration to go on forever, we can use the


StopIteration statement.
74
In the __next__() method, we can add a terminating condition
to raise an error if the iteration is done a specified number of
times:
Stop after 20 iterations:

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

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

myclass = MyNumbers()
75
myiter = iter(myclass)

for x in myiter:
print(x)

Python scope

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


This is called scope.
A variable created inside a function is available inside that
function:

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

myfunc()

76
The local variable can be accessed from a function within the
function:

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

myfunc()

A variable created in the main body of the Python code is a


global variable and belongs to the global scope.

x = 300

def myfunc():
print(x)
77
myfunc()
print(x)

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

def myfunc():
global x
x = 300

myfunc()
print(x)

78
Python modules

Consider a module to be the same as a code library.


A file containing a set of functions you want to include in your
application.

To create a module just save the code you want in a file with
the file extension .py:
Import the module named mymodule, and call the greeting
function:

import mymodule
mymodule.greeting("Jonathan")

When using a function from a module, use the syntax:


module_name.function_name.

The module can contain functions, as already described, but


also variables of all types (arrays, dictionaries, objects etc):

79
There are several built-in modules in Python, which you can
import whenever you like.
Import and use the platform module:

import platform

x = platform.system()
print(x)

There is a built-in function to list all the function names (or


variable names) in a module. The dir() function:
List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

80
You can choose to import only parts from a module, by using
the from keyword.
Import only the person1 dictionary from the module:

from mymodule import person1


print (person1["age"])

Python dates

A date in Python is not a data type of its own, but we can


import a module named datetime to work with dates as date
objects.
Import the datetime module and display the current date:

import datetime
x = datetime.datetime.now()
print(x)

81
Return the year and name of weekday:

import datetime
x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))

To create a date, we can use the datetime() class (constructor)


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

import datetime
x = datetime.datetime(2020, 5, 17)
print(x)

The datetime object has a method for formatting date objects


into readable strings.

82
The method is called strftime(), and takes one parameter,
format, to specify the format of the returned string:
Display the name of the month:

import datetime
x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))

Python math

Python has a set of built-in math functions, including an


extensive math module, that allows you to perform
mathematical tasks on numbers.
The min() and max() functions can be used to find the lowest or
highest value in an iterable:

x = min(5, 10, 25)

83
y = max(5, 10, 25)

print(x)
print(y)

The abs() function returns the absolute (positive) value of the


specified number:

x = abs(-7.25)
print(x)

The pow(x, y) function returns the value of x to the power of y


(xy).

x = pow(4, 3)
print(x)

Python has also a built-in module called math, which extends


the list of mathematical functions.

84
To use it, you must import the math module:

import math

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

import math

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

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

import math
x = math.pi
print(x)
85
Python RegEx

A RegEx, or Regular Expression, is a sequence of characters that


forms a search pattern.
RegEx can be used to check if a string contains the specified
search pattern.

import re

When you have imported the re module, you can start using
regular expressions.
Search the string to see if it starts with "The" and ends with
"Spain":

import re

txt = "The rain in Spain"


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

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

Function Description
 findall Returns a list containing all matches
 search Returns a Match object if there is a match
anywhere in the string
 split Returns a list where the string has been split at
each match
 sub Replaces one or many matches with a string
Character Description
 [] A set of characters
 \ Signals a special sequence (can also be used to escape
special characters)
 . Any character (except newline character)
 ^ Starts with
 $ Ends with
 Zero or more occurrences
 + One or more occurrences
 ? Zero or one occurrences
 {} Exactly the specified number of occurrences
 | Either or
 () Capture and group
87
The findall() function returns a list containing all matches.
Print a list of all matches:

import re

txt = "The rain in Spain"


x = re.findall("ai", txt)
print(x)

The search() function searches the string for a match, and


returns a Match object if there is a match.
Search for the first white-space character in the string:

import re

txt = "The rain in Spain"


x = re.search("\s", txt)
print("The first white-space character is located in position:",
x.start())
88
The split() function returns a list where the string has been split
at each match:
Split at each white-space character:

import re

txt = "The rain in Spain"


x = re.split("\s", txt)
print(x)

The sub() function replaces the matches with the text of your
choice:
Replace every white-space character with the number 9:

import re

txt = "The rain in Spain"


x = re.sub("\s", "9", txt)
print(x)
89
You can control the number of replacements by specifying the
count parameter:
Replace the first 2 occurrences:

import re

txt = "The rain in Spain"


x = re.sub("\s", "9", txt, 2)
print(x)

Python try… except

 The try block lets you test a block of code for errors.
 The except block lets you handle the error.
 The else block lets you execute code when there is no
error.
 The finally block lets you execute code, regardless of the
result of the try- and except blocks.

90
When an error occurs, or exception as we call it, Python will
normally stop and generate an error message.
These exceptions can be handled using the try statement:

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

You can define as many exception blocks as you want, e.g. if


you want to execute a special block of code for a special kind of
error:

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

91
You can use the else keyword to define a block of code to be
executed if no errors were raised:
In this example, the try block does not generate any error:

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

The finally block, if specified, will be executed regardless if the


try block raises an error or not.

finally:
print("The 'try except' is finished")

92
As a Python developer you can choose to throw an exception if
a condition occurs.
To throw (or raise) an exception, use the raise keyword.
Raise an error and stop the program if x is lower than 0:

x = -1

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

Python user input

Python allows for user input.


That means we are able to ask the user for input.
The following example asks for the username, and when you
entered the username, it gets printed on the screen:

username = input("Enter username:")


93
Python string formatting

To make sure a string will display as expected, we can format


the result with the format() method.

The format() method allows you to format selected parts of a


string.
Sometimes there are parts of a text that you do not control,
maybe they come from a database, or user input?
To control such values, add placeholders (curly brackets {}) in
the text, and run the values through the format() method:
Add a placeholder where you want to display the price:

price = 49
txt = "The price is {} dollars"
print(txt.format(price))

You can add parameters inside the curly brackets to specify


how to convert the value:

94
Format the price to be displayed as a number with two
decimals:

txt = "The price is {:.2f} dollars"

If you want to use more values, just add more values to the
format() method:

print(txt.format(price, itemno, count))

And add more placeholders:

quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))

95
You can use index numbers (a number inside the curly brackets
{0}) to be sure the values are placed in the correct placeholders:

quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f}
dollars."
print(myorder.format(quantity, itemno, price))

Python file handling

File handling is an important part of any web application.


Python has several functions for creating, reading, updating,
and deleting files.

The key function for working with files in Python is the open()
function.

96
The open() function takes two parameters; filename, and
mode.
There are four different methods (modes) for opening a file:

 "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
In addition you can specify if the file should be handled as
binary or text mode

 "t" - Text - Default value. Text mode


 "b" - Binary - Binary mode (e.g. images)

To open a file for reading it is enough to specify the name of


the file:

97
f = open("demofile.txt")

The code above is the same as:

f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you
do not need to specify them.

To open the file, use the built-in open() function.


The open() function returns a file object, which has a read()
method for reading the content of the file:

f = open("demofile.txt", "r")
print(f.read())

If the file is located in a different location, you will have to


specify the file path, like this:
Open a file on a different location:

98
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

By default the read() method returns the whole text, but you
can also specify how many characters you want to return:
Return the 5 first characters of the file:

f = open("demofile.txt", "r")
print(f.read(5))
You can return one line by using the readline() method:
Read one line of the file:

f = open("demofile.txt", "r")
print(f.readline())

It is a good practice to always close the file when you are done
with it.
Close the file when you are finish with it:
99
f = open("demofile.txt", "r")
print(f.readline())
f.close()

To write to an existing file, you must add a parameter to the


open() function:

 "a" - Append - will append to the end of the file


 "w" - Write - will overwrite any existing content
Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:

f = open("demofile2.txt", "r")
100
print(f.read())

Open the file "demofile3.txt" and overwrite the content:

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the overwriting:


f = open("demofile3.txt", "r")
print(f.read())
Note: the "w" method will overwrite the entire file.

To create a new file in Python, use the open() method, with one
of the following parameters:

 "x" - Create - will create a file, returns an error if the file


exist
101
 "a" - Append - will create a file if the specified file does not
exist
 "w" - Write - will create a file if the specified file does not
exist

Create a file called "myfile.txt":

f = open("myfile.txt", "x")

Result: a new empty file is created!


Create a new file if it does not exist:

f = open("myfile.txt", "w")

To delete a file, you must import the OS module, and run its
os.remove() function:
Remove the file "demofile.txt":

import os

102
os.remove("demofile.txt")

To avoid getting an error, you might want to check if the file


exists before you try to delete it:
Check if file exists, then delete it:

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

To delete an entire folder, use the os.rmdir() method:

Remove the folder "myfolder":

import os
os.rmdir("myfolder")
103

You might also like