Python
Python
Python
Giacomo Fiumara
[Link]@[Link]
2025-2026
1 / 181
2 / 181
3 / 181
4 / 181
Anaconda
5 / 181
Jupyter (online)
6 / 181
Google Colab
7 / 181
Variables, Expressions and Instructions
Assignments /1
8 / 181
Variables, Expressions and Instructions
Assignments /2
9 / 181
Variables, Expressions and Instructions
Assignments /3
10 / 181
Variables, Expressions and Instructions
Expressions
11 / 181
Variables, Expressions and Instructions
n = 12.3
print(n)
12.3
n
12.3
12 / 181
Variables, Expressions and Instructions
Operation precedence
13 / 181
Variables, Expressions and Instructions
Operation precedence
For example:
360
2π
gradi = 360
pi = 3.14159
print(gradi / 2 * pi)
565.4861999999999
print(gradi / 2 / pi)
57.295827908797776
14 / 181
Variables, Expressions and Instructions
Comments
15 / 181
Variables, Expressions and Instructions
Comments
#comment
n = 4 # setting n to 4
n
4
’’’Multi line comment enclosed by triple (single)
quotes
’’’
’Multi line comment enclosed by triple quotes’
16 / 181
Functions
Function call
17 / 181
Functions
Function call
int(’32’)
32
int(12.445)
12
int(’c’)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ’c’
int(3.999)
3
18 / 181
Functions
Function call
float(32)
32.0
float(’123’)
123.0
str(32)
‘32’
float(’123.45’)
‘123.45’
19 / 181
Functions
Mathematical functions
20 / 181
Functions
Creating new functions
def printing():
print(’’First message’’)
print(’’Second message’’)
21 / 181
Functions
Creating new functions
def printing():
print(’’First message’’)
print(’’Second message’’)
22 / 181
Functions
Creating new functions
Note the difference between the two calls: in the second case
only some information about the object printing are
requested
23 / 181
Functions
Creating new functions
24 / 181
Functions
Execution flow
25 / 181
Functions
Parameters and arguments
printing2(’hello’, ’everybody’)
hello
everybody
26 / 181
Functions
Parameters and arguments
printing3(’hello’, ’ ciao’)
hello ciao
print(stringx)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ’stringx’ is not defined
27 / 181
Functions
Parameters and arguments
28 / 181
Functions
Fruitful functions and void functions
29 / 181
Functions
Fruitful functions and void functions
30 / 181
Functions
Fruitful functions and void functions
def printing():
print(’1st message’)
print(’2nd message’)
result = printing()
1st message
2nd message
print(result)
None
Note that variable result does not contain any value (as
expressed by None)
31 / 181
Conditionals and recursion
Modulus operator
32 / 181
Conditionals and recursion
Modulus operator
33 / 181
Conditionals and recursion
Modulus operator
34 / 181
Conditionals and recursion
Boolean expressions
>>> 5 == 5
True
>>> 5 == 6
False
>>> 5 = 5
File "<stdin>", line 1
SyntaxError: can’t assign to literal
>>> 5 == 6
False
>>>
35 / 181
Conditionals and recursion
Boolean expressions
True and False are special values of the type bool, they
are not strings
>>> type(True)
<class ’bool’>
>>> type(False)
<class ’bool’>
>>>
36 / 181
Conditionals and recursion
Boolean expressions
x != y x is not equal to y
x >y x is greater than y
x <y x is smaller than y
x >= y x is greater than or equal to y
x <= y x is smaller than or eqaul to y
37 / 181
Conditionals and recursion
Logical operators
38 / 181
Conditionals and recursion
Logical operators
39 / 181
Conditionals and recursion
Conditionals
40 / 181
Conditionals and recursion
Conditionals
41 / 181
Conditionals and recursion
Alternatives
42 / 181
Conditionals and recursion
Series of conditionals
44 / 181
Conditionals and recursion
Nested conditions
45 / 181
Conditionals and recursion
Recursion
46 / 181
Conditionals and recursion
Infinite recursion
47 / 181
Conditionals and recursion
Keyboard input
When this function is called, the program stops and waits for
the user to input something
48 / 181
Conditionals and recursion
Keyboard input
49 / 181
Conditionals and recursion
Recursion: factorial of a number
def factorial(n):
if n== 0:
return 1
else:
x = factorial(n-1)
result = n * x
return result
50 / 181
Fruitful functions
Recursion
def factorial(n):
spaces = ’ ’ * (4 * n)
print(spaces, ’factorial’, n)
if n == 0:
print(spaces, ’return 1’)
return 1
else:
ricors = factorial(n-1)
result = n * ricors
print(spaces, ’return ’, result)
return result
51 / 181
Fruitful functions
Return values
def area(radius):
a = [Link] * radius**2
return a
Or, equivalently:
def area(radius):
return [Link] * radius**2
52 / 181
Functions produttive
Return values
def asbolute_value(x):
if x < 0:
return -x
else:
return x
53 / 181
Fruitful functions
Boolean functions
Or equivalently:
54 / 181
Fruitful functions
Boolean functions: review 1
55 / 181
Fruitful functions
Boolean functions: review
def between(x,y,z):
return x <= y <= z
56 / 181
Fruitful functions
Checking types
57 / 181
Fruitful functions
Checking types
58 / 181
Fruitful functions
Checking types
def factorial(n):
if not isinstance(n, int):
print("Enter an integer number")
return None
elif n < 0:
print("Enter a positive integer number")
return None
elif n == 0:
return 1
else:
return n * factorial(n-1)
59 / 181
Fruitful functions
Review 2
60 / 181
Fruitful functions
Review 3
61 / 181
Loops
The while loop
62 / 181
Loops
The while loop
def countdown(n):
while n > 0:
print(n)
n -= 1
print("Via!!!")
63 / 181
Loops
The while loop
The body of the loop should change the value of one or more
variables so that the condition becomes false eventually and
the loop terminates
64 / 181
Loops
The while loop
def sequence(n):
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = n * 3 + 1
print(n)
65 / 181
Loops
The while loop: break
while True:
line = input("Enter a string: ")
if line == ’done’:
break
print(line)
print("Done!")
66 / 181
Loops
The while loop: review
˙ (−1)i
X
π=4
i 2i + 1
67 / 181
Loops
The while loop: review
˙ (−1)i
X
π=4
i 2i + 1
import math
def greekpi():
gpi, i = 0, 0
while abs(gpi - [Link]) > 0.0001:
gpi += 4 * [Link](-1,i)/(2 * i + 1)
print(i, gpi, abs(gpi - [Link]))
i += 1
68 / 181
Loops
The while loop: review
69 / 181
Loops
The while loop: review
70 / 181
Strings
71 / 181
Strings
Function len
72 / 181
Strings
for loop
73 / 181
Strings
for loop
74 / 181
Strings
Slicing
75 / 181
Strings
Slicing
– The operator [n:m] returns the part of the string from the
n-th character to the m-th character, including the first but
excluding the last
76 / 181
Strings
Slicing
– If the second index is omitted, the slice goes to the end of the
string
77 / 181
Strings
Slicing
78 / 181
Strings
Strings are immutable
79 / 181
Strings
Strings are immutable
80 / 181
Strings
Strings are immutable
81 / 181
Strings
Searching
82 / 181
Strings
Counting
83 / 181
Strings
Methods
84 / 181
Strings
Methods
85 / 181
Strings
Methods
>>> ’[Link]’.endswith(’exe’)
True
>>> [Link](’ry’)
9
>>> [Link](’yr’)
-1
>>> [Link](40)
’Hello everybody ’
>>> [Link](40)
’ Hello everybody’
>>> [Link](’y’,’Y’)
’Hello everYbodY’
86 / 181
Strings
The in operator
87 / 181
Strings
The in operator
t
u
t
t
i
>>>
88 / 181
Strings
The in operator
89 / 181
Strings
String comparison
>>> a=’ciao’
>>> b = ’CIAO’
>>> a == b
False
>>> a > b
True
>>> b = ’Ciao’
>>> a > b
True
90 / 181
Strings
Review
91 / 181
Lists
>>> la = [1,2,3,4,5]
>>> lb = [’hello’, ’everybody. ’, ’How’, ’are you
?’]
>>> lc = [1,2,3,’hello everybody. How are you?’,
20, 30.24, True]
>>> lc
[1, 2, 3, ’hello everybody. How are you?’, 20,
30.24, True]
92 / 181
Lists
93 / 181
Lists
Lists are mutable
– The syntax for accessing the elements of a list is the same for
accessing the characters of a string, the bracket operator
– Unlike strings, lists are mutable
94 / 181
Lists
Lists are mutable
95 / 181
Lists
Lists are mutable
>>> ’a’ in lb
False
>>> ’How’ in lb
True
96 / 181
Lists
Traversing a list
97 / 181
Lists
Traversing a list
>>> lb
[’hello’, ’everybody. ’, ’How’, ’are you?’]
>>> for i in range(len(lb)):
... print(i, "\t", lb[i])
...
0 hello
1 everybody.
2 How
3 are you?
98 / 181
Lists
Traversing a list
>>> [Link]([10,20,30])
>>> lb
[’hello’, ’everybody. ’, ’How’, ’are you?’, [10,
20, 30]]
>>> for i in range(len(lb)):
... print(i,"\t", lb[i])
...
0 hello
1 everybody.
2 How
3 are you?
4 [10, 20, 30]
99 / 181
Lists
The range built-in function
– The syntax is
range(stop)
range(start, stop [, step])
100 / 181
Lists
The range built-in function
>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2, 10,2))
[2, 4, 6, 8]
>>> list(range(2, 10,-2))
[]
>>> list(range(100, 0, -10))
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
101 / 181
Lists
List operations
>>> la
[1, 2, 3, 4, 5]
>>> lb
[’ciao’, ’a’, ’TUTTI’, ’voi’]
>>> la + lb
[1, 2, 3, 4, 5, ’ciao’, ’a’, ’TUTTI’, ’voi’]
>>> (la+lb)[1]
2
>>> 3*la
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
102 / 181
Lists
List slices
>>> la = [1,2,3,4,5]
>>> la[1:3]
[2, 3]
>>> la[1:]
[2, 3, 4, 5]
>>> la[0:1] = [10,20]
>>> la
[10, 20, 2, 3, 4, 5]
103 / 181
Lists
List methods (1/2)
104 / 181
Lists
List methods (2/2)
105 / 181
Lists
List methods
>>> la
[1, 2, 3, 4, 5, 6]
>>> lb
[1, 2, 3, 4, 5]
>>> [Link](0,11)
>>> la
[11, 1, 2, 3, 4, 5, 6]
>>> [Link](2,22)
>>> la
[11, 1, 22, 2, 3, 4, 5, 6]
106 / 181
Lists
List methods
>>> la
[11, 1, 22, 2, 3, 4, 5, 6]
>>> [Link]()
>>> la
[6, 5, 4, 3, 2, 22, 1, 11]
>>> lb
[1, 2, 3, 4, 5]
>>> [Link](lb)
>>> la
[6, 5, 4, 3, 2, 22, 1, 11, 1, 2, 3, 4, 5]
>>> [Link]()
>>> la
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 11, 22]
107 / 181
Lists
Common tasks
108 / 181
Lists
Review
109 / 181
Lists
Review
110 / 181
Lists
Review
111 / 181
Lists
Reduce /1
def sum_list(s):
sum = 0
for x in s:
sum += x
return sum
112 / 181
Lists
Reduce /2
def sum_list(s):
sum = 0
for x in s:
sum += x
return sum
a = [10,20,30,40]
print(sum_list(a))
print(sum(a))
113 / 181
Lists
Map
def capitalize_all(s):
result = []
for x in s:
[Link]([Link]())
return result
114 / 181
Lists
Filter
def only_upper(s):
result = []
for x in s:
if [Link]():
[Link](x)
return result
115 / 181
Lists
Deleting elements
116 / 181
Lists
Deleting elements
117 / 181
Lists
Lists and strings
118 / 181
Lists
Lists and strings: function split()
119 / 181
Objects and values
>>> s1 = ’ciao’
>>> s2 = ’ciao’
>>> s1 is s2
True
>>> id(s1)
139857562372896
>>> id(s2)
139857562372896
120 / 181
Objects and values
>>> s1 = ’ciao’
>>> s2 = ’ciao’
>>> id(s1)
139857562372336
>>> id(s2)
139857562373008
>>> s1 is s2
False
>>> if s1 == s2:
... print("Equivalent")
...
Equivalent
>>> s1=’ciao!’
>>> s2=’ciao!’
>>> s1 is s2
False
121 / 181
Objects and values
>>> a = [1, 2, 3, 4, 5]
>>> b = [1, 2, 3, 4, 5]
>>> a is b
False
>>> if a == b:
... print("Equivalent")
...
Equivalent
>>> id(a)
139857562454344
>>> id(b)
139857562375048
>>> a = [1, 2, 3, 4, 5]
>>> b = a
>>> b is a
True
>>> id(a)
139857562454984
>>> id(b)
139857562454984
123 / 181
Objects and values
Alias
– An object with more than one reference has more than one
name
– The object is aliased
>>> b[0] = 44
>>> a
[44, 2, 3, 4, 5]
>>> b
[44, 2, 3, 4, 5]
>>> id(a)
139857562454984
>>> id(b)
139857562454984
124 / 181
Lists
List arguments
>>> a
[44, 2, 3, 4, 5]
>>> id(a)
139857562454984
>>> def truncate(listx):
... [Link](len(listx)-1)
...
>>> truncate(a)
>>> a
[44, 2, 3, 4]
>>> id(a)
139857562454984
125 / 181
Lists
List arguments
>>> a
[44, 2, 3, 4]
>>> b = [Link](5)
>>> a
[44, 2, 3, 4, 5]
>>> b
>>> b = a + [11]
>>> a
[44, 2, 3, 4, 5]
>>> b
[44, 2, 3, 4, 5, 11]
126 / 181
Lists
List arguments
127 / 181
Lists
List arguments
def bad_truncate(listx):
listx = listx[1:]
print("Within the function: ", listx)
print(id(listx))
128 / 181
Lists
List arguments
def fine_truncate(listx):
listx = listx[1:]
print("Within the function: ", listx)
print(id(listx))
return listx
129 / 181
Digression
Using the Montecarlo method to calculate π
import math
import random
def greekpi(eps):
gpi = 0.0
no_int_points = 0
no_tot_points = 0
while abs(gpi - [Link]) > eps:
no_tot_points += 1
x = [Link]()
y = [Link]()
if (x**2 + y**2) <= 1.0:
no_int_points += 1
gpi = 4 * no_int_points / no_tot_points
print(no_int_points, no_tot_points)
print(gpi)
print([Link])
greekpi(0.000001)
130 / 181
Digression
Using the Montecarlo method to calculate π
import math
import random
def greekpi(eps):
gpi = 0.0
no_int_points = 0
no_tot_points = 0
while abs(gpi - [Link]) > eps:
no_tot_points += 1
x = [Link]()
y = [Link]()
if (x**2 + y**2) <= 1.0:
no_int_points += 1
gpi = 4 * no_int_points / no_tot_points
print(no_int_points, no_tot_points)
print(gpi)
print([Link])
greekpi(0.000001)
131 / 181
Digression
Using the Montecarlo method to calculate π
132 / 181
Digression
Using the Montecarlo method to calculate π
133 / 181
Digression
Using the Montecarlo method to calculate π
134 / 181
Dictionaries
phonebook = {}
print(phonebook)
{}
phonebook[’joe’] = ’090123456’
print(phonebook)
{’joe’: ’090123456’}
135 / 181
Dictionaries
>>> rubrica[’peppe’]
’090123’
136 / 181
Dictionaries
>>> rubrica[’franco’]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ’franco’
>>> len(rubrica)
3
>>> ’joe’ in phonebook
True
>>> ’frank’ in phonebook
False
137 / 181
Dictionaries
– Values (and keys) returned are not iterable like lists or strings:
>>> mykeys[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’dict_keys’ object does not support indexing
138 / 181
Dictionaries
Review
139 / 181
Dictionaries
Review
140 / 181
Dictionaries
Review
141 / 181
Dictionaries
Review
142 / 181
Dictionaries
Review
def counting(text):
d = dict()
for c in text:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
143 / 181
Dictionaries
Method get
144 / 181
Dictionaries
Reverse lookup
145 / 181
Dictionaries
Reverse lookup
146 / 181
Dictionaries
Dictionaries and lists
147 / 181
Tuples
>>> type(t1)
<class ’tuple’>
>>> type(t2)
<class ’tuple’>
148 / 181
Tuples
>>> t = (’a’)
>>> type(t)
<class ’str’>
149 / 181
Tuples
150 / 181
Tuples
>>> t[0]
’c’
>>> t[1:4]
(’i’, ’a’, ’o’)
>>> t[0] = ’C’
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’tuple’ object does not support item
assignment
151 / 181
Tuples
152 / 181
Tuples
Tuple assignment
153 / 181
Tuples
Tuple assignment
>>> a, b = 1, 2, 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected
2)
154 / 181
Tuples
Tuples as return values
– A function can only return one value, but if the value is a tuple
the effect is the same as returning multiple values
– For example:
>>> t = divmod(11, 3)
>>> t
(3, 2)
155 / 181
Tuples
Variable-length argument tuples
156 / 181
Tuples
Variable-length argument tuples
>>> divmod(*t)
(2, 1)
>>>
157 / 181
Tuples
Lists and tuples
>>> a = ’abc’
>>> b = [1,2,3]
>>> zip(a,b)
<zip object at 0x7f323f37b848>
>>> for i in zip(a, b):
... print(i)
...
(’a’, 1)
(’b’, 2)
(’c’, 3)
158 / 181
Tuples
Lists and tuples
159 / 181
Tuples
Lists and tuples
160 / 181
Tuples
Lists and tuples
161 / 181
Tuples
Dictionaries and tuples
162 / 181
Tuples
Dictionaries and tuples
163 / 181
Tuples
Dictionaries and tuples
164 / 181
Tuples
Dictionaries and tuples
165 / 181
Sets
166 / 181
Sets
167 / 181
Sets
newset = set()
168 / 181
Sets
print(len(nset))
if 10 in numbers:
print("The element", 10, is contained in the
set)
169 / 181
Sets
for i in range(len(nset)):
print(i,"\t", nset[i])
# TypeError: ’set’ object is not subscriptable
for i in nset:
print(i)
170 / 181
Sets
Adding elements
[Link](20)
171 / 181
Sets
Removing elements
[Link](20)
[Link](5)
172 / 181
Sets
Subsets
ca = {’red’, ’white’}
it = {’red’, ’white’, ’green’}
fr = {’red’, ’white’, blue’}
if [Link](it):
print("Subset")
if it == fr:
print("The same colors")
if ca != fr:
print("Not the same colors")
173 / 181
Sets
Review 1
174 / 181
Sets
Review 2
175 / 181
Sets
Union
ca = {’red’, ’white’}
it = {’red’, ’white’, ’green’}
fr = {’red’, ’white’, blue’}
it_u_fr = [Link](fr)
fr_u_it = [Link](it)
176 / 181
Sets
Review 3
177 / 181
Sets
Intersection
ca = {’red’, ’white’}
it = {’red’, ’white’, ’green’}
fr = {’red’, ’white’, blue’}
it_i_fr = [Link](fr)
fr_i_it = [Link](it)
178 / 181
Sets
Review 4
179 / 181
Sets
Difference
ca = {’red’, ’white’}
it = {’red’, ’white’, ’green’}
fr = {’red’, ’white’, blue’}
it_d_fr = [Link](fr)
fr_d_it = [Link](it)
180 / 181
Sets
Review 5
181 / 181