The for#

loops

Motivation#

Let’s return to our program to count from 1 to 5:

n = 1

while n <= 5:
    print(n)
    n = n + 1
1
2
3
4
5

It follows a classic program pattern with a counter:

    initialisation

    while condition:
        bloc d instructions
        incrémentation


Initialization

While condition: Block of instructions Incrementation

  • The initialization n = 1 determines from which value we count;

  • the increment n = n + 1 determines by how much we count;

  • the condition n <= 5 determines up to which value we count.

Problem:

Counter management is scattered: the reader has to look in three places to

get all the information about the counter. In particular, the increment is found

far away if the instruction block is long.

To overcome this, most programming languages introduce the

for loop: “for … from … to … do …”. Here’s how it’s written in Python on our

example:

for i in range(1, 6):
    print(i)
1
2
3
4
5

Literally, this translates to: “for i in the sequence from 1 to 6 exclusive, display

i”.

The range() function#

Definition: The range() function

The range function returns a sequence of integers. It is often used in

loops to repeat an action a certain number of times. It can be used in

three forms:

  • range(fin): generates a sequence of integers from 0 to fin (exclusive).

  • range(début, fin): generates a sequence of integers from début to fin (exclusive).

  • range(début, fin, pas): generates a sequence of integers from début to fin (exclusive), in steps of pas.

  • Displays the numbers from 0 to 4:

for i in range(5):
    print(i)
0
1
2
3
4
  • Displays the numbers from 1 to 5:

for i in range(1, 6):
    print(i)
1
2
3
4
5
  • Displays the odd numbers (in steps of 2) between 1 and 9:

for i in range(1, 10, 2):
    print(i)
1
3
5
7
9
  • The step can also be negative:

for i in range(5, 0, -1):
    print(i)
5
4
3
2
1

Definition: for loop

Syntax:

for i in range(début, fin, pas):
    # bloc d'instructions

Semantics

  1. Initialization: At the beginning of the loop, Python extracts the first value given by \(range()\), and it is placed in the temporary variable \(i\).

  2. Block of instructions: The block under the loop is executed.

  3. Iteration: Python extracts the next element given by \(range()\) and assigns its value to the variable \(i\).

  4. End of loop: The loop ends when all the values have been traversed.

In the previous examples, we used \(range()\), which generates a sequence

of integers: the \(for\) loop also works by iterating over other types of data

such as lists; we will come back to this later in the course.

Exercise: Let’s count!#

  • Copy the for instruction below into the next cell, and replace the three “?” with the appropriate values to display the even integers between 0 and 20 (0, 2, 4, …, 20):

    for i in range(?, ?, ? ):
        print(i)
    
### BEGIN SOLUTION
for i in range(0, 21, 2):
    print(i)
### END SOLUTION
0
2
4
6
8
10
12
14
16
18
20
  • Write for loops that display the following numbers in the given order:

0, 3, 6, 9, 12:

### BEGIN SOLUTION
for i in range(0, 13, 3):
    print(i)
### END SOLUTION
0
3
6
9
12

20, 21, 22, 23, 24, 25:

### BEGIN SOLUTION
for i in range(20, 26):
    print(i)
### END SOLUTION
20
21
22
23
24
25

10, 9, 8, 7, 6, 5, 4, 3, 2, 1:

### BEGIN SOLUTION
for i in range(10, 0, -1):
    print(i)
### END SOLUTION
10
9
8
7
6
5
4
3
2
1

Using the for loop in Laby#

  • Take on the Laby challenge below if you haven’t already done so in Week 1:

from laby.global_fr import *
Laby("counting-the-rocks")
### BEGIN SOLUTION
# Prend le caillou qui est devant et le pose derrière
def deplace_caillou_derriere():
    prend()
    avance()
    gauche()
    gauche()
    pose()
    gauche()
    gauche()
### END SOLUTION
debut()
### BEGIN SOLUTION
avance()
# Avance et pose les cailloux derrière (7 fois)
for i in range(0, 7):
    deplace_caillou_derriere()

# Tourne à gauche puis avance (2 fois)
for i in range(0,2):
    gauche()
    avance()
    avance()

# Tourne à droite puis avance à travers les cailloux (4 fois)
droite()
for i in range(0,4):
    deplace_caillou_derriere()

# Tourne à droite puis avance à travers les cailloux (5 fois)
droite()
avance()
for i in range(0,5):
    deplace_caillou_derriere()

gauche()
avance()
avance()
ouvre()
### END SOLUTION
assert est_gagnant()
  • ♣ Write a function carre(L) that takes an integer L as a parameter, and that makes the ant follow a square path with sides of L squares. The ant must return to the starting square at the end of the function.

Laby(carte=
"o o o o o o o o o o o o\n"
"o . . . . . . . . . . o\n"
"o . . . . . . . . . . o\n"
"o . . . . . . . . . . o\n"
"o . . . . . . . . . . o\n"
"o . . . . . . . . . . o\n"
"o . . . . . . . . . . o\n"
"o . . . . . . . . . . o\n"
"o . . . . . . . . . . o\n"
"o . . . . . . . . . . o\n"
"o ↑ . . . . . . . . . o\n"
"o o o o o o o o o o o o\n"
)
# Entrée : un entier L, correspondant à la longeur d'un côté de la trajectoire.
# Sortie : aucune, déplace la fourmi selon un carré de longueur L
### BEGIN SOLUTION
def carre(L) :
    if (L > 0):
        for i in range(4):
            for j in range(L-1):
                avance()
            droite()
### END SOLUTION
debut()
carre(0)  # La fourmi ne fait rien
debut()
carre(1)  # La fourmi doit faire un tour sur elle-même
debut()
carre(5)  # la fourmi doit parcourir un carré de longueur 5 cases

Additional exercises#

import glob, os
from jupylates import Exerciser
os.chdir("../Exercices")
Exerciser(glob.glob("boucles-for/*"), mode="train")

Summary#

Tip

Key points to remember When the loop involves a counter, we generally use a for loop, and

otherwise a while loop.