3.7.1. Looping using while#
The while
instruction repeats a code block as long as a condition is true. Its syntax is:
while condition:
instruction1()
instruction2()
instruction3()
...
where condition
is a boolean variable. Each repetition of a code block is called an iteration.
Here is an example with five iterations of a code block:
i = 0
while i < 5:
print(f"Now, the variable i is {i}.")
i += 1
print("done")
Now, the variable i is 0.
Now, the variable i is 1.
Now, the variable i is 2.
Now, the variable i is 3.
Now, the variable i is 4.
done
We see that as long as i
was strictly lower than 5, the while
instruction executed the code block. When i
equaled 5, the (i < 5)
condition evaluated to False, and therefore the while
instruction stopped executing the code block.
Here is a practical example where we took some measurements in metres and stored them in a list. We want to convert this list to another list where the measurements are in millimetres instead:
# Measurements in meters:
meters = [0.329, 0.009, 0.210, 0.726, 0.686, 0.912, 0.285, 0.833, 0.334, 0.165]
# Create an empty list of the same measurements in millimeters, which we will
# fill up using a while loop.
millimeters = []
# Multiply each element of meters by 1000, and append it to the millimeters list.
i = 0
while i < len(meters):
millimeters.append(meters[i] * 1000)
i += 1
# Done.
millimeters
[329.0, 9.0, 210.0, 726.0, 686.0, 912.0, 285.0, 833.0, 334.0, 165.0]
Good practice: Looping
While this example works perfectly well and is indeed a correct demonstration of how while
works, we will see later that for this specific example, other methods such as using for or NumPy would be less error-prone and faster.