0% found this document useful (0 votes)
3 views

04_loops.ipynb - Colaboratory

The document explains the use of loops in Python, specifically focusing on 'for' and 'while' loops, including their syntax and examples. It also covers nested loops, the 'break' and 'continue' statements, and how to handle exceptions when user input is involved. Various examples illustrate the concepts, including generating multiplication tables and binary representations of integers.

Uploaded by

899141
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

04_loops.ipynb - Colaboratory

The document explains the use of loops in Python, specifically focusing on 'for' and 'while' loops, including their syntax and examples. It also covers nested loops, the 'break' and 'continue' statements, and how to handle exceptions when user input is involved. Various examples illustrate the concepts, including generating multiplication tables and binary representations of integers.

Uploaded by

899141
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

04_loops.

ipynb - Colaboratory 27/02/24, 13:35

 Simple repetition ( for )


If we have to repeat a piece of code many times, we can use the simple for statement, which
repeats for a given number of timed the nested block of instructions, i.e., the body of the for .

The general syntax of a for loop is

for <var> in <iterable collection>:


<block of statements>

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

Function range(n) generate a list of integers from 0 up to n-1: [0,1,2,3,...,n-1] .

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.

The general form of range has 3 parameters:

range(begin, end, step)

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:

range(end) = range(0, end, 1)


range(begin, end) = range(begin, end, 1)

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.

This code print a 5 × 5 multiplication table.

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:

for n in range(10, 0, -1):


print(n)
print('Launch the rocket!')

The general syntax of a while loop is

while <Bool condition>:


<block of statement>
<next statement>

where the Low of execution is:

1. Determine whether the condition is True or False.


2. If False, exit the while statement and continue execution at the ?rst statement after of
the body ( next statement ).
3. If the condition is True, run the body, and then go back to step 1.

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

for n in range(10, 0, -1):


print(n)
print('Launch the rocket!')

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)

# use for and range():

N = int(input("Integer N, 0 <= N <= 255? "))

# 2**7 * d7 + 2**6 * d6 + 2**5 * d5 + 2**4 * d4 + 2**3 * d3 +


# + 2**2 * d2 + 2**1 * d1 + 2**0 * d0 = N

if 2**7 <= N:

https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 6 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35

print(1, end='', sep='')


N = N - 2**7
else:
print(0, end='', sep='')

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

Integer N, 0 <= N <= 255? 2


00000010

N = int(input("Integer N, 0 <= N <= 65535? "))

# 2**15 * d15 + ..... + 2**7 * d7 + 2**6 * d6 + 2**5 * d5 + 2**4 * d4 + 2**3 * d3


# + 2**2 * d2 + 2**1 * d1 + 2**0 * d0 = N

for i in range(15, -1, -1):


if 2**i <= N:
print(1, end='', sep='')
N = N - 2**i
else:
print(0, end='', sep='')

Integer N, 0 <= N <= 65535? 65535


1111111111111111

N = int(input("Integer N, 0 <= N <= 65535? "))

# 2**7 * d7 + 2**6 * d6 + 2**5 * d5 + 2**4 * d4 + 2**3 * d3 +


# + 2**2 * d2 + 2**1 * d1 + 2**0 * d0 = N

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

Integer N, 0 <= N <= 65535? 3


0000000000000011

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)

# equivalent code without 'continue'


# ...
# if n < 0:
# print("number must be positive")
# else:
# print(n)

input a positive number (0 for exit): 45


45
input a positive number (0 for exit): 3
3
input a positive number (0 for exit): -2
number must be positive!
input a positive number (0 for exit): 1
1
input a positive number (0 for exit): 0

 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

a = int(input("Type an integer number: "))


print(a)

Type an integer number: 10.1


---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-5604a3338482> in <cell line: 1>()
----> 1 a = int(input("Type an integer number: "))
2 print(a)

ValueError: invalid literal for int() with base 10: '10.1'

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.

For handling errors in the input, we can thus operate as follows:

while True:
try:
a = int(input("Enter an integer number: "))
break
except:
print("The input cannot be transformed into an integer!")

print("integer:", a)

Enter an integer number: 99-99


The input cannot be transformed into an integer!
Enter an integer number: -9999y
The input cannot be transformed into an integer!
Enter an integer number: -9999
integer: -9999

https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 11 di 12
04_loops.ipynb - Colaboratory 27/02/24, 13:35

# We can also check the specific raised error


while True:
try:
a = int(input("Enter an integer number: "))
break
except ValueError: # ValueError raised for an inappropriate argument value of a
print("The input cannot be transformed into an integer!")

print("integer:", a)

Enter an integer number: eee


The input cannot be transformed into an integer!
Enter an integer number: 11
integer: 11

https://colab.research.google.com/drive/17ZF8QQkTMBAOxwte3QtIrxlMpu21ap85 Pagina 12 di 12

You might also like