HomeCourseModule 04 › while loops — repeat until done

while loops — repeat until done

Module 04 · Control Flow6 min readBeginner

What you'll learn

  • Write a while loop with a clean exit condition
  • Use break to leave a loop early
  • Avoid accidental infinite loops

The shape of a while loop

balance = 100
months = 0
while balance < 200:
    balance = balance * 1.05   # 5% per month
    months += 1
print(f"Took {months} months")   # 15

"Keep going while the condition is true." When the condition flips false, the loop exits.

The classic infinite loop

x = 0
while x < 10:
    print(x)
    # forgot to change x — runs forever

If you ever fire one off by accident, hit the ⬛ stop button in Jupyter, or Ctrl+C in the terminal.

while True + break — the "until" pattern

while True:
    answer = input("Type 'quit' to stop: ")
    if answer == "quit":
        break
    print(f"You typed: {answer}")

When to use while vs for

If you know how many times you'll iterate…use for
If you keep going until a condition flips…use while

Key takeaways

  • while CONDITION: runs until the condition is false.
  • Change the variable inside the loop or you'll spin forever.
  • while True: ... break is the Pythonic "until" pattern.

Doubling game

Start at 1. Keep doubling until you exceed 1,000,000. Print how many doublings it took.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.