Wrap input() inside a while True: loop that validates the entered value (using try ... except ValueError for type conversions or conditional checks for allowed values), executes break (or return inside a helper function) only when validation succeeds, and prints a clear correction message on failure before looping back.
Basic Example
# 1. Recommended: Reusable validation helper function using `while True` + `try/except`
def prompt_int(message: str, min_val: int, max_val: int) -> int:
while True:
raw = input(message).strip()
try:
value = int(raw)
except ValueError:
print(f"Invalid input '{raw}': please enter a whole number.")
continue
if min_val <= value <= max_val:
return value
print(f"Out of range: enter a number between {min_val} and {max_val}.")
age = prompt_int("Enter your age (1–120): ", min_val=1, max_val=120)
print(f"Accepted age: {age}")
# 2. Validating against a fixed set of allowed text choices (case-insensitive):
VALID_CHOICES = {"yes", "no", "y", "n"}
while True:
answer = input("Continue? [y/n]: ").strip().lower()
if answer in VALID_CHOICES:
break
print("Please enter 'y' or 'n'.")
Key Details & Edge Cases
- Always
.strip()user input before validating:- Users frequently press Space accidentally before or after typing (
" yes "or"42 "). Calling.strip()prevents false rejections on string comparisons and cleans whitespace before regex or rule checks.
- Users frequently press Space accidentally before or after typing (
- Avoid recursive self-calls (
return prompt_int(...)) for re-prompting:- Calling a prompt function recursively on invalid input (
except ValueError: return prompt_int(...)) works for a few retries, but exhausts Python’s call stack (RecursionError: maximum recursion depth exceededafter ~1,000 failed attempts) if an automated pipe or user repeatedly feeds invalid lines. Always use an iterativewhile True:loop instead.
- Calling a prompt function recursively on invalid input (
- Handle
EOFErrorandKeyboardInterruptcleanly so piped/aborted input doesn’t loop forever:- If stdin reaches End-of-File (
Ctrl+Don macOS/Linux,Ctrl+Z+ Enter on Windows, or an empty piped file),input()raisesEOFError. Catchexcept (EOFError, KeyboardInterrupt): raise SystemExit("\nInput cancelled.")so the loop terminates cleanly rather than crashing with a raw traceback.
- If stdin reaches End-of-File (
- Reject
nanandinfwhen validatingfloat()inputs:float("nan")andfloat("inf")succeed without raisingValueError. When validating numeric floats, combinefloat(raw)withmath.isfinite(value)(if not math.isfinite(value): ...) so"nan"and"inf"trigger re-prompting.
- Keep the
tryblock narrow (wrap ONLY the conversion, not downstream logic):- Place only
value = int(raw)insidetry ... except ValueError:; keeping subsequent business logic outsidetryguarantees you never accidentally swallow an unrelatedValueErrorraised by later code.
- Place only
Comparison of Input Validation Loop Patterns in Python
| Pattern | Prevents RecursionError? |
Separates Type Errors from Range/Rule Errors? | Reusable Across Multiple Prompts? | Best Used When |
|---|---|---|---|---|
while True: + try/except helper function (Recommended) |
Yes (iterative $O(1)$ stack) | Yes (distinct messages for format vs. bounds) | Yes (accepts custom bounds or validator callable) | Production CLI tools and multi-field user forms requiring clean, specific error feedback. |
Inline while True: + if ... in VALID_SET: break |
Yes | N/A (string membership check) | No (inline single prompt) | Quick menu selections, yes/no confirmations, or fixed keyword choices. |
Generic validator: Callable[[str], T] wrapper |
Yes | Yes (any parsing function raising ValueError triggers retry) |
Yes (works for int, float, date.fromisoformat, regex, etc.) |
Consolidating dates, emails, numbers, and custom formats behind a single prompt_valid(msg, parser) utility. |
Recursive retry (except ValueError: return ask()) |
No (crashes after ~1,000 bad inputs) | Yes | Yes | Not recommended—always prefer an iterative while True: loop. |
You must log in or register to comment.
