Python foundations

Python while Loops: Conditions, Counters, and Exits

Use a while loop when work ends as a condition changes. Set a clear exit, bound retry attempts, and avoid infinite loops.

A Python while loop repeats as long as its condition is true. Python checks the condition before the first pass and before every later pass. Choose while when the current state determines when you stop. A for loop fits when a sequence already tells you what to process.

balance = 12
withdrawals = 0

while balance >= 5:
    balance -= 5
    withdrawals += 1

assert balance == 2
assert withdrawals == 2

The condition needs a balance of at least five. The body reduces the balance each time. Those two facts explain why the loop stops. Check both when a loop takes longer than you expected.

What prevents an infinite while loop?

Look for the value that changes on each pass. A cursor should move forward through the text, or a queue should lose an item as work finishes. If continue skips part of the body, check that it still leaves the loop able to move on.

A common bug is placing the only update after an early continue. When the skipped record is invalid, every pass sees the same record again. For a sequence of items, switch to a direct for traversal when appropriate. For an actual condition-driven loop, put the progress update where the next iteration always sees a new state.

Bound attempts independently of success

An operation might fail repeatedly for reasons outside your program. You can model an attempt budget separately from the success condition. This example uses local values so the result is predictable.

observations = iter(["pending", "pending", "ready"])
attempts = 0
ready = False

while attempts < 3 and not ready:
    attempts += 1
    ready = next(observations, None) == "ready"

assert ready
assert attempts == 3

The loop tries at most three times, even if every observation says "pending". If the actual operation can wait on an external service, give each call its own timeout. Three calls that never return still have no useful time limit.

Choose how an unbounded loop exits

while True can make sense when the stopping rule is easiest to judge after reading the next item. The body should contain a clear break, return, or other intended end. A boundary that closes the application is different from a sentinel meaning “no more records.” Treat the two cases according to the caller's expectations.

With a loop that reads text from a file, an empty return from readline() means end of file. A blank line typically still contains a newline and has not reached the end. Stripping the line before checking for an empty result can mix up those cases. For ordinary line-by-line reading, a direct loop over the file handles the end without a sentinel test.

Check zero iterations and the final pass

If a counter limit is 3 and you start at zero, counter < 3 produces three passes with values zero through two before you increment. counter <= 3 would allow a fourth. Write down whether the display label is a zero-based index or a one-based attempt number.

Test a starting condition that is already false, a condition that becomes false on the first pass, and a condition that reaches the final permitted pass. If the loop may stop in two different ways, such as success or exhaustion, test both and give the caller enough information to tell which one occurred.

Sources and further reading

Related reading

Browse Python foundations · Explore project tutorials

Search PythonProjects.org