A new question arrives from the supply team: how many minutes can the engine run before the tank is empty? Rocket starts typing range, then stops.
"Wait," he says. "I do not know how many times to loop. That is the whole question."
Raven writes the rule in her notebook: keep burning while there is fuel. "What do you notice about that sentence?" she asks. "It does not give a number. It gives a condition."
Nova blinks a slow yellow. "Interesting," she says. "Python has a loop that checks a condition before every round, just like your sentence. Be sure the condition can become False."
Rocket writes the word while and thinks carefully about the last part of her hint.
A while loop checks its condition, runs its block if the condition is True, and then checks again. It stops the first time the condition is False.
Use while when you do not know in advance how many rounds you need. Use for when you do.
# burn_time.py
fuel = 100
minutes = 0
while fuel > 0:
fuel = fuel - 30
minutes = minutes + 1
print(f"Fuel ran out after {minutes} minutes.")
print("Fuel left:", fuel) | Round | fuel > 0? | fuel after | minutes after |
|---|---|---|---|
| 1 | 100 > 0 is True | 70 | 1 |
| 2 | 70 > 0 is True | 40 | 2 |
| 3 | 40 > 0 is True | 10 | 3 |
| 4 | 10 > 0 is True | -20 | 4 |
| Check | -20 > 0 is False | loop ends |
Fuel ran out after 4 minutes. Fuel left: -20
If nothing inside the loop changes the condition, it stays True forever. That is an infinite loop. The shell keeps running and never shows a new prompt.
Do not worry if it happens. Click in the shell and press Ctrl+C to stop it. You will see KeyboardInterrupt, and then you can fix the loop.
# This loop never ends: fuel never changes.
fuel = 100
while fuel > 0:
print("Burning...") while is the right loop when the question is how many steps something takes. Here a signal doubles in strength until it reaches at least 1000.
# doubling.py
signal = 1
steps = 0
while signal < 1000:
signal = signal * 2
steps = steps + 1
print("Steps:", steps)
print("Signal:", signal) Steps: 10 Signal: 1024
| Statement | True or false? |
|---|---|
| A while loop checks its condition before each round. | ? |
| If the condition is False at the very start, the block runs once anyway. | ? |
| Use while when you do not know how many rounds you need. | ? |
| Ctrl+C deletes your program file. | ? |
You can now repeat until something happens, and you know how to stop a loop that runs away. Tomorrow you will leave a loop early with break.