Python Fundamentals ยท Control Flow

while Loops

Repeat while a condition stays true. Watch the condition being checked before every round, and the loop stop once it turns false.

while_loop.py

savings = 100
months = 0

while savings < 150:
    savings = savings + 20
    months = months + 1

print("reached", savings, "after", months, "months")

Step by step

  1. Start with 100 saved.
  2. months is created with the value 0.
  3. Check the condition: 100 < 150 is True, so run the body.
  4. Save 20 more: 120.
  5. One month gone.
  6. Python checks savings < 150 to decide whether the loop keeps going.
  7. savings changes from 120 to 140.
  8. months changes from 1 to 2.
  9. 140 < 150: still True, one more round.
  10. Now 160.
  11. months changes from 2 to 3.
  12. 160 < 150 is False: the loop ends and Python carries on after it.
  13. Three rounds took savings from 100 to 160. The loop did not know in advance how many rounds it would need; the condition decided.