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.
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:
answer = input("Type 'quit' to stop: ")
if answer == "quit":
break
print(f"You typed: {answer}")
| If you know how many times you'll iterate… | use for |
|---|---|
| If you keep going until a condition flips… | use while |
while CONDITION: runs until the condition is false.while True: ... break is the Pythonic "until" pattern.Start at 1. Keep doubling until you exceed 1,000,000. Print how many doublings it took.