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

Question:

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.

To solve this question, 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






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.