Start, condition, update
A loop that counts needs three things. Here they are in a loop that prints the times of a bus that leaves every two hours:
hour = 9 # 1. the start value
while hour <= 17: # 2. the condition
print(f"{hour}:00")
hour += 2 # 3. the update
9:00
11:00
13:00
15:00
17:00- Initialization: before the loop, the variable in the condition gets its first value. Here
hourstarts at 9. - Condition: at the top of the loop, it decides whether another round runs.
- Update: in the body, the variable changes, so that every round brings the loop closer to its end. Here
hourgrows by 2 in every round, so sooner or laterhour <= 17is false.
If one of the three is missing or wrong, the loop goes wrong too.
Forgetting the start value
Without an initialization, the variable doesn't exist yet when Python first checks the condition:
while total < 100:
total += 30
print(total)
Traceback (most recent call last):
File "main.py", line 1, in <module>
while total < 100:
^^^^^
NameError: name 'total' is not definedThe fix is a line before the loop that gives total its start value, such as total = 0.
Forgetting the update
Without an update, the condition never changes. If it's true once, it stays true forever:
hour = 9
while hour <= 17:
print(f"{hour}:00")
This prints 9:00 again and again, without end: an infinite loop, like the ones in the last module. On your own computer you stop such a program with Ctrl+C. On this site, a program that runs for more than a few seconds, or prints a huge amount, is stopped for you, with a note that says so.
A sneakier way to lose the update is to forget its indentation:
hour = 9
while hour <= 17:
print(f"{hour}:00")
hour += 2
hour += 2 isn't indented, so it isn't part of the body. Only the indented lines repeat; this line would run once the loop is over, and the loop is never over.
The update can also go the wrong way. With hour -= 2, hour gets smaller in every round and stays below 17 forever. So before you run a loop, ask yourself: does every round take a step toward making the condition false?