Focused practice · 8 min read

Python while Loop Exercises: 5 Patterns That Cover Most Problems

Most while-loop exercises are variations on five patterns. Once you can name the pattern, you can write the condition and the update without guessing.

Pattern 1: count down with a changing condition

Start with a value, test it, and change it inside the loop. The update is not optional: it is what makes the loop finish. Predict the output before running the example.

count = 3
while count > 0:
    print(count)
    count -= 1
print("Liftoff")

A predictable countdown

Pattern 2: stop on a sentinel

A sentinel is a special value that means stop. Check both the index and the value so the loop cannot run past the end of the sequence. This is the same idea as reading input until the user types quit.

commands = ["start", "check", "quit", "ignored"]
i = 0
while i < len(commands) and commands[i] != "quit":
    print(commands[i])
    i += 1

Stop before the sentinel

Pattern 3: break for an early exit

Use break when the stopping condition is easier to express inside the body than in the while header. Keep the exit close to the condition that triggers it, so a reader does not have to search for it.

prices = [3.0, 6.0, 4.5]
i = 0
while i < len(prices):
    if prices[i] > 5:
        print(prices[i])
        break
    i += 1

Find the first match

Pattern 4: accumulate until a limit

Create the accumulator before the loop, update it inside, and print it after. A limit in the condition prevents an accidental endless total. Trace the first two iterations by hand before trusting the result.

total = 0
n = 1
while total < 10:
    total += n
    n += 1
print(total)

A bounded accumulation

Debug an infinite loop

If a loop never ends, print the loop variable at the top of the body. Check that the update is inside the loop, that the condition uses the right operator, and that no branch skips the update. Then run again with a small input.

n = 0
while n < 3:
    print("top", n)
    n += 1
print("done", n)

Inspect the changing value

Your practice checklist

Common questions

When should I use while instead of for?

Use while when the number of repetitions is unknown, such as reading until a sentinel or retrying until a condition changes. Use for when you already have a collection or a known range.

Why does my while loop run forever?

The condition probably never becomes false. Check the counter update, the comparison operator, and whether a continue skips the update.

Is break bad practice?

No. break is fine when it makes an early exit clearer. Too many breaks in one loop usually mean the loop should be split into smaller steps.

Practice while loops

12 questions on conditions, counters, break, continue, and safe exits.

Open practice

Keep reading: