Python
Python
What is Python?
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be
very quick.
• Python can be treated in a procedural way, an object-oriented way or a
functional way.
Good to know
• The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated
with anything other than security updates, is still quite popular.
• In this tutorial Python will be written in a text editor. It is possible to
write Python in an Integrated Development Environment, such as
Thonny, Pycharm, Netbeans or Eclipse which are particularly useful
when managing larger collections of Python files.
1
Python Syntax compared to other programming
languages
• Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope, such as
the scope of loops, functions, and classes. Other programming
languages often use curly brackets for this purpose.
•
To check if you have python installed on a Linux or Mac, then on linux open
the command line or on Mac open the Terminal and type:
python --version
If you find that you do not have Python installed on your computer, then you
can download it for free from the following website: [Link]
Python Quickstart
Python is an interpreted programming language, this means that as a
developer you write Python (.py) files in a text editor and then put those files
into the python interpreter to be executed.
The way to run a python file is like this on the command line:
Where "[Link]" is the name of your python file. Let's write our first
Python file, called [Link], which can be done in any text editor.
[Link]
print("Hello, World!")
Hello, World!
Simple as that. Save your file. Open your command line, navigate to the
directory where you saved your file, and run:
2
C:\Users\Your Name>python [Link]
Hello, World!
Congratulations, you have written and executed your first Python program.
C:\Users\Your Name>python
Or, if the "python" command did not work, you can try "py":
C:\Users\Your Name>py
From there you can write any python, including our hello world example from
earlier in the tutorial:
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!
Whenever you are done in the python command line, you can simply type
the following to quit the python command line interface:
exit()
3
Python Tuples
mytuple = ("apple", "banana", "cherry")
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Set, and Dictionary, all with different qualities and
usage.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values. Tuple
items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.
4
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
<class 'tuple'>
<class 'str'>
5
Tuple Items - Data Types
Tuple items can be of any data type:
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
type()
From Python's perspective, tuples are defined as objects with the data type
'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
<class 'tuple'>
6
('apple', 'banana', 'cherry')
banana
Note: The first item has index 0.
Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
cherry
7
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
When specifying a range, the return value will be a new tuple with the
specified items.
Example
Return the third, fourth, and fifth item:
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not
included). Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT included,
"kiwi":
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])
8
Example
This example returns the items from index -4 (included) to index -1
(excluded)
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Example
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)
9
Add Items
Since tuples are immutable, they do not have a build-in append() method,
but there are other ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you
can convert it into a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("orange")
thistuple = tuple(y)
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you
want to add one item, (or many), create a new tuple with the item(s), and
add it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Note: When creating a tuple with only one item, remember to include a
comma after the item, otherwise it will not be identified as a tuple.
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can
use the same workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a
tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
[Link]("apple")
thistuple = tuple(y)
10
('banana', 'cherry')
Or you can delete the tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no
longer exists
Traceback (most recent call last):
File "demo_tuple_del.py", line 3, in <module>
print(thistuple) #this will raise an error because the tuple
no longer exists
NameError: name 'thistuple' is not defined
Example
Packing a tuple:
fruits = ("apple", "banana", "cherry")
But, in Python, we are also allowed to extract the values back into variables.
This is called "unpacking":
Example
Unpacking a tuple:
apple
banana
cherry
11
Note: The number of variables must match the number of values in the
tuple, if not, you must use an asterisk to collect the remaining values as a
list.
Using Asterisk*
If the number of variables is less than the number of values, you can add
an * to the variable name and the values will be assigned to the variable as a
list:
Example
Assign the rest of the values as a list called "red":
If the asterisk is added to another variable name than the last, Python will
assign values to the variable until the number of values left matches the
number of variables left.
Example
Add a list of values the "tropic" variable:
fruits = ("apple", "mango", "papaya", "pineapple", "cherry")
(green, *tropic, red) = fruits
print(green)
print(tropic)
print(red)
apple
['mango', 'papaya', 'pineapple']
cherry
apple
banana
cherry
Example
Print all items by referring to their index number:
thistuple = ("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
apple
banana
cherry
Example
Print all items, using a while loop to go through all the index numbers:
thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple):
print(thistuple[i])
i = i + 1
apple
banana
cherry
13
Python - Join Tuples
Join Two Tuples
To join two or more tuples you can use the + operator:
Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you
can use the * operator:
Example
Multiply the fruits tuple by 2:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
Method Description
index() Searches the tuple for a specified value and returns the position
of where it was found
14
Python Tuple count() Method
Example
Return the number of times the value 5 appears in the tuple:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](5)
print(x)
2
Syntax
[Link](value)
Parameter Values
Parameter Description
Search for the first occurrence of the value 8, and return its position:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](8)
print(x)
3
15
Definition and Usage
The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.
Syntax
[Link](value)
Parameter Values
Parameter Description
Exercise:
Print the first item in the fruits tuple.
Exercise:
Use the correct syntax to print the number of items in the fruits tuple.
Exercise:
Use negative indexing to print the last item in the tuple.
16
fruits = ("apple", "banana", "cherry")
print( )
Exercise:
Use a range of indexes to print the third, fourth, and fifth item in the tuple.
Python Sets
myset = {"apple", "banana", "cherry"}
Set
Sets are used to store multiple items in a single variable. Set is one of 4 built-
in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage. A set is a
collection which is unordered, unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new
items.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Note: Sets are unordered, so you cannot be sure in which order the items
will appear.
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
17
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and
cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after
the set has been created.
Once a set is created, you cannot change its items, but you can remove
items and add new items.
Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Example
String, int and boolean data types:
18
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
print(set1)
print(set2)
print(set3)
Example
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
print(set1)
{True, 34, 40, 'male', 'abc'}
type()
From Python's perspective, sets are defined as objects with the data type
'set':
<class 'set'>
Example
What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))
<class 'set'>
19
Python Collections (Arrays)
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, unchangeable*, and unindexed.
No duplicate members.
• Dictionary is a collection which is ordered** and changeable. No
duplicate members.
*Set items are unchangeable, but you can remove items and add new items.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
apple
cherry
banana
Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
True
20
Change Items
Once a set is created, you cannot change its items, but you can add new
items.
Example
Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)
Add Sets
To add items from another set into the current set, use
the update() method.
Example
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
[Link](tropical)
print(thisset)
Example
21
Add elements of a list to at set:
thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
[Link](mylist)
print(thisset)
{'cherry', 'apple'}
Note: If the item to remove does not exist, remove() will raise an error.
Example
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
{'apple', 'cherry'}
Note: If the item to remove does not exist, discard() will NOT raise an
error.
You can also use the pop() method to remove an item, but this method will
remove the last item. Remember that sets are unordered, so you will not
know what item that gets removed. The return value of the pop() method is
the removed item.
Example
Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = [Link]()
22
print(x)
print(thisset)
apple
{'cherry', 'banana'}
Note: Sets are unordered, so when using the pop() method, you do not know
which item that gets removed.
Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)
set()
Example
The del keyword will delete the set completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
Example
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
cherry
banana
apple
23
Python - Join Sets
Join Two Sets
There are several ways to join two or more sets in Python. 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:
Example
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)
Example
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
[Link](set2)
print(set1)
Note: Both union() and update() will exclude any duplicate items.
{'apple'}
24
The intersection() method will return a new set, that only contains the
items that are present in both sets.
Example
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 = [Link](y)
print(z)
{'apple'}
Example
Keep the items that are not present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)
25
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference
between two or more sets
difference_update() Removes the items in this set that are
also included in another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of
two other sets
intersection_update() Removes the items in this set that are
not present in other, specified set(s)
isdisjoint() Returns whether two sets have a
intersection or not
issubset() Returns whether another set contains
this set or not
issuperset() Returns whether this set contains
another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric
differences of two sets
symmetric_difference_update() inserts the symmetric differences from
this set and another
union() Return a set containing the union of
sets
update() Update the set with the union of this
set and others
26
fruits = {"apple", "banana", "cherry"}
[Link]("orange")
print(fruits)
Syntax
[Link](elmnt)
Parameter Values
Parameter Description
More Examples
Example
Try to add an element that already exists:
fruits = {"apple", "banana", "cherry"}
[Link]("apple")
print(fruits)
27
Syntax
[Link]()
Parameter Values
No parameters
Syntax
[Link]()
Parameter Values
No parameters
{'cherry', 'banana'}
28
Meaning: The returned set contains items that exist only in the first set, and
not in both sets.
Syntax
[Link](set)
Parameter Values
Parameter Description
More Examples
Example
Reverse the first example. Return a set that contains the items that only
exist in set y, and not in set x:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](x)
print(z)
{'microsoft', 'google'}
29
Syntax
set.difference_update(set)
Parameter Values
Parameter Description
{'apple', 'cherry'}
Syntax
[Link](value)
Parameter Values
Parameter Description
30
Example
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 = [Link](y)
print(z)
{'apple'}
Syntax
[Link](set1, set2 ... etc)
Parameter Values
Parameter Description
set2 Optional. The other set to search for equal items in.
You can compare as many sets you like.
Separate the sets with a comma
More Examples
Example
Compare 3 sets, and return a set with items that is present in all 3 sets:
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
result = [Link](y, z)
print(result)
{'c'}
31
Example
Remove the items that is not present in both x and y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)
{'apple'}
Syntax
set.intersection_update(set1, set2 ... etc)
Parameter Values
Parameter Description
set2 Optional. The other set to search for equal items in.
You can compare as many sets you like.
Separate the sets with a comma
More Examples
Example
Compare 3 sets, and return a set with items that is present in all 3 sets:
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
x.intersection_update(y, z)
print(x)
{'c'}
32
Python Set isdisjoint() Method
Example
Return True if no items in set x is present in set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = [Link](y)
print(z)
True
Syntax
[Link](set)
Parameter Values
Parameter Description
More Examples
Example
What if no items are present in both sets? Return False if one ore more items
are present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = [Link](y)
print(z)
False
33
z = [Link](y)
print(z)
True
Syntax
[Link](set)
Parameter Values
Parameter Description
More Examples
Example
What if not all items are present in the specified set? Return False if not all
items in set x is present in set y:
False
True
34
Definition and Usage
The issuperset() method returns True if all items in the specified set exists
in the original set, otherwise it retuns False.
Syntax
[Link](set)
Parameter Values
Parameter Description
More Examples
Example
What if not all items are present in the specified set?
Return False if not all items in set y are present in set x:
x = {"f", "e", "d", "c", "b"}
y = {"a", "b", "c"}
z = [Link](y)
print(z)
False
{'apple', 'cherry'}
Syntax
[Link]()
35
Parameter Values
No parameter values.
More Examples
Example
Return the removed element:
fruits = {"apple", "banana", "cherry"}
x = [Link]()
print(x)
apple
{'cherry', 'apple'}
Syntax
[Link](item)
Parameter Values
Parameter Description
36
Python Set symmetric_difference() Method
Example
Return a set that contains all items from both sets, except items that are
present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
Syntax
set.symmetric_difference(set)
Parameter Values
Parameter Description
37
Syntax
set.symmetric_difference_update(set)
Parameter Values
Parameter Description
Syntax
[Link](set1, set2...)
Parameter Values
Parameter Description
More Examples
Example
Unify more than 2 sets:
38
x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"}
result = [Link](y, z)
print(result)
Syntax
[Link](set)
Parameter Values
Parameter Description
Exercise:
Check if "apple" is present in the fruits set.
39
fruits = {"apple", "banana", "cherry"}
if "apple" fruits:
print("Yes, apple is a fruit!")
Exercise:
Use the add method to add "orange" to the fruits set.
fruits = {"apple", "banana", "cherry"}
Exercise:
Use the correct method to add multiple items (more_fruits) to
the fruits set.
fruits = {"apple", "banana", "cherry"}
more_fruits = ["orange", "mango", "grapes"]
Exercise:
Use the remove method to remove "banana" from the fruits set.
fruits = {"apple", "banana", "cherry"}
Exercise:
Use the discard method to remove "banana" from the fruits set.
fruits = {"apple", "banana", "cherry"}
Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionary
Dictionaries are used to store data values in key:value pairs. A dictionary is a
collection which is ordered*, changeable and do not allow duplicates.
40
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by
using the key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ford
Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
When we say that dictionaries are ordered, it means that the items have a
defined order, and that order will not change.
Unordered means that the items does not have a defined order, you cannot
refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove
items after the dictionary has been created.
41
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
Print the number of items in the dictionary:
print(len(thisdict))
3
type()
From Python's perspective, dictionaries are defined as objects with the data
type 'dict':
<class 'dict'>
42
Example
Print the data type of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
<class 'dict'>
*Set items are unchangeable, but you can remove and/or add items whenever
you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
Example
Get the value of the "model" key:
thisdict = {
"brand": "Ford",
43
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
Mustang
There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key:
x = [Link]("model")
print(x)
Mustang
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
Get a list of the keys:
x = [Link]()
print(x)
dict_keys(['brand', 'model', 'year'])
The list of the keys is a view of the dictionary, meaning that any changes
done to the dictionary will be reflected in the keys list.
Example
Add a new item to the original dictionary, and see that the keys list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])
44
Get Values
The values() method will return a list of all the values in the dictionary.
Example
Get a list of the values:
x = [Link]()
print(x)
dict_values(['Ford', 'Mustang', 1964])
The list of the values is a view of the dictionary, meaning that any changes
done to the dictionary will be reflected in the values list.
Example
Make a change in the original dictionary, and see that the values list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 2020])
Example
Add a new item to the original dictionary, and see that the values list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
dict_values(['Ford', 'Mustang', 1964])
dict_values(['Ford', 'Mustang', 1964, 'red'])
45
Get Items
The items() method will return each item in a dictionary, as tuples in a list.
Example
Get a list of the key:value pairs
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
The returned list is a view of the items of the dictionary, meaning that any
changes done to the dictionary will be reflected in the items list.
Example
Make a change in the original dictionary, and see that the items list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
2020)])
Example
Add a new item to the original dictionary, and see that the items list gets
updated as well:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
46
print(x) #before the change
car["color"] = "red"
print(x) #after the change
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964), ('color', 'red')])
Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict
dictionary")
Yes, 'model' is one of the keys in the thisdict dictionary
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
47
Update Dictionary
The update() method will update the dictionary with the items from the
given argument.
The argument must be a dictionary, or an iterable object with key:value
pairs.
Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Update Dictionary
The update() method will update the dictionary with the items from a given
argument. If the item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value
pairs.
48
Example
Add a color item to the dictionary by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"color": "red"})
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color':
'red'}
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)
{'brand': 'Ford', 'year': 1964}
Example
The popitem() method removes the last inserted item (in versions before
3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
{'brand': 'Ford', 'model': 'Mustang'}
49
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
{'brand': 'Ford', 'year': 1964}
Example
The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no
longer exists.
Traceback (most recent call last):
File "demo_dictionary_del3.py", line 7, in <module>
print(thisdict) #this will cause an error because "thisdict"
no longer exists.
NameError: name 'thisdict' is not defined
Example
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
{}
50
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
brand
model
year
Example
Print all values in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
Ford
Mustang
1964
Example
You can also use the values() method to return values of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in [Link]():
print(x)
Ford
Mustang
1964
Example
You can use the keys() method to return the keys of a dictionary:
51
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in [Link]():
print(x)
brand
model
year
Example
Loop through both keys and values, by using the items() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in [Link]():
print(x, y)
brand Ford
model Mustang
year 1964
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = [Link]()
print(mydict)
52
Example
Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Example
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name':
'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year':
2011}}
53
Example
Create three dictionaries, then create one dictionary that will contain the
other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name':
'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year':
2011}}
Method Description
items() Returns a list containing a tuple for each key value pair
54
pop() Removes the element with the specified key
setdefault() Returns the value of the specified key. If the key does not
exist: insert the key, with the specified value
Syntax
[Link]()
Parameter Values
No parameters
55
x = [Link]()
print(x)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Syntax
[Link]()
Parameter Values
No parameters
Syntax
[Link](keys, value)
Parameter Values
Parameter Description
value Optional. The value for all keys. Default value is None
56
More Examples
Example
Same example as above, but without specifying the value:
x = ('key1', 'key2', 'key3')
thisdict = [Link](x)
print(thisdict)
['key1': None, 'key2': None, 'key3': None]
x = [Link]("model")
print(x)
Mustang
Syntax
[Link](keyname, value)
Parameter Values
Parameter Description
57
More Examples
Example
Try to return the value of an item that do not exist:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("price", 15000)
print(x)
15000
x = [Link]()
print(x)
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
Syntax
[Link]()
Parameter Values
No parameters
58
More Examples
Example
When an item in the dictionary changes value, the view object also gets
updated:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
car["year"] = 2018
print(x)
Syntax
[Link]()
59
Parameter Values
No parameters
More Examples
Example
When an item is added in the dictionary, the view object also gets updated:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
car["color"] = "white"
print(x)
Syntax
[Link](keyname, defaultvalue)
60
Parameter Values
Parameter Description
More Examples
Example
The value of the removed item is the return value of the pop() method:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("model")
print(x)
Mustang
61
The removed item is the return value of the popitem() method, as a tuple,
see example below.
Syntax
[Link]()
Parameter Values
No parameters
More Examples
Example
The removed item is the return value of the pop() method:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
('year', 1964)
x = [Link]("model", "Bronco")
print(x)
Mustang
62
Syntax
[Link](keyname, value)
Parameter Values
Parameter Description
value Optional.
If the key exist, this parameter has no effect.
If the key does not exist, this value becomes the key's
value
Default value None
More Examples
Example
Get the value of the "color" item, if the "color" item does not exist, insert
"color" with the value "white":
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("color", "white")
print(x)
White
63
[Link]({"color": "White"})
print(car)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color':
'White'}
Syntax
[Link](iterable)
Parameter Values
Parameter Description
64
Syntax
[Link]()
Parameter Values
No parameters
More Examples
Example
When a values is changed in the dictionary, the view object also gets
updated:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
car["year"] = 2018
print(x)
Try to insert the missing part to make the code work as expected:
Exercise:
Use the get method to print the value of the "model" key of
the car dictionary.
car = {
"brand": "Ford",
65
"model": "Mustang",
"year": 1964
}
print( )
Exercise:
Change the "year" value from 1964 to 2020.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
=
Exercise:
Use the pop method to remove "model" from the car dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Exercise:
Use the clear method to empty the car dictionary.
car = {
"brand": "Ford",
"model": "Mustang",
66
"year": 1964
}
In this example we use two variables, a and b, which are used as part of the
if statement to test whether b is greater than a. As a is 33, and b is 200, we
know that 200 is greater than 33, and so we print to screen that "b is greater
than a".
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code. Other programming languages often use curly-brackets for
this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
File "demo_if_error.py", line 4
print("b is greater than a")
67
^
IndentationError: expected an indented block
Elif
The elif keyword is pythons way of saying "if the previous conditions were
not true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
a and b are equal
Else
The else keyword catches anything which isn't caught by the preceding
conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
a is greater than b
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to
screen that "a is greater than b".
68
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
b is not greater than a
Short Hand If
If you have only one statement to execute, you can put it on the same line
as the if statement.
Example
One line if statement:
if a > b: print("a is greater than b")
"a is greater than b"
Example
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
B
This technique is known as Ternary Operators, or Conditional
Expressions.
You can also have multiple else statements on the same line:
Example
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
=
69
And
The and keyword is a logical operator, and is used to combine conditional
statements:
Example
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")
Both conditions are True
Or
The or keyword is a logical operator, and is used to combine conditional
statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
At least one of the conditions is True
Nested If
You can have if statements inside if statements, this is
called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Above ten,
and also above 20!
70
Example
a = 33
b = 200
if b > a:
pass
Exercise:
Print "Hello World" if a is greater than b.
a = 50
b = 10
a b
print("Hello World")
Exercise:
Print "Hello World" if a is not equal to b.
a = 50
b = 10
a b
print("Hello World")
Exercise:
Print "Yes" if a is equal to b, otherwise print "No".
a = 50
b = 10
a b
print("Yes")
print("No")
Exercise:
Print "1" if a is equal to b, print "2" if a is greater than b, otherwise print "3".
a = 50
b = 10
71
a b
print("1")
a b
print("2")
print("3")
Exercise:
Print "Hello" if a is equal to b, and c is equal to d.
if a == b c == d:
print("Hello")
Exercise:
Print "Hello" if a is equal to b, or if c is equal to d.
if a == b c == d:
print("Hello")
Exercise:
This example misses indentations to be correct.
Insert the missing indentation to make the code correct:
if 5 > 2:
print("Five is greater than two!")
Exercise:
Use the correct short hand syntax to put the following statement on one line:
if 5 > 2:
print("Five is greater than two!")
Exercise:
Use the correct short hand syntax to write the following conditional
expression in one line:
72
if 5 > 2:
print("Yes")
else
print("No")
73
break
i += 1
1
2
3
74
Exercise:
Print i as long as i is less than 6.
i = 1
i < 6
print(i)
i += 1
Exercise:
Stop the loop if i is 3.
i = 1
while i < 6:
if i == 3:
i += 1
Exercise:
In the loop, when i is 3, jump directly to the next iteration.
i = 0
while i < 6:
i += 1
if i == 3:
print(i)
Exercise:
Print a message once the condition is false.
i = 1
while i < 6:
print(i)
i += 1
75
Python For Loops
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string). This is less like the for keyword in other
programming languages, and works more like an iterator method as found in
other object-orientated programming languages. With the for loop we can
execute a set of statements, once for each item in a list, tuple, set etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
apple
banana
cherry
The for loop does not require an indexing variable to set beforehand.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
b
a
n
a
n
a
Example
Exit the loop when x is "banana":
76
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
apple
banana
Example
Exit the loop when x is "banana", but this time the break comes before the
print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
apple
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
apple
cherry
77
4
5
The range() function defaults to increment the sequence by 1, however it is
possible to specify the increment value by adding a third parameter: range(2,
30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
2
5
8
11
14
17
20
23
26
29
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
78
0
1
2
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer
loop":
Example
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
ed apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Exercise:
Loop through the items in the fruits list.
79
Exercise:
In the loop, when the item value is "banana", jump directly to the next item.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
print(x)
Exercise:
Use the range function to loop through a code set 6 times.
for x in :
print(x)
Exercise:
Exit the loop when x is "banana".
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
print(x)
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.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
80
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Emil Refsnes
Tobias Refsnes
Linus Refsnes
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
Number of Arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
81
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Emil Refsnes
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
Traceback (most recent call last):
File "demo_function_args_error.py", line 4, in <module>
my_function("Emil")
TypeError: my_function() missing 1 required positional argument:
'lname'
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
82
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
83
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
apple
banana
cherry
Return Values
To let a function, return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
15
25
45
Example
def myfunction():
pass
84
Recursion
Python also accepts function recursion, which means a defined function can
call itself.
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.
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.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
85
Exercise:
Create a function named my_function.
:
print("Hello from a function")
Exercise:
Execute a function named my_function.
def my_function():
print("Hello from a function")
Exercise:
Inside a function with two parameters, print the first parameter.
def my_function(fname, lname):
print( )
Exercise:
Let the function return the x parameter + 5.
def my_function(x):
Exercise:
If you do not know the number of arguments that will be passed into your
function, there is a prefix you can add in the function definition, which prefix?
def my_function( kids):
print("The youngest child is " + kids[2])
Exercise:
If you do not know the number of keyword arguments that will be passed
into your function, there is a prefix you can add in the function definition,
which prefix?
def my_function( kid):
print("His last name is " + kid["lname"])
86
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.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
Example
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
15
Lambda functions can take any number of arguments:
Example
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
30
Example
Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
13
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the
number you send in:
87
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
22
Or, use the same function definition to make a function that
always triples the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
33
Or, use the same function definition to make both functions, in the same
program:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
22
33
Exercise:
Create a lambda function that takes one parameter (a) and returns it.
x =
88
Python Arrays
Arrays
Note: This page shows you how to use LISTS as ARRAYS, however, to work
with arrays in Python you will have to import a library, like the NumPy
library.
Example
Create an array containing car names:
cars = ["Ford", "Volvo", "BMW"]
print(cars)
['Ford', 'Volvo', 'BMW']
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars
in single variables could look like this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
Note: Python does not have built-in support for Arrays, but Python Lists can
be used instead. Thus, for python array len property and other methods of
python array, one can always refer the python list method discussed in the
preceding topics.
89
Create a Class
To create a class, use the keyword class:
Example
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
print(mydoubler(11))
<class '__main__.MyClass'>
Create Object
Now we can use the class named MyClass to create objects:
Example
Create an object named p1, and print the value of x:
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
5
All classes have a function called __init__(), which is always executed when
the class is being initiated.
Example
Create a class named Person, use the __init__() function to assign values for
name and age:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
90
p1 = Person("John", 36)
print([Link])
print([Link])
John
36
Note: The __init__() function is called automatically every time the class is
being used to create a new object.
Example
The string representation of an object WITHOUT the __str__() function:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("John", 36)
print(p1)
Example
The string representation of an object WITH the __str__() function:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def __str__(self):
return f"{[Link]}({[Link]})"
p1 = Person("John", 36)
print(p1)
John(36)
91
Object Methods
Objects can also contain methods. Methods in objects are functions that
belong to the object. Let us create a method in the Person class:
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link]()
Note: The self parameter is a reference to the current instance of the class,
and is used to access variables that belong to the class.
92
Example
Set the age of p1 to 40:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link] = 40
print([Link])
40
Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
del p1
93
print(p1)
Traceback (most recent call last):
File "demo_class8.py", line 13, in <module>
print(p1)
NameError: 'p1' is not defined
Example
class Person:
pass
Exercise:
Create a class named MyClass:
MyClass:
x = 5
Exercise:
Create an object of MyClass called p1:
class MyClass:
x = 5
=
Exercise:
Use the p1 object to print the value of x:
class MyClass:
x = 5
p1 = MyClass()
print( )
94
Exercise:
What is the correct syntax to assign a "init" function to a class?
class Person:
def (self, name, age):
[Link] = name
[Link] = age
Python Inheritance
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.
Example
Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
#Use the Person class to create an object, and then execute the
printname method:
95
x = Person("John", "Doe")
[Link]()
John Doe
Example
Create a class named Student, which will inherit the properties and methods
from the Person class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other
properties or methods to the class.
Now the Student class has the same properties and methods as the Person
class.
Example
Use the Student class to create an object, and then execute
the printname method:
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
class Student(Person):
pass
x = Student("Mike", "Olsen")
[Link]()
Mike Olsen
96
Add the __init__() Function
So far we have created a child class that inherits the properties and methods
from its parent.
Note: The __init__() function is called automatically every time the class is
being used to create a new object.
Example
Add the __init__() function to the Student class:
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Example
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Mike", "Olsen")
[Link]()
Mike Olsen
Now we have successfully added the __init__() function, and kept the
inheritance of the parent class, and we are ready to add functionality in
the __init__() function.
97
Use the super() Function
Python also has a super() function that will make the child class inherit all
the methods and properties from its parent:
Example
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
x = Student("Mike", "Olsen")
[Link]()
Mike Olsen
By using the super() function, you do not have to use the name of the
parent element, it will automatically inherit the methods and properties from
its parent.
Add Properties
Example
Add a property called graduationyear to the Student class:
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
[Link] = 2019
x = Student("Mike", "Olsen")
print([Link])
98
2019
In the example below, the year 2019 should be a variable, and passed into
the Student class when creating student objects. To do so, add another
parameter in the __init__() function:
Example
Add a year parameter, and pass the correct year when creating objects:
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year
Add Methods
Example
Add a method called welcome to the Student class:
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year
def welcome(self):
print("Welcome", [Link], [Link], "to the class
of", [Link])
x = Student("Mike", "Olsen", 2019)
[Link]()
99
Welcome Mike Olsen to the class of 2019
If you add a method in the child class with the same name as a function in
the parent class, the inheritance of the parent method will be overridden.
Exercise:
What is the correct syntax to create a class named Student that will inherit
properties and methods from a class named Person?
class :
Exercise:
We have used the Student class to create an object named x.
What is the correct syntax to execute the printname method of the object x?
class Person:
def __init__(self, fname):
[Link] = fname
def printname(self):
print([Link])
class Student(Person):
pass
x = Student("Mike")
Python Iterators
Python Iterators
An iterator is an object that contains a countable number of values. An
iterator is an object that can be iterated upon, meaning that you can
traverse through all the values.
100
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from. All these objects have
a iter() method which is used to get an iterator:
Example
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))
apple
banana
cherry
Example
Strings are also iterable objects, containing a sequence of characters:
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
b
a
n
a
n
a
101
Example
Iterate the values of a tuple:
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
apple
banana
cherry
Example
Iterate the characters of a string:
mystr = "banana"
for x in mystr:
print(x)
b
a
n
a
n
a
The for loop actually creates an iterator object and executes the next()
method for each loop.
Create an Iterator
To create an object/class as an iterator you have to implement the
methods __iter__() and __next__() to your object.
As you have learned in the Python Classes/Objects chapter, all classes have a
function called __init__(), which allows you to do some initializing when the
object is being created.
The __iter__() method acts similar, you can do operations (initializing etc.),
but must always return the iterator object itself.
The __next__() method also allows you to do operations, and must return the
next item in the sequence.
102
Example
Create an iterator that returns numbers, starting with 1, and each sequence
will increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
1
2
3
4
5
StopIteration
The example above would continue forever if you had enough next()
statements, or if it was used in a for loop.
Example
Stop after 20 iterations:
class MyNumbers:
def __iter__(self):
self.a = 1
return self
103
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Python Scope
A variable is only available from inside the region it is created. This is
called scope.
Local Scope
A variable created inside a function belongs to the local scope of that
function, and can only be used inside that function.
104
Example
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
300
Example
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
300
Global Scope
A variable created in the main body of the Python code is a global variable
and belongs to the global scope. Global variables are available from within
any scope, global and local.
Example
A variable created outside of a function is global and can be used by anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
105
300
300
Naming Variables
If you operate with the same variable name inside and outside of a function,
Python will treat them as two separate variables, one available in the global
scope (outside the function) and one available in the local scope (inside the
function):
Example
The function will print the local x, and then the code will print the global x:
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
200
300
Global Keyword
If you need to create a global variable, but are stuck in the local scope, you
can use the global keyword. The global keyword makes the variable global.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = 300
myfunc()
print(x)
300
Also, use the global keyword if you want to make a change to a global
variable inside a function.
106
Example
To change the value of a global variable inside a function, refer to the
variable by using the global keyword:
x = 300
def myfunc():
global x
x = 200
myfunc()
print(x)
200
Python Modules
What is a Module?
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.
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
Example
Save this code in a file named [Link]
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
[Link]("Jonathan")
Hello, Jonathan
107
Variables in Module
The module can contain functions, as already described, but also variables of
all types (arrays, dictionaries, objects etc):
Example
Save this code in the file [Link]
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
36
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
36
Built-in Modules
There are several built-in modules in Python, which you can import whenever
you like.
108
Example
Import and use the platform module:
import platform
x = [Link]()
print(x)
Windows
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you
create yourself.
109
Import From Module
You can choose to import only parts from a module, by using
the from keyword.
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import only the person1 dictionary from the module:
Note: When importing using the from keyword, do not use the module name
when referring to elements in the module.
Example: person1["age"], not mymodule.person1["age"]
Exercise:
What is the correct syntax to import a module named "mymodule"?
mymodule
Exercise:
If you want to refer to a module by using a different name, you can create an
alias. What is the correct syntax for creating an alias for a module?
import mymodule mx
Exercise:
What is the correct syntax of printing all variables and function names of the
"mymodule" module?
110
import mymodule
print( )
Exercise:
What is the correct syntax of importing only the person1 dictionary of the
"mymodule" module?
mymodule person1
111