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 ... while keyword (PEP 315): Guido van Rossum rejected PEP 315 because while True: ... if cond: break avoids awkward indentation rules (where a trailing while 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/Java do { ... } while (keep_going);, you write the continuation condition; in Python’s if 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.
  • continue statement gotcha inside while True: ... if not cond: break:
    • In a native C/Java do-while loop, executing continue jumps straight to the bottom while (cond) check.
    • In Python’s while True: emulation, executing continue jumps back to the top of while True:, skipping the trailing if ...: break check at the bottom—which can cause an infinite loop if the state variable isn’t updated before continue.
    • If your loop uses continue and must still evaluate the exit condition at the end of every pass, wrap the body in a single-pass for _ in (0,): block or structure the check before continue:
      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
      
  • Caveat with the walrus operator (while (x := expr) != sentinel:): Notice that while (roll := random.randint(1, 6)) != 6: evaluates expr at least once, but skips the loop body on the iteration where roll == 6. Use while True: ... if roll == 6: break instead 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.