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*


PySaaS: The Pure Python SaaS Starter Kit

馃殌 Build a software business faster with pure Python: Link*

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