04_loops.ipynb - Colaboratory
04_loops.ipynb - Colaboratory
Also the for needs a column ':' at the end of the ?rst line, before the indented body of the
for , indeed a block of statements.
A for statement is called a loop because the %ow of execution runs through the body, by
executing all the block of statements, and then loops back to the top to access the next
element of the <iterable collection> .
In the simple example below, we repeat for 5 times a print statement. This is speci?ed by
range(5) .
for i in range(5):
print("Hello", i)
print("Salvatore!")
print("exit")
Hello 0
Salvatore!
Hello 1
Salvatore!
Hello 2
Salvatore!
Hello 3
Salvatore!
Hello 4
Salvatore!
exit
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 1 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
So the variable <var> of the for iterates over the list dynamically created by range , and for
each value executes the code block of the body.
where the list produced is [begin, begin + step, begin + 2*step, begin + 3*step,
...] .
The element end will not be included in the ?nal list, and step can be negative.
Function range can be called with 1, 2, or 3 parameters. These are the equivalence between
the various forms:
Look at the following example, where we use the variable of the for instantiated at each
iteration of the loop.
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 2 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
print('++++range(4)++++++')
for i in range(4):
print('Hello! Iteration:', i)
print('+++++++++++++++++++\n')
print('++++range(2,4)+++++')
for i in range(2, 4):
print('Hello! Iteration:', i)
print('===================\n')
print('++++range(1, 6, 2)+')
for i in range(1, 6, 2):
print('Hello! Iteration:', i)
print('*******************\n')
print('++++range(6,1,-1)++')
for i in range(6, 1, -1):
print('Hello! Iteration:', i)
++++range(4)++++++
Hello! Iteration: 0
Hello! Iteration: 1
Hello! Iteration: 2
Hello! Iteration: 3
+++++++++++++++++++
++++range(2,4)+++++
Hello! Iteration: 2
Hello! Iteration: 3
===================
++++range(1, 6, 2)+
Hello! Iteration: 1
Hello! Iteration: 3
Hello! Iteration: 5
*******************
++++range(6,1,-1)++
Hello! Iteration: 6
Hello! Iteration: 5
Hello! Iteration: 4
Hello! Iteration: 3
Hello! Iteration: 2
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 3 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
The for loop can be nested, i.e., within the body of the loop we can insert another for loop.
n = 5
for i in range(1,n+1):
for j in range(1,n+1):
print(i*j, end=' ')
print()
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Now we try to complete a program that prints a grid like the following (2 × 3):
----------------
| | | |
----------------
| | | |
----------------
r = 2
c = 3
for j in range(r):
# print row
for i in range(c):
print('-----', end='')
print('-')
----------------
----------------
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 4 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
While loop
There is a more Lexible alternative to for loops. This is an example of countdown:
The body has to contain some statements that change the value of the condition, to allow the
control Low to eventually exit from the loop. Otherwise the loop will repeat forever, which is
called an in8nite loop.
Below we show the example above of the countdown computation expressed with a while .
Note that you can almost read the while statement as if it were written English. It means:
“While n is greater than 0, display the value of n and then decrement n. When you get to 0,
display the phrase "Launch the rocket!" .
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 5 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
10
9
8
7
6
5
4
3
2
1
Launch the rocket!
n = 10
while n > 0:
print(n)
n = n - 1
print('Launch the rocket!')
10
9
8
7
6
5
4
3
2
1
Launch the rocket!
# Given as input an integer number. Assume that we can represent it with 8 bits (ma
# Print its binary representation starting from the most significant.
# (Hint: use the substraction method. Try to represent the number as the sum of pow
# At each step, if 2**i is the biggest power of two which is not more than the x, p
# Print 0 otherwise)
if 2**7 <= N:
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 6 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
if 2**6 <= N:
print(1, end='', sep='')
N = N - 2**6
else:
print(0, end='', sep='')
if 2**5 <= N:
print(1, end='', sep='')
N = N - 2**5
else:
print(0, end='', sep='')
if 2**4 <= N:
print(1, end='', sep='')
N = N - 2**4
else:
print(0, end='', sep='')
if 2**3 <= N:
print(1, end='', sep='')
N = N - 2**3
else:
print(0, end='', sep='')
if 2**2 <= N:
print(1, end='', sep='')
N = N - 2**2
else:
print(0, end='', sep='')
if 2**1 <= N:
print(1, end='', sep='')
N = N - 2**1
else:
print(0, end='', sep='')
if 2**0 <= N:
print(1, end='', sep='')
N = N - 2**0
else:
print(0, end='', sep='')
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 7 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
i = 15
while i >= 0:
if 2**i <= N:
print(1, end='', sep='')
N = N - 2**i
else:
print(0, end='', sep='')
i = i - 1
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 8 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
break
Sometimes you don’t know the time to end a loop, until you get half way through the body. In
that case you can use the break statement to jump out of the loop ( while or for ).
For example, suppose you want to take input from the user until they type done. You could
write:
while True:
line = input('> ')
if line == 'done':
break
print(line)
print("exit from while!")
> hhh
hhh
> hhhh
hhhh
> qqqqq
qqqqq
> done
exit from while!
An alternative way without break requires a Boolean variable, initialized to True and then
modi?ed in the body to force the loop to exit:
not_done = True
while not_done:
line = input('> ')
if line == 'done':
not_done = False
else:
print(line)
print("exit from while!")
> dddd
dddd
> w
w
> ciao
ciao
> done
exit from while!
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 9 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
continue
The continue statement in Python returns the control to the beginning of the while loop.
The continue statement rejects all the remaining statements in the current iteration of the
loop and moves the control back to the top of the loop.
The continue statement can be used in both while and for loops.
# Read and print all the integer numbers > 0, otherwise print "number must be posit
# Exit when the number = 0
while True:
n = int(input('input a positive number (0 for exit): '))
if n == 0:
break
if n < 0:
print("number must be positive!")
continue
print(n)
Catching exceptions
Consider this code, where depending on the input you can obain a runtime error, also called
exceptions. To force the occurrence of this exception, type a letter besides number and minus
( - ) symbols.
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 10 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
The observed exception is ValueError . Is it possible to catch this exception and handle it to
avoid blocking the execution?
The try block allows us to execute a block of code, and tests for errors without
blocking the execution.
The except block lets us handle the error. The except block is executed only if an
exception/error is raised, and the program is not terminated.
while True:
try:
a = int(input("Enter an integer number: "))
break
except:
print("The input cannot be transformed into an integer!")
print("integer:", a)
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 11 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35
print("integer:", a)
https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 12 di 12