A loop with a condition
In the last module, every loop started with while True:. Since True is always true, a loop like that would run forever on its own, so a break inside it did the stopping. But while can do more: like if, it takes any condition, and the loop runs as long as the condition is true.
Here is a loop in the style of the last module. It counts to three:
number = 1
while True:
if number > 3:
break
print(number)
number += 1
print("Done")
1
2
3
DoneAnd here is the same loop with a condition:
number = 1
while number <= 3:
print(number)
number += 1
print("Done")
1
2
3
DoneThis is what Python does with it:
- It checks the condition
number <= 3. If it's true, it runs the indented lines under thewhile, the body of the loop. - At the end of the body, it goes back up to the
whileline and checks the condition again. - As soon as the condition is false, it skips the body and goes on with the first line after the loop.
One pass through the body is an iteration of the loop, as in the last module. These lessons also call it a round, which is shorter. Here the body runs three times, with number at 1, 2 and 3. After the third round number is 4, the condition 4 <= 3 is false, and the loop ends.
Compare the two conditions. The if before break says when to stop: number > 3. The while condition says when to keep going: number <= 3. One is the opposite of the other. The version with the condition is shorter, and a reader sees right at the top how long the loop runs.
The condition comes first
Python checks the loop condition before every round, the first one included. If the condition is false from the start, the body doesn't run at all:
lap = int(input("Starting lap: "))
while lap <= 5:
print(f"Lap {lap}")
lap += 1
print("Race over")
3Starting lap: 3
Lap 3
Lap 4
Lap 5
Race overWith 8 as the input, 8 <= 5 is false straight away, so after the prompt the program prints only Race over.
The condition is checked only there, at the top. If it becomes false in the middle of the body, the rest of the body still runs, and the loop ends when Python comes back up to check.