while Loops and Stopping Conditions
Unit ID: M04-U04 Estimated active time: 20-30 minutes
Repeat while a condition remains true
attempt = 1
while attempt <= 3:
print(f"Attempt {attempt}")
attempt = attempt + 1
The loop has three visible parts:
- initial state:
attempt = 1; - condition:
attempt <= 3; - progress:
attemptincreases each time.
Without progress, the condition may stay true forever.
Prefer for when iterating over a known collection
Use for to process every item in a list. Use while when repetition depends on a changing condition and the number of repetitions is not naturally the collection length.
A safe countdown
remaining = 3
while remaining > 0:
print(remaining)
remaining = remaining - 1
print("Complete")
Trace remaining: 3, 2, 1, then 0. At 0, the condition is false and the loop ends.
Infinite-loop warning
This loop never changes remaining:
remaining = 3
while remaining > 0:
print(remaining)
Interrupt the kernel if code continues unexpectedly. Then repair the stopping logic before rerunning.
Use a maximum as a safeguard
When retrying a simulated operation, keep an explicit limit:
attempt = 1
maximum_attempts = 3
success = False
while attempt <= maximum_attempts and not success:
print(f"Checking attempt {attempt}")
success = attempt == 2
attempt = attempt + 1
This deterministic example succeeds on attempt 2. Real retries need carefully defined failure handling and should not repeat unsafe actions automatically.
Practice
Start with current_hours = 0. Add 2 during each loop until the value reaches 8. Print each new value. Then explain the initial state, condition, progress step, and final state.
Takeaway
Every while loop needs visible state, a condition, and reliable progress toward stopping. Prefer for when the collection already defines the repetitions. Next, we will control searches with break, continue, and loop else.
