Emulate a do-while loop in Python using a while True: loop with a conditional if not condition: break statement at the end of the loop body—ensuring the body executes at least once before evaluating the exit condition, or using the walrus operator (:=) inside while (val := func()) != sentinel: when the loop simply polls a function until a sentinel value appears.
Basic Example
# 1. Standard Pythonic idiom: `while True:` with a trailing `if ...: break`
attempts = 0
while True:
attempts += 1
print(f"Attempt #{attempts}")
# Exit condition checked at the END of the iteration (guaranteed >= 1 run)
if attempts >= 3:
break
# 2. User-input / menu prompt validation (classic do-while use case)
while True:
choice = input("Enter 'y' or 'n': ").strip().lower()
if choice in {"y", "n"}:
break
print("Invalid input, try again.")
# 3. Walrus operator (`:=`) idiom when polling an expression until a sentinel value
import random
while (roll := random.randint(1, 6)) != 6:
print(f"Rolled {roll}, rolling again...")
print("Rolled a 6!")
Key Details & Edge Cases
- Why Python has no native
do ... whilekeyword (PEP 315): Guido van Rossum rejected PEP 315 becausewhile True: ... if cond: breakavoids awkward indentation rules (where a trailingwhile cond:would sit at the same indentation level as the loop body) and generalizes cleanly to “loop-and-a-half” patterns where the exit check belongs in the middle of the loop body rather than strictly at the top or bottom. - Keep exit conditions positive and readable (
if done: break): In C/Javado { ... } while (keep_going);, you write the continuation condition; in Python’sif exit_cond: break, you write the termination condition (if attempts >= 3: break). Double-check that you invert the condition accurately when translating from C-style loops. continuestatement gotcha insidewhile True: ... if not cond: break:- In a native C/Java
do-whileloop, executingcontinuejumps straight to the bottomwhile (cond)check. - In Python’s
while True:emulation, executingcontinuejumps back to the top ofwhile True:, skipping the trailingif ...: breakcheck at the bottom—which can cause an infinite loop if the state variable isn’t updated beforecontinue. - If your loop uses
continueand must still evaluate the exit condition at the end of every pass, wrap the body in a single-passfor _ in (0,):block or structure the check beforecontinue:while True: for _ in (0,): # `continue` inside here jumps straight to the exit check below data = fetch_next() if data is None: continue process(data) if should_stop(): break
- In a native C/Java
- Caveat with the walrus operator (
while (x := expr) != sentinel:): Notice thatwhile (roll := random.randint(1, 6)) != 6:evaluatesexprat least once, but skips the loop body on the iteration whereroll == 6. Usewhile True: ... if roll == 6: breakinstead whenever the loop body itself must execute on that final matching iteration too.
Comparison of do-while Emulation Patterns in Python
| Pattern | Syntax | Executes Body >= 1 Time? | Safe with continue? |
Best Used When |
|---|---|---|---|---|
while True: + trailing break |
while True: body(); if stop: break |
Yes (always runs at least once) | Needs care if continue skips break |
Standard post-test loops, input retries, and loop-and-a-half workflows. |
Walrus Operator (:=) in while |
while (x := fn()) != stop: body(x) |
Evaluates fn() >= 1 time (body runs 0+ times) |
Yes | Reading chunks (while (chunk := f.read(4096)):) or polling until a sentinel value. |
Priming Read Before while |
x = fn(); while cond(x): body(x); x = fn() |
Evaluates fn() >= 1 time |
Yes | Avoiding while True: when fn() is a short single call and continue is used heavily. |
while True: + for _ in (0,): guard |
while True: for _ in (0,): ...; if stop: break |
Yes | Yes (continue hits exit check) |
Complex loops requiring both guaranteed first execution and internal continue jumps. |
You must log in or register to comment.
