Loops in Python
loops are a powerful tools used in various problems, that's why we focus on this course in how to use them in Python.
In the other programming languages like C/C++ and Java we found three different kinds of loops, In Python, there are only two ways to execute loops. Although all methods offer similar basic functionality, their syntax and time for checking conditions differ.
While Loop
In python, the while loop is used to execute a block of statements repeatedly until a given condition is met. And when the condition becomes false, the line immediately after the loop in the program is executed.
Syntax
while condition/expression: instructions
All instructions indented by the same number of character spaces and are considered to be part of a single block of code. Python uses indentation as a method of grouping statements.
Example
nb = 1 while nb <= 5: print(nb) nb += 1
2
3
4
5
Else
while loop executes the block until a condition is met. When the condition becomes false, the instruction immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you exit the loop or if an exception is thrown, it will not be executed.
Syntax
while condition/expression: # Execute theses instructions else: # Execute theses instructions
Example 1
nb = 1 while nb <= 5: print(nb) nb += 1 else: print("bye bye")
2
3
4
5
bye bye
Example 2
nb = 1 while nb <= 5: print(nb) nb += 1 break else: print("bye bye")
2
3
4
5
bye bye
For in Loop
The for loop is used for sequential traverses. For example: browse a list, a chain, an array, etc.
In Python, there is no for style (i = 0; i <n; i ++). There is a "for in" loop similar to foreach in other programming languages.
Syntax
for iterator in sequence: instructions
Example 1
L = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samed', 'Dimanche'] for jour in L: print(jour)
Mardi
Mercredi
Jeudi
Vendredi
Samed
Dimanche
Example 2
L = ('Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samed', 'Dimanche') for jour in L: print(jour)
Mardi
Mercredi
Jeudi
Vendredi
Samed
Dimanche
Example 3
D = {} D['nom'] = 'ESSADDOUKI' D['prenom'] = 'Mostafa' D['Annee'] = 2019 for cle in D: print(cle, ' : ', D[cle])
prenom : Mostafa
Annee : 2019
Exemple 4
# range(fin) for i in range(5): print(i, end=" ") print() #range(debut, fin) for i in range(2, 5): print(i, end=" ") print() #range(debut, fin, pas) for i in range(1, 11, 2): print(i, end=" ") print()
2 3 4
1 3 5 7 9
Example 5
L = ('Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samed', 'Dimanche') for i in range(len(L)): print(L[i])
Mardi
Mercredi
Jeudi
Vendredi
Samed
Dimanche
Example 6
msg = 'Bonjour' for lettre in msg: print(lettre) print('-------------') for i in range(len(msg)): print(i, ': ', msg[i])
o
n
j
o
u
r
-------------
0 : B
1 : o
2 : n
3 : j
4 : o
5 : u
6 : r
Else
The else block will be executed immediately after the block is executed. If you exit the loop or if an exception is thrown, it will not be executed.
for i in range(5): print(i) else: print('bye bye') print('------------------') for i in range(5): if i == 2: break print(i) else: print('bye bye')
1
2
3
4
bye bye
------------------
0
1
Nested loops
Python allows you to use a loop in another loop (nested loops).
Syntax
for iterator1 in sequence1: for iterator2 in sequence2: instructions
while condition1: while condition2: instructions
Example 1
for i in range(2): for j in range(3): print(i, ' - ', j)
0 - 1
0 - 2
1 - 0
1 - 1
1 - 2
Example 2
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] n = len(matrix) # nombre de lignes m = len(matrix[0]) # nombre de colonnes for i in range(n): # pour chaque ligne print("row ", i, " of the matrix : ", end=" ") for j in range(m):# for each column of row i print(matrix[i][j], end=' ') print("")
row 1 of the matrix : 4 5 6
row 2 of the matrix : 7 8 9
row 3 of the matrix : 10 11 12
Loop control instructions
The loop control instructions modify the normal execution of the sequence.
Instruction continue
It returns control to the start of the loop.
L = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samed', 'Dimanche'] print("here are the days of the week except Thursday and Friday in French") for i in range(len(L)): if i == 3 or i == 4: continue print(L[i], end=" ")
Lundi Mardi Mercredi Samed Dimanche
Instruction break
It ends the current loop and resumes execution at the next instruction after the loop
L = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samed', 'Dimanche'] # leave if day is Thursday for i in range(len(L)): if i == 3: break print(L[i], end=" ") print("\nIt's Done")
It's Done
Instruction pass
We use the pass statement to write empty loops. Pass is also used for empty control statements, functions, and classes.
L = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samed', 'Dimanche'] for jour in L: pass print("the last day of the week in french is ", jour)
class EmptyClass: pass
0 Comment(s)