While Loop — Python

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…

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

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

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")

⚠️ Loops that won't stop, or stop in the wrong place

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.

What you will learn