for needs a sequence that is already known: three orders, or range(5). But how many more cups of coffee can Mr. Darto sell today? He doesn't know the number. He only has one habit: before he serves the next customer, he looks at the coffee jar. If there is still coffee in it, he serves. If it is empty, he stops selling.
Mr. Darto's habit is to repeat something under a condition: repeat as long as the jar still has coffee. In Python, you repeat under a condition with a while loop: one block of code repeats as long as a condition is True. Python checks the condition before every pass. As soon as the condition is False, the loop stops. At the stall, the condition is "the jar still has coffee", and one pass is serving one customer. The coffee in the jar goes down on every pass, so at some point the jar is empty.
How while works
This is Mr. Darto's habit as code. stock is the coffee in the jar, 3 cups at the start:
stock = 3
while stock > 0:
stock -= 1
print(f"Sold 1 coffee, {stock} left")
print("Stall closed")
The output:
Sold 1 coffee, 2 left
Sold 1 coffee, 1 left
Sold 1 coffee, 0 left
Stall closed
This table shows each check of the condition:
| Check | stock |
stock > 0 |
What happens |
|---|---|---|---|
| 1 | 3 | True |
stock becomes 2, prints 2 left |
| 2 | 2 | True |
stock becomes 1, prints 1 left |
| 3 | 1 | True |
stock becomes 0, prints 0 left |
| 4 | 0 | False |
the loop ends, on to Stall closed |
while stock > 0:checks the condition,stock > 0. If it isTrue, the loop body (the indented lines below it) runs once. Then Python goes back to thewhileline and checks again.stock -= 1is short forstock = stock - 1. Because of this line, the stock keeps going down until it is 0, and then the condition isFalse.- The condition is checked 4 times, but the body runs only 3 times. The fourth check gives
False, so the loop stops. - If the condition is already
Falseat the start (stock = 0), the body does not run at all.
for or while? Use for when the sequence is known from the start: each item of a list, or range(5). Use while when you repeat until something changes: the stock runs out, the money reaches a target, or the user's answer is correct.
Infinite loop: forgetting to change the condition
If you delete the line stock -= 1, stock stays 3 forever. 3 > 0 is always True, so the loop never stops. This is called an infinite loop (a loop with no end). The terminal keeps printing the same line until you stop it with Ctrl+C (the Ctrl and C keys together):
Sold 1 coffee, 3 left
Sold 1 coffee, 3 left
^CTraceback (most recent call last):
File "/home/darto/stall.py", line 3, in <module>
print(f"Sold 1 coffee, {stock} left")
~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyboardInterrupt
^Cis the Ctrl+C you pressed. Python stops at the line that was running at that moment, then writesKeyboardInterrupt(stopped from the keyboard).- Every
whileneeds a line in its loop body that makes the conditionFalseat some point, or abreak(explained next).
break: leaving halfway
break stops the loop right away, without waiting for the condition to become False. For example, Mr. Darto wants to stop selling as soon as the stock is down to 1. He does not sell the cup he took on that pass; he keeps it for himself:
stock = 3
while stock > 0:
stock -= 1
if stock == 1:
break
print(f"Sold 1 coffee, {stock} left")
print("Stall closed")
The output:
Sold 1 coffee, 2 left
Stall closed
On the second pass stock becomes 1, so break runs. Python jumps directly to the line after the loop. The print inside the loop does not run, so 1 left is never printed.
One pattern is used a lot: while True: with a break inside it. The condition is True itself, so it is never False. The loop only stops through break. For example, Mr. Darto saves $150 a day until he has at least $500:
money = 0
days = 0
while True:
days += 1
money += 150
if money >= 500:
break
print(days, money) # 4 600
The loop stops on day 4, when the money is $600: past the target.
continue: skipping to the next pass
continue skips the rest of the loop body, but only for the current pass. Python then goes back to check the condition, and the loop keeps running. This is the previous example, with break replaced by continue:
stock = 3
while stock > 0:
stock -= 1
if stock == 1:
continue
print(f"Sold 1 coffee, {stock} left")
print("Stall closed")
The output:
Sold 1 coffee, 2 left
Sold 1 coffee, 0 left
Stall closed
When stock is 1, continue runs and the print is skipped. The next pass still runs, until the stock is 0. The difference from break: break ends the loop, continue only ends one pass.
else on a loop
Python has a feature that few other languages have: an else after a loop. The else block runs when the loop ends normally, which means its condition became False. If a break stops the loop, the else is skipped. For example:
stock = 3
while stock > 0:
stock -= 1
print(f"Sold 1 coffee, {stock} left")
else:
print("Out of coffee")
print("Stall closed")
- This program prints three
Soldlines, thenOut of coffee, thenStall closed. - If you add
if stock == 1: breakinside the loop,Out of coffeeis no longer printed. The loop stopped because ofbreak, not because its condition becameFalse. - If the first line is
stock = 0, the body never runs, but theelsestill runs. The reason: the loop ended because its condition isFalse, not because of abreak. - A
forcan have anelsetoo, with the same rule: theelseruns when the loop reaches the last item without abreak. This is useful for a search: youbreakwhen the item is found, so theelseonly runs when it is not found.
⚠️ Loops that won't stop, or stop in the wrong place
- Forgetting to change the condition's variable. Without
stock -= 1the loop runs forever. Stop it with Ctrl+C, then add the line that changes the condition. continuebefore the counter changes. If the counter line (stock -= 1) is belowcontinue, that line is skipped too. The stock stops going down, so the loop never stops.- Picking
>or>=wrongly.while stock >= 0:is stillTruewhen the stock is 0. So the loop sells 4 times, and the last pass prints-1 left. - Expecting
elseto run afterbreak.elseonly runs when the loop ends because its condition isFalse.
TL;DR: while condition: checks its condition before every pass, and repeats the loop body while the condition is True. The body must change something (for example stock -= 1) so that the condition becomes False at some point. If nothing changes, you get an infinite loop (a loop with no end), which only stops with Ctrl+C (KeyboardInterrupt). break ends the loop right away. continue only skips the rest of the current pass. An else after the loop runs when the loop ends normally (its condition is False), and is skipped when the loop stops because of break. Use for for a known sequence, and while to repeat until something changes.
⚡ Repeat while it's True
Write:
stock = 3
while stock > 0:
stock -= 1
print(f"Sold 1 coffee, {stock} left")
print("Stall closed")
Meaning: Before every pass, Python checks the condition (the test after while): stock > 0. While the condition is True, the indented lines below while run again. stock -= 1 (subtract 1 from the stock) makes the condition False at some point, and then the loop stops. Use while when you repeat until something changes.
⚡ A condition that never changes
Guess first: the line stock -= 1 is deleted from the code above. What happens?
The loop never stops. stock stays 3 and 3 > 0 is always True, so the terminal keeps printing the same line until you stop it with Ctrl+C.
Meaning: A loop that never stops is called an infinite loop. Every while needs a line inside it that makes the condition False at some point, or a break (next step).
⚡ break and continue
Meaning: break ends the loop right away, without waiting for the condition to be False. continue only skips the rest of the current pass, then the loop goes on.
⚡ else after a loop
Write:
stock = 3
while stock > 0:
stock -= 1
print(f"Sold 1 coffee, {stock} left")
else:
print("Out of coffee")
print("Stall closed")
Guess first: if if stock == 1: break is added inside the loop, is Out of coffee still printed?
No. An else after a loop only runs when the loop ends because its condition became False. Here the loop stopped because of break, so the else is skipped.
Meaning: An else after a loop runs when the loop ends normally: its condition became False, and no break stopped it.