Lesson 11 · Beginner · 19 min

Python while Loops

Repeat work until a condition changes, and know when to stop.

while conditionscountersbreak and continue

The bean hopper holds two hundred shots, and the queue does not care when it empties. A while loop can watch the level, but nothing else will update it. What condition ends the shift?

A while loop keeps running as long as its condition is true. It is the right tool when you do not know the number of repetitions in advance. The trade-off is that you must update the condition yourself, or the loop will never end. You will also use a loop invariant, bound retries, and drain a work queue.

A condition controls the loop

Before each iteration, Python checks the condition. If it is true, the body runs; if it is false, the loop stops. A counter that changes inside the body is the usual way to make the condition become false.

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

A countdown

break and continue

break leaves the loop immediately. continue skips the rest of the current iteration and goes back to the condition. Use both sparingly: too many exits make a loop harder to reason about.

n = 0
while n < 6:
    n += 1
    if n == 2:
        continue
    if n == 5:
        break
    print(n)

Skipping and stopping

A while loop over a sequence

You can use an index with while when you need manual control. Update the index at the end of every iteration. A for loop is usually clearer when you simply want every item.

orders = ["latte", "tea", "mocha"]
i = 0
while i < len(orders):
    print(orders[i])
    i += 1

Manual iteration

A loop invariant explains the total

Before each pass, total is the sum of the first i prices. The body adds one price and increments i, so the invariant is true again at the top. State that sentence before writing the loop; if you cannot, the loop probably needs a different shape.

prices = [4.5, 3.0, 2.5]
total = 0
i = 0
while i < len(prices):
    total += prices[i]
    i += 1
print(total)
print("processed", i, "of", len(prices))

An invariant makes the loop auditable

Give retries a budget

A validation loop needs a limit as well as a success path. Track attempts separately from the value; stop on success or when the budget is exhausted. Print the reason the loop stopped so a failure is visible instead of silent.

raw_values = ["many", "3", "5"]
attempts = 0
value = None
while attempts < len(raw_values):
    raw = raw_values[attempts]
    attempts += 1
    try:
        value = int(raw)
        break
    except ValueError:
        print("retry after", raw)
print("value", value, "attempts", attempts)

Stop on success or when attempts run out

Drain a queue one item at a time

A while loop fits work that shrinks. pop() removes one item, the list gets shorter, and the empty list is false. Do not append to a list while a for loop is walking it; remove work explicitly instead.

queue = ["latte", "tea", "mocha"]
served = []
while queue:
    order = queue.pop()
    served.append(order)
    print("serving", order)
print("served", served)

One removal per pass, empty ends the loop

Key points

  • while checks its condition before every iteration.
  • The loop body must move the condition toward false.
  • break exits the loop; continue skips to the next iteration.
  • Prefer for when you already have a collection to walk through.
  • A loop invariant names what stays true; one update per pass keeps it true.

Common mistakes

  • Forgetting to update the counter, which creates an infinite loop.
  • Using = instead of == in the condition.
  • Putting the counter update outside the loop body.
  • Updating the total but not the index, so the loop never reaches its end.
Your turn

Use a while loop to add the numbers 1 through 5, then print the total.

Try it yourself

Change the values, predict the output, then run the code. The Python runtime is downloaded the first time you press Run, so the first run can take a few seconds.

In-browser PythonRuns locally · no account
First run downloads Pyodide from a CDN. Use Run code after editing.

Practice this lesson

12 questions with immediate explanations.

See all 12 answersStart practice
← JSON datatuples and sets →