──────────────────────────────────────

15. Game Loops · Give a Loop an Exit

Make a while loop stop when a value reaches its limit.

Lesson files · lessons/loops-and-games/while-and-stop

Before you start
- Use a comparison to make a yes-or-no decision.
- Update a running total inside a loop.

By the end
- Use while to repeat while a condition is true.
- Trace the update that makes the loop stop.
- Test an input for which the loop runs zero times.

Where you can use it
Play a simple game while the player has energy left. Lower the energy on each turn and show the end message after it reaches zero.

A while loop checks its condition before each trip through the indented body. Start with fuel at 2. Each fuel -= 1 update subtracts one. When fuel reaches 0, fuel > 0 becomes False and the program continues with the line after the loop.

If a loop keeps running, press Stop. Trace the starting value, the condition and the update to find out what keeps it going.

Predict
Which line makes the condition eventually false?
- fuel -= 1
- print("Engine off.")

Worked example (example.py)

fuel = 2
while fuel > 0:
    print(f"Fuel: {fuel}")
    fuel -= 1
print("Engine off.")


Example result
Fuel: 2
Fuel: 1
Engine off.

Read a starting battery number. While it is above zero, print Battery: with the current value and lower it by one. Then print Power down.

Starter program (starter.py)

fuel = 2
while fuel > 0:
    print(f"Fuel: {fuel}")
    fuel -= 1
print("Engine off.")


Hint
The final print belongs outside the loop. Test the case where the starting battery is already 0.

Case 1. Try the sample
Input
2
Expected output
Battery: 2
Battery: 1
Power down.

Case 2. Already empty
Input
0
Expected output
Power down.

Stretch
Predict and test the result of draining two units per round.

Reflect
How can you tell from the code that the loop will stop?

Check your prediction
fuel -= 1 The subtraction is inside the loop, so each repetition moves fuel toward zero.
