while loop
A while loop repeats a block of code as long as its condition stays true, for when you do not know how many rounds you need.
while condition:
# code that runs while condition is true
else:
# optional: runs if the loop did not breakA while loop checks its condition, runs the indented block if the condition is true, then checks again. It keeps going until the condition turns false.
Use it when the number of rounds depends on what happens inside the loop: asking until the user types a valid answer, halving a number until it is small, or reading until the data runs out. When you already have a collection to walk through, for loop is simpler.
Something in the loop must change the condition, or the loop never ends. A common pattern is while True: with a break statement inside to leave when you are done.
Examples
1Count up
n = 1
while n <= 5:
print("Round", n)
n += 1Round 1 Round 2 Round 3 Round 4 Round 5
n += 1 is what eventually makes n <= 5 false. Without it the loop would never stop.
2Savings goal: how many months?
You do not know the number of rounds in advance, so while is the natural fit.
balance = 0
months = 0
while balance < 1000:
balance += 150
months += 1
print(months, "months, balance", balance)7 months, balance 1050
3Halve until it is small enough
Shrinking a photo by half each time until it is under 500 KB: the loop decides for itself when to stop.
size_kb = 4800
rounds = 0
while size_kb > 500:
size_kb = size_kb / 2
rounds += 1
print("Round", rounds, "->", size_kb, "KB")Round 1 -> 2400.0 KB Round 2 -> 1200.0 KB Round 3 -> 600.0 KB Round 4 -> 300.0 KB
4while True with break
stock = [3, 8, 0, 5]
i = 0
while True:
if stock[i] == 0:
print("Shelf", i, "is empty")
break
i += 1Shelf 2 is empty
5Take items off a list until it is empty
tasks = ["wash", "dry", "fold"]
while tasks:
task = tasks.pop(0)
print("Doing:", task)
print("All done")Doing: wash Doing: dry Doing: fold All done
An empty list counts as false, so the loop stops when nothing is left.
Common mistakes
Forgetting to change the condition
If nothing inside the loop changes the variables in the condition, the loop runs forever. Make sure every round moves you closer to the end, for example with n += 1.
Using while to walk through a list by index
A counter plus while i < len(items): works but is easy to get wrong. A for loop does the same with less code.
names = ["Ada", "Ben", "Chen"]
i = 0
while i < len(names):
print(names[i])
i += 1
for name in names:
print(name)Ada Ben Chen Ada Ben Chen
Questions people ask
How do I stop an infinite loop?
In a terminal, press Ctrl+C. In your code, use break statement or make sure the condition can become false.
Does Python have a do-while loop?
No. Write while True:, put the body first and end it with if not condition: break. The body then always runs at least once.
What does while ... else do?
The else block runs when the condition becomes false. It is skipped if the loop ends with break.
for or while: which should I use?
Use for when you loop over a collection or a known range. Use while when you stop because of something that happens inside the loop.