Asking the user for input until they give a valid response
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Repeatedly prompting the user for input until they provide a valid response is a fundamental pattern in interactive programs. In Python, this is typically done with a while True loop that uses break when the input passes validation, or a while loop with a condition that becomes True once valid input is received. The key is to validate the input inside the loop, display clear error messages, and exit only when the response meets all criteria.
Basic Pattern: while True with break
The while True loop runs indefinitely until break is called. This pattern is clean because there is only one exit point — the break statement after validation succeeds.
Pattern: while with Sentinel Value
This variation uses None as a sentinel. The loop continues while age remains None, and only assigns a value when input is valid.
Validating Numeric Input
Using try/except around int() handles non-numeric input gracefully. The continue statement skips back to the top of the loop on validation failure.
Validating String Input (Menu Selection)
Validating with Regular Expressions
Limiting Retries
Validating Multiple Fields
Yes/No Confirmation Pattern
Common Pitfalls
- Forgetting to handle
ValueErrorfor numeric conversion: Callingint(input(...))withouttry/exceptcrashes the program when the user enters non-numeric text. Always wrap conversions in a try/except block. - Using
input()return value without.strip(): Trailing whitespace or newlines from copy-pasted input can cause validation to fail unexpectedly. Call.strip()on user input before validating. - Not normalizing case for string comparisons: Checking
choice == "Yes"fails when the user types"yes"or"YES". Use.lower()or.casefold()before comparing against lowercase options. - Infinite loop without clear error messages: If the loop only re-prompts without explaining what went wrong, users cannot correct their input. Always print a specific error message before the next iteration.
- Validating only format, not semantics: An input like
"2024-02-30"passes a regex date format check but is not a valid date. Use domain-specific validation (likedatetime.strptime) in addition to format checks.
Summary
- Use
while Truewithbreakfor the cleanest input validation loop pattern - Wrap numeric conversions in
try/except ValueErrorto handle non-numeric input - Create reusable validation functions with configurable constraints (min/max, regex, allowed values)
- Always call
.strip()and normalize case before comparing string input - Limit retries with a
forloop when unlimited attempts are undesirable - Print specific error messages so users know how to correct their input
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.