Python while loop

PYTHON Published Updated 3 mins read By Leon Wei
Python while loop cover image

Quick summary

Summarize this blog with AI

A while loop tests its condition before every iteration. A correct loop needs both a reason to continue and a way to make progress toward stopping. Use a for loop for ordinary iteration over known items; use while when continuation depends on evolving state. These Python 3.12.14 fixtures are finite and make no network calls.

Check zero iterations and normal termination

def countdown(start):
    if type(start) is not int or start < 0:
        raise ValueError("start must be a nonnegative integer")
    remaining = start
    seen = []
    while remaining > 0:
        seen.append(remaining)
        remaining -= 1
    return seen

print(countdown(3))
print(countdown(0))
try:
    countdown(-1)
except ValueError as error:
    print(str(error))

Expected output:

[3, 2, 1]
[]
start must be a nonnegative integer

The progress measure is a nonnegative integer that decreases every iteration. The function rejects Boolean values as well as negative and noninteger values under its explicit contract. When the initial condition is false, the body is skipped entirely. A loop counter alone does not guarantee termination if an operation inside an iteration blocks forever.

Else means the loop ended without break

def locate(values, wanted):
    index = 0
    while index < len(values):
        if values[index] == wanted:
            break
        index += 1
    else:
        return None
    return index

print(locate([4, 7, 7], 7))
print(locate([4, 7], 9))
print(locate([], 9))

Expected output:

1
None
None

The else block runs when the while condition becomes false, including when it was false initially. It does not run after break. It also does not run if the loop exits through an exception or a function return. Continue skips the rest of the current body, so place required state updates where continue cannot accidentally bypass them.

Bound a polling loop and classify terminal outcomes

def wait_ready(read_state, max_attempts=3):
    if type(max_attempts) is not int or not 1 <= max_attempts <= 10:
        raise ValueError("max_attempts must be an integer from 1 to 10")
    attempts = 0
    while attempts < max_attempts:
        attempts += 1
        state = read_state()
        if state == "ready":
            return attempts
        if state == "failed":
            raise RuntimeError("operation failed")
        if state != "pending":
            raise ValueError("unexpected state")
    raise TimeoutError("attempt limit reached")

states = iter(["pending", "pending", "ready"])
print(wait_ready(lambda: next(states)))
for state in ["pending", "failed", "unknown"]:
    try:
        wait_ready(lambda: state)
    except (TimeoutError, RuntimeError, ValueError) as error:
        print(type(error).__name__, str(error))

Expected output:

3
TimeoutError attempt limit reached
RuntimeError operation failed
ValueError unexpected state

The first example succeeds on the final allowed attempt. The others distinguish exhaustion, an explicitly failed operation, and an unknown protocol state. Exceptions from read_state are allowed to propagate; silently treating every exception as pending would hide broken dependencies. The ten-attempt maximum is a teaching bound, not a universal service recommendation.

Attempts, elapsed time, and retries are different controls

A real remote poll needs per-request timeouts and a delay or backoff; a tight while loop can waste CPU and overload the service. A count limit is not a strict wall-clock deadline if each request can block. A deadline should use a monotonic clock, while cancellation still depends on the called operation. Polling a status endpoint is also different from retrying a state-changing action: retrying a purchase or job submission can duplicate effects unless the service supports an appropriate idempotency contract.

Before running a loop, state its invariant, progress measure, terminal states and resource limit. Test zero work, first-attempt success, final-attempt success, exhaustion, and an unexpected response. For interactive input, handle end-of-file explicitly instead of prompting forever. For an infinite event loop that is intentional, define a shutdown mechanism rather than assuming someone will kill the process.

References and next steps

While statement, break and continue, Monotonic clock.

Interview Prep

Begin Your SQL, Python, and R Journey

Master 230 interview-style coding questions and build the data skills needed for analyst, scientist, and engineering roles.

Related Articles

All Articles
Python exceptions cover image
python Apr 29, 2024

Python exceptions

Python exceptions: write robust code to handle errors, debug, and ensure programs reliable under various scenarios using try-except blocks, cust…