Command Palette

Search for a command to run...

Hectal
PHASE 2Beginner ~27 min· topic 3 of 9

Topic 2.3

Repeating with while

In one line

A while loop repeats a block of code for as long as its condition stays True. You must make something inside the loop change the condition, or the loop never ends.

Think of it like this

Filling a glass of water. "While the glass is not full, keep pouring." You look at the glass, decide, pour a little, and look again. You do not count the pours in advance; you keep checking the condition. A while loop is exactly this: check, do the work, check again.

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

Loop
Code that repeats.
Iteration
One pass through the body of a loop.
Counter
A variable that counts passes or steps, such as count or i.
Infinite loop
A loop that never ends because its condition never becomes False.
Sentinel
A special value that signals "stop", such as -1 at the end of a list of scores.
break
A statement that leaves the nearest loop immediately (Topic 2.5).
Ctrl+C
The keys that interrupt a running program in a terminal. Python raises KeyboardInterrupt.
List (preview)
Several values kept in order inside square brackets, such as [4, 8, 15]. Phase 4 teaches lists properly; here we only read from them.

Step by step

01A countdown: the three parts of a counter loop

Set the counter, test it, change it. Python prints 3, 2, 1, then at count = 0 the test 0 > 0 is False and the loop ends. "Liftoff" is outside the block, so it runs once, at the end.

main.pywhole filepython
count = 3                   # 1. set
while count > 0:            # 2. test
    print("Countdown:", count)
    count = count - 1       # 3. change
print("Liftoff")
A countdown: the three parts of a counter loopdiagram
Rendering diagram…

02Accumulating a total

A very common use: keep a running total in one variable, and a counter in another. Each pass adds the current number to the total and moves the counter on. After the loop, total holds 1 + 2 + 3 + 4 + 5 = 15.

main.pywhole filepython
total = 0
n = 1
while n <= 5:
    total += n
    n += 1
print("Sum of 1..5:", total)

03When you don't know how many times

How many years until 100 grows past 150 at 10% a year? You cannot say without trying, so a while loop fits: keep going until the goal is reached. The answer is 5 years (balance 161.05). balance * 1.1 adds 10% each year, and round(balance, 2) shows the number with 2 decimal places.

main.pywhole filepython
balance = 100
years = 0
while balance < 150:
    balance = balance * 1.1
    years += 1
print("Years:", years, "Balance:", round(balance, 2))

04The infinite loop

This loop never changes count, so count < 3 is always True. It prints 0 forever. Whenever you write a while, find the line that makes the condition eventually False.

Do not run this one: it is shown to teach you what to look for.

main.pywhole filepython
count = 0
while count < 3:
    print(count)
    # forgot: count += 1     <- nothing changes the condition

05A sentinel loop

The list is read from the front, one item at a time, with index pointing at the current item (numbers[0] is the first). The loop stops when it meets -1, the sentinel, so 99 is never added. The result is 4 + 8 + 15 = 27.

main.pywhole filepython
numbers = [4, 8, 15, -1, 99]
index = 0
total = 0
while numbers[index] != -1:
    total += numbers[index]
    index += 1
print("Sum before -1:", total)

06while True with break

while True: means "repeat forever", and the break is the only way out. Here the test happens in the middle of the block (after taking a guess), which is why this shape is clearer than putting a condition on the while line. The guesses come from a fixed list so the example is repeatable.

main.pywhole filepython
guesses = [3, 9, 5, 7]
target = 5
attempts = 0
while True:
    guess = guesses[attempts]
    attempts += 1
    if guess == target:
        print("Found", target, "after", attempts, "tries")
        break
    print("Wrong:", guess)

07Zero iterations, and the float trap

If the condition is False the first time, the block never runs and nothing is printed. And comparing floats with != is dangerous because of rounding (Topic 1.3).

main.pywhole filepython
balance = 200
while balance < 150:
    print("never printed")        # zero iterations

x = 0.0
# while x != 1.0:                 # never ends: 0.1 added 10 times is
#     x += 0.1                    # 0.9999999999999999, not 1.0
while x < 1.0:
    x += 0.1                      # use < instead of !=

Try it yourself

  1. 1

    Count up

    Change the countdown to count up from 1 to 5. You need to change the starting value, the condition and the update. Run it and check that it prints 1 to 5 and then stops.

  2. 2

    Double until big

    Start value = 1 and steps = 0. While value is at most 1000, double it and add one to steps. Predict the final value and steps before you run (powers of two: 1, 2, 4, 8 ...).

  3. 3

    Spot the infinite loop (safely)

    Read the third code block and write down the one line that would fix it. Then add that line to a copy and run the fixed version.

Code & diagrams

Counters, totals and a growing balance New tab

Change the start of the countdown to 5, and change the target balance to 200. Predict the number of years first.

Sign in to run this example in your browser.

Expected output

Countdown: 3
Countdown: 2
Countdown: 1
Liftoff
Sum of 1..5: 15
Years: 5 Balance: 161.05
Sentinel loop and while True with break New tab

Move the 5 later in the guesses list and see how the number of tries changes. What happens if the target is not in the list at all? (The program will stop with an error: why?)

Sign in to run this example in your browser.

Expected output

Sum before -1: 27
Wrong: 3
Wrong: 9
Found 5 after 3 tries
An infinite loop (do not run)python

The counter never changes, so the condition is always True. Never put a loop like this in a runnable example: it would print forever.

count = 0
while count < 3:
    print(count)
    # count += 1 is missing

Output

0
0
0
... (forever, until you press Ctrl+C)

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Forget to update the counter

Delete the line count += 1 from a counting loop and run it in a terminal.

main.pywhole filepython
count = 0
while count < 3:
    print(count)
terminal
$ python main.py
── what you'll see ──
0
0
0
0
... (it never stops; press Ctrl+C)
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(count)
KeyboardInterrupt

Myth vs fact

Myth

A while loop checks its condition continuously, so it stops the moment the condition becomes False.

Fact

The condition is tested only at the top, before each iteration. If it becomes False in the middle of the block, the rest of that block still runs.

Myth

while True is bad style.

Fact

It is the normal, clear way to write "repeat until a break" when the exit test happens in the middle of the block. It is bad only when there is no break or return that can end it.

Myth

Use while loops for everything you repeat.

Fact

When you have a known list or count, for (Topic 2.4) is shorter and cannot forget the counter update. Use while when the number of repeats is not known in advance.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    Programs that run forever on purpose (servers, bots, a game loop) are written as while True: with a clean way out, such as a shutdown flag or an exception handler. The loop body does one unit of work and returns to waiting.

  • ▸

    A retry loop is a while loop: attempts = 0, loop while attempts < 3, try the request, break on success. Real code adds a delay that grows between attempts (exponential backoff, Topic 15.2), which is how AI API clients cope with rate limits.

  • ▸

    Every loop should have an upper bound you can name, even if only a maximum number of attempts. An unbounded loop that waits for an outside system (a network, a file) is a classic cause of hung jobs in production.

  • ▸

    The while condition is re-evaluated on every pass, so keep it cheap and free of side effects. Calling a function in the condition (while compute() > 0) runs it every iteration, and the walrus operator (Topic 2.9) can store its result.

  • ▸

    Python has no do ... while loop (run the body once, then test). The idiom is while True: with the work first and if not condition: break at the end. Interviewers like this question because it checks that you know the loop forms rather than the syntax of one language.

  • ▸

    Float counters drift: x = 0.0 with while x < 1.0: x += 0.1 runs 11 times, not 10, because ten additions give 0.9999999999999999, which is still below 1.0. Count with an integer and compute the float from it (x = step * 0.1), or use math.isclose (Topic 1.3). For a bounded retry, for attempt in range(3): with a loop else for the "all attempts failed" case is safer than a hand-made while counter.

Remember this

  1. 1

    The shape is while condition: followed by an indented block, just like if. The difference is what happens at the end of the block. After an if block Python moves on. After a while block Python jumps back to the condition and tests it again. One pass through the block is called an iteration. When the condition is False at the check, the loop is over and Python continues with the first line after the block.

  2. 2

    The most common pattern is a counter: set it before the loop, test it in the condition, and change it inside the block. count = 3, while count > 0:, count = count - 1. Three parts, and if you forget the third, the condition never changes. You can write the update as count -= 1 (Topic 1.7).

  3. 3

    A loop whose condition never becomes False is an infinite loop. It is a bug, not an error: Python does not complain, the program just never finishes (or prints forever). The usual causes are forgetting the update, updating the wrong variable, or a condition that can never be False. When you read a while loop, ask: "what inside the block changes the thing the condition looks at?" If nothing does, it is an infinite loop. In a terminal press Ctrl+C to stop it; the Run button on this page stops a program that runs too long.

  4. 4

    The condition is tested before the first iteration, so a while loop can run zero times. while balance < 150: does nothing at all if the balance is already 150 or more. This is useful: "do it as many times as needed, including none".

  5. 5

    A sentinel loop repeats until a special value (the sentinel) appears, such as -1 meaning "end of data". A related pattern is while True: (an intentional infinite loop) with a break inside that leaves the loop when the goal is reached. It is the clearest way to write "keep trying until it works" when the test comes in the middle of the block (Topic 2.5 covers break).

  6. 6

    Use while when you do not know in advance how many repeats you need (read until the data ends, retry until success, grow until a limit). When you have a known list of items or a known count, a for loop (Topic 2.4) is shorter and safer, because it cannot forget the counter update. Be careful with decimal numbers (floats, Topic 1.3). while x != 1.0 can run forever, because 0.1 added ten times is not exactly 1.0. Use < or <= instead.

Explain it without notes

01

How does a while loop work, step by step?

02

What is an infinite loop and how do you spot one while reading code?

03

What is a sentinel loop? Give an example.

04

When would you choose while over for?

Practice

01

Use a while loop to print the numbers 1 to 5, one per line.

02

Start with value = 1 and steps = 0. Double value while it is at most 1000, counting the steps. Print value and steps.

03

A list data = [5, 10, 0, 7] ends data at the first 0. Use a sentinel while loop to add up the numbers before the 0 and print Total: 15.

Trade-offs

  • ↔

    while vs for. while is flexible (any condition) but you must manage the counter yourself. for is safer when the items are known.

  • ↔

    Condition on the while line vs while True + break. A condition on the line is the simplest reading. while True is clearer when the exit test is in the middle of the work.

Done when you can

  • Done when you can write a counter loop with a start, a test and an update.

  • Done when you can point to the line that ends a loop, or find that none exists.

  • Done when you can write a sentinel loop and a while True loop with break.

  • Done when you can explain why a while loop can run zero times.

  • Done when you can say why != on floats is dangerous in a loop condition.