The while#

loops

In programming, there are sets of instructions that need to be repeated multiple times.

For example, if you want to perform the same task on all the elements of a list.

When you need to repeat a set of instructions, sometimes you know how many

times you are going to repeat it, other times you do not. Sometimes, the number of

repetitions is not important, and you want to repeat the code until a

certain condition is met.

For all these uses, you will use loops.

The role of a while loop is to execute a block of code, that is, a certain

number of instructions, as long as a condition is true.

A while loop in Python therefore always starts with a logical test. Python checks

if a condition is true: if it is not, we do not even enter the loop!

On the other hand, if the condition is true, Python executes the block of code that is just

below.

Once the first iteration is complete, Python checks again whether the condition is

true or not. As long as the condition is true, Python executes the block of

code again.

The while loop stops when the logical test is no longer verified. Then, it

does not execute the block of code below, and exits the loop. The rest of the program

takes over.

When writing a WHILE loop, you have to pay attention to two things:

  • the first line always ends with a colon “:”

  • the block of code that contains the instructions must be indicated by an indentation. This is how Python differentiates between what is included in the while loop and the rest of the program.

Execute the following cell and observe the result:

n = 1

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

We have created a program that counts from 1 to 5.

Exercise 1: First while loop#

  • Execute the following cell:

n = 1
a = 5
while n <= a:
    print(n)
    n = n + 1
1
2
3
4
5
  • Modify the value of a above to obtain:

  • Exactly 1 display

  • Exactly 0 display

  • Exactly 4 displays

Exercise 2: Panic in the Dark#

Our ant is lost in a dark labyrinth. It’s panicking! Before

each step, it randomly turns left or right. Will it find

the exit?

It’s up to you to find out by programming the ant’s behavior!

To simulate the dark, we have written a function that places the door randomly.

Execute the following two cells. Each time the labyrinth is created, the

door is placed in a different location. The same program should always work!

Hints:

  • You can use the condition regarde() != Sortie;

  • To flip a coin to decide whether the ant will turn left or right, you can use the function random.randint(0,1) which randomly returns 0 or 1.

import random
def porteAleatoire():
    s = "o o o o o o o\n"
    s += "o → . . . . o\n"
    ligne = random.randint(0, 3)
    col = random.randint(0, 4)
    for i in range(4):
        s += "o "
        for j in range(5):
            if ( i == ligne and j == col ):
                s += "x "
            else:
                s += ". "
        s += "o\n"
    s += "o o o o o o o\n"
    return s

from laby.global_fr import *
Laby(carte = porteAleatoire())
/home/nthiery/work/Enseignement/py-edu-fr/init-laby/.venv/lib/python3.12/site-packages/laby/laby.py:337: SyntaxWarning: invalid escape sequence '\w'
  p = re.compile("[A-Z]+(\w)*")
debut()
### BEGIN SOLUTION
while ( regarde() != Sortie ):
    if ( random.randint(0,1) == 0 ):
        gauche()
    else:
        droite()
    avance()
ouvre()
### END SOLUTION

Exercise 3: Euclidean division by subtraction#

  • Observe the following cells, then in the next cell, assign values to \(b\) and \(c\) with \(b > c\) so that, at the end of the loop, we have \(b=3\):

### BEGIN SOLUTION
b = 18;
c = 5;
### END SOLUTION
while ( b >= c ):
    b = b - c
b
3

Automatic test (should display nothing):

assert( b == 3 )
  • Modify the cell below by introducing a variable \(k\) that counts the number of loop executions;

  • Assign values to \(b\) and \(c\) before the loop such that, at the end of the loop, we have \(b=3\) and \(k=5\).

### BEGIN SOLUTION
b = 23;
c = 4;
k = 0;
### END SOLUTION
while ( b >= c ):
    b = b - c
    ### BEGIN SOLUTION
    k = k + 1
    ### END SOLUTION
b     # doit afficher 3
3
k     # doit afficher 5
5

Automated tests:

assert( b == 3 )
assert( k == 5 )

Exercise 4: Syracuse sequence#

  • Execute the cell below without modifying it, then execute the second cell three times:

d = 5
if ( d % 2 == 0):
    d = d // 2;
else:
    d = 3 * d + 1
print(d)
16

Note that when the number \(d\) is even, it is divided by 2 (using the integer division operator //). When it is odd, it is multiplied by 3 and 1 is added.

  • Rewrite the cell, completing it so that this action is repeated as long as the number \(d\) is greater than 1. We want to display the value of \(d\) each time. If your code is correct, it should display 16 8 4 2 1 (starting from d=5).

### BEGIN SOLUTION
d = 5
while d > 1:
    if d % 2 == 0:
        d = d // 2;
    else:
        d = 3 * d + 1
    print(d)
### END SOLUTION
16
8
4
2
1

Exercise 5#

  • Observe the following function and try to understand what it calculates by reading the code and trying several call values:

def mystere(n):
    k = 1
    while k * k < n:
        k = k + 1
    return k
mystere(5)
3
  • Determine a value of n such that the returned value is 6:

n = 0
### BEGIN SOLUTION
n = 36
### END SOLUTION
mystere(n)
6
assert( mystere(n) == 6 )

The while loop: more examples#

Special case: always false condition#

*If the condition is false from the start, then the block of instructions will

never be executed!*

n = 1

while n <= 0:
    print(n)   ## Affiche la valeur de n
    n = n + 1;

Special case: condition always true#

*If the value of the condition is always true, then the block of instructions will be

executed indefinitely!*

Warning

Warning ⚠️ The following example will not stop! You will have to restart the kernel (Kernel menu) ⚠️

n = 1

while True:
    print(n)    # Affiche la valeur de n
    n = n + 1

Classic error: end of loop#

What is the value of \(n\) at the end of the following program?

n = 1

while n <= 5:
    n = n + 1

print(n)
6

Key takeaway:

  • We exit the loop when the condition is “False”; the counter is therefore “one step too far”.

Overview#

You can now practice on additional exercises by running the

following cell, or move on to the sheet on for loops. You can then

tackle the more advanced exercise below.

Additional exercises#

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

Exercise 6 ♣#

  • Complete the code of the following function so that it determines whether \(n\) is a perfect square. If so, it should return true; otherwise it should return false.Reminder: A perfect square is a number that can be written as \(k\times k\) with \(k\) an integer. For example, \(16\) is a perfect square because \(16 = 4 \times 4\), but \(20\) is not a perfect square.

def carreParfait(n):
    ### BEGIN SOLUTION
    k = 0
    while ( k * k < n ):
        k = k + 1
    return k*k == n
    ### END SOLUTION
  • Try your function on the following examples:

carreParfait(16)  # doit renvoyer true
True
carreParfait(20)  # doit renvoyer false
False
  • Check that your function passes the following automatic tests:

assert( carreParfait(0) )
assert( carreParfait(1) )
assert( not carreParfait(2) )
assert( not carreParfait(50) )
assert( carreParfait(100) )
assert( not carreParfait(250) )