1. About Loops in Python

Loops are algorithmic tools that allow us to execute a block of code several times, i.e. to execute code “in a loop” as long as a given condition is verified.
When coding, we will often have to execute the same code several times. Using a loop allows us to write code that needs to be executed multiple times only once.
We will thus be able to use loops to browse the values ​​of a list variable or to display a sequence of numbers etc.
For this purpose, the Python language offers us two loops:

  1. The while loop
  2. The for loop

The general operation of loops will always be the same: we set a condition which will generally be linked to the value of a variable and we execute the code of the loop as long as the condition is verified.

2. The For loop in Python …

The for loop in Python, allows to execute repeated instructions.

Syntax:

for counter in range(start_counter, end_counter):
     instructions...

Example. display the first 10 numbers

for i in range (1,11):
     print(i)
#prints the first 10 numbers 1, 2, ..., 10

Note

Note that in the loop for i in range(1, n) the last one which is n is not included! This means that the loop stops at order n-1.



3. The repetitive structure While

The while structure is used to execute a set of statements as long as a condition is fulfilled and execution stops when the condition is no longer satisfied.

Syntax

while (condition):
       intructions ...

Example. display of the first 10 integers with the while loop

i = 1
while(i <= 10):
    print (i)
    i = i + 1
"""
output:
1
2
3
4
5
6
7
8
9
10
"""

4. Stopping a loop with break instruction

Sometimes we need to stop a loop when a certain result is reached. To immediately stop a loop, you can use the break keyword.
Example let's have fun looking for the first number greater than 10 in a list:

Exemple (searching the first number greater than 10)

L = [ 3 , 7 , 11 , 23, 31 , 20 , 27]
for x in L:
    # we test if x > 10
    if x > 10:
        print("The first number greater than 10 is : ", x)
        # on quitte la boucle
        break
# output: The first number greater than 10 is :  11

 

Younes Derfoufi
my-courses.net

Leave a Reply