How to ask the user for input until they give a valid response in Python

A clean way to ask the user for input and catch invalid inputs.


How to ask the user for input until they give a valid response in Python. Here's one clean way:

  • use a while True loop
  • use input() to get the user input
  • use a try-except block to catch invalid inputs
  • use an else block to break if the input is valid
while True:
    try:
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue
    else:
        break

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*


Python Problem-Solving Bootcamp

🚀 Solve 42 programming puzzles over the course of 21 days: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏