3. Controllo del flusso#
Nei paradigmi di programmazione imperativa (todo fare riferimento ai paradigmi di programmazione. Ha senso questa distinzione?), vengono usate delle strutture di controllo del flusso di esecuzione di un programma.
Si possono distinguere due categorie delle strutture di controllo:
condizionale ed alternativa: if, if-then, if-then-else
iterazione: for, while, …
3.1. Alternativa#
3.1.1. \(\texttt{if}\)-\(\texttt{then}\) statement#
""" if-then example """
# Try this script changing the user input
# User input
a = 2 # a is initialize as an integer
# a = 2.1 # if a is initialized as a real, a % 2 perform automatic casting, int(a) % 2
# uncomment previous line and try!
word = 'odd'
if ( a % 2 == 0 ): # automatic casting into an int -> a % 2 = floor(a) % 2
word = 'even'
print(f"User input ({a}) is an {word} number")
User input = 2 is an even number
3.1.2. \(\texttt{if}\)-\(\texttt{then}\)-\(\texttt{else}\) statement#
""" if-then-else example"""
# Try this script changing the user input
# User input
a = 15
if ( a % 3 == 1 ): # First condition
reminder = 1
elif ( a % 3 == 2 ): # Other condition
reminder = 2
else: # All the other conditions
reminder = 0
print(f"User input ({a}). {a} % 3 = {reminder}")
User input (15.7). 15.7 % 3 = 0
3.2. Iterazione#
3.2.1. for loop#
""" for loop examples
Loops over:
- elements of a list
- elements in range
- keys, values of a dict
- ...
"""
# Loop over elements of a list
seq = ['a', 3, 4. , {'key': 'value'}]
print("\nLoop over elements of the list: seq = {seq}")
for el in seq:
print(f"element {el} has type {type(el)}")
# Loop over elements of a tuple
# ...
# Loop over elements of a range
n_el = 5
range_el = range(5)
print("\nLoop over elements of the list, seq = {seq}")
print(f"range({n_el}) has type: {type(range_el)}")
print(f"range({n_el}): {range_el}")
for i in range_el:
print(i)
# Loop over keys, values of a dict
d = {'a': 1., 'b': 6, 'c': {'c1': 1, 'c2': True}}
print(f"\nLoop over elements of the dict, d = {d}")
for i,k in d.items():
print(i, k)
Loop over elements of the list: seq = {seq}
element a has type <class 'str'>
element 3 has type <class 'int'>
element 4.0 has type <class 'float'>
element {'key': 'value'} has type <class 'dict'>
Loop over elements of the list, seq = {seq}
range(5) has type: <class 'range'>
range(5): range(0, 5)
0
1
2
3
4
Loop over elements of the dict, d = {'a': 1.0, 'b': 6, 'c': {'c1': 1, 'c2': True}}
a 1.0
b 6
c {'c1': 1, 'c2': True}
3.2.2. while loop#
""" while loop example """
a = 3
while ( a < 5 ):
a += 1
print(f">> in while loop, a: {a}")
print(f"after while loop, a: {a}")
>> in while loop, a: 4
>> in while loop, a: 5
after while loop, a: 5
3.2.3. altri cicli#
todo