Python - While Loops
Overview
Estimated time: 15–25 minutes
Use while loops for condition-driven repetition, with safe termination patterns.
Learning Objectives
- Write while loops with clear termination conditions.
- Use break,continue, andelsewith loops.
- Prefer forwhen iterating over collections.
Prerequisites
Examples
n = 3
while n > 0:
    print(n)
    n -= 1
else:
    print("done")
Breaking and continuing
i = 0
while True:
    i += 1
    if i % 2 == 0:
        continue
    if i > 5:
        break
    print(i)
Common Pitfalls
- Forgetting to update the loop variable → infinite loop.
- Using while Truewithout a clear and reachablebreak.
Checks for Understanding
- When does the elseon a loop execute?
- How do you avoid infinite loops?
Show answers
- When the loop finishes without hitting break.
- Ensure the condition changes and/or include a clear breakpath.
Exercises
- Read integers from input until 0 is entered; print their sum.
- Implement a guessing game with at most 5 attempts.