Home »
Python
Asking the user for input until a valid response in Python
Here, we are going to learn how to ask the user for input until they give a valid response in Python programming language?
Submitted by IncludeHelp, on April 25, 2020
Problem statement
We want to input age which should be greater than 18 and less than 51, gender which should be either "Male" or "Female". If the user inputs an invalid value, the program should ask again for the input.
Input until a valid response
To ask the user for input until a valid response, just take the input in an infinite loop (using while True) and when the value is valid, terminate the loop (using break keyword). To handle value errors while reading an integer value – use the try-except block and continue the program's execution (using continue keyword) to the loop to read it again.
Python program for asking the user for input until a valid response
# input age
while True:
try:
age = int(input("Enter age: "))
if age>18 and age<51:
print("Age entered successfully...")
break;
else:
print("Age should be >18 and <51...")
except ValueError:
print("Provide an integer value...")
continue
# input gender
while True:
try:
gender = input("Enter gender: ")
if gender == "Male" or gender == "Female":
print("Gender entered successfully...")
break;
else:
print("Gender should be either Male or Female")
except:
continue
# print age and gender
print("Age is:", age)
print("Gender is:", gender)
Output
Enter age: 12.5
Provide an integer value...
Enter age: Thirty Two
Provide an integer value...
Enter age: 78
Age should be >18 and <51...
Enter age: 32
Age entered successfully...
Enter gender: I am Male
Gender should be either Male or Female
Enter gender: Don't know
Gender should be either Male or Female
Enter gender: Male
Gender entered successfully...
Age is: 32
Gender is: Male
Python Tutorial