while Loops

Repeat as long as something stays true

Beginner 9 min

In this lesson

A while loop repeats as long as a condition is true. Use it when you don’t know in advance how many times you’ll loop — you just keep going until something changes.

Explain it like I’m 5

‘Keep doing this while the answer is yes.’ Python checks the question before every round and stops the moment the answer becomes no.

Condition first, then body

A while loop checks its condition before each pass. If the condition is true, the indented body runs, then Python rechecks the condition and repeats. As soon as the condition is false, the loop ends and execution continues below it. If the condition is false on the very first check, the body never runs at all.

Example
balance = 100
withdrawal = 30

while balance >= withdrawal:
    balance = balance - withdrawal
    print("Withdrew 30, balance now", balance)

print("Not enough for another withdrawal. Left:", balance)
Output
Withdrew 30, balance now 70
Withdrew 30, balance now 40
Withdrew 30, balance now 10
Not enough for another withdrawal. Left: 10
Loop while there's still enough money to withdraw.

Something must change inside the loop

The critical rule: something inside the loop must eventually make the condition false, or the loop runs forever — an infinite loop. Usually that means updating a counter or a flag each pass. Always ask: ‘what makes this loop stop?’ before you run it.

This loop should print 5, 4, 3, 2, 1 then 'Liftoff!' — but it's missing the line that changes n. Add it so the loop ends.

n = 5
while n > 0:
    print(n)
print("Liftoff!")

break and continue with while

break exits immediately, even if the condition is still true — handy for ‘loop forever until I find/receive X’. continue jumps back to the condition check, skipping the rest of the current pass. A common pattern is while True: with a break inside when you’re done.

Example
total = 0
while True:
    total += 10
    print("total is now", total)
    if total >= 30:
        break
print("Reached the goal.")
Output
total is now 10
total is now 20
total is now 30
Reached the goal.
while True loops forever until break stops it.

The 'loop until valid' pattern

while shines for retrying until input is acceptable: keep prompting until the user types a valid value. Because you can’t know how many wrong tries they’ll make, a count-based for loop won’t fit — the condition (‘not valid yet’) is what drives it.

Example
# Stand-ins for what a user might type, in order:
typed = ["", "   ", "Ada"]
i = 0
name = typed[i].strip()
while not name:
    i += 1
    name = typed[i].strip()
print("Welcome,", name)
Output
Welcome, Ada
Keep going until a non-empty value arrives.

Flags and sentinel values

Two patterns make while loops read clearly when a simple counter won’t do. A flag is a boolean that records ‘keep going’ or ‘stop’: running = Truewhile running:, and you set it to False when you’re done. A sentinel is a special value that means ‘stop’ — like looping over input until the user types quit.

Both give the loop a readable, intention-revealing stop condition instead of a magic number.

Example
# Stand-in for what a user might type, in order:
commands = ["add", "add", "quit", "add"]
i = 0
running = True

while running:
    command = commands[i]
    if command == "quit":
        running = False
    else:
        print("Running:", command)
        i += 1

print("Stopped.")
Output
Running: add
Running: add
Stopped.
A sentinel value ("quit") flips the flag that ends the loop.

Common mistake: Forgetting to update the loop variable (infinite loop)

Why it happens:

If the condition never becomes false because nothing inside the loop changes it, the loop runs forever.

How to fix it:

Make sure each pass moves you toward the stop condition — decrement a counter, set a flag, or break on a clear event.

n = 5
while n > 0:
    print(n)
    n -= 1  # this line is what ends the loop

When does a while loop stop?

What causes an infinite loop?

Mini exercise (medium)

Start with total = 0 and a counter n = 1. Using a while loop, add n to total, then increase n by 1, until total first exceeds 50. Print how many numbers it took.

Do it here. Finish the code below and press Run to try your answer right in the browser — no setup needed.

total = 0
n = 1
count = 0
# TODO: while total <= 50, add n to total, then grow n by 1 and add 1 to count each time n grows.
print(count)

What to learn next

You learned when to choose while over for, how the condition and body work together, how to avoid infinite loops, and the “loop until valid” pattern. You wrote a while loop that kept adding numbers until the running total passed 50.

You’ve been looping over collections; now it’s time to study the most important one closely. Lists covers creating, indexing, and slicing them, adding and removing items, the common methods, and what it means for a list to be mutable. When you’re ready, continue to the next lesson.