How to Ask User Input in Python Until Valid Response

These days Python applications need to be interactive and give results based on user input. So Python developers need to be able to ask user input from within Python script or application. Accepting user input is one thing and accepting a valid user input is a different thing altogether. This is because, when you ask for user input, if they enter improper values then your Python script/application will crash and not proceed further. Therefore, we need also add a little bit of input validation and error handling to solve this problem. In this article, we will learn how to ask user input in Python until valid response.

Accepting User Input in Python

It is very easy to accept user input Python, using input() function. Here is an example.

age = int(input("Enter your age:"))

When you run the following command or script with this command, you will see the following output.

Enter your age:

If you enter values like 20, 30, etc. the above code will work properly. If you enter text values twenty, thirty, etc. it will throw the following error.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'twenty' is not defined

This is because Python expects a numerical value whereas we have provided a string input. That is why we need to include some kind of validation to make sure users do not enter improper values, and also put the input() function inside some kind of a loop so that in case the user inputs erroneous values, the program asks the users to enter input again. Finally, we also need to add exception handling to catch any unforeseen issues. We will look at how to do this in this article.

How to Ask User Input in Python Until Valid Response

Here are the steps to build a code that asks for user input until it gets a valid response.

1. Accept User Input

Here is a simple code to keep asking for user input until they enter proper values.

while True:
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Please enter numeric value")
continue

In the above code, we call input() function inside try…except block to catch any errors thrown due to invalid inputs. Since we need to ask user input till we get valid input, we add this try…except block in a while loop. The try-except block will make sure that in case users do not enter numerical values, the program does not throw an exception. The while loop makes sure that the program asks user input once again.

We have used ValueError exception type. If you do not know what it does, or want to catch a broader set of exceptions, then simply use Exception keyword instead.

while True:
try:
age = int(input("Please enter your age: "))
except Exception as e:
print("Please enter numeric value")
continue

2. Add Input Validation

You can add custom input validation such as the checking if the value is negative, to the above code. Make sure to add it inside the while loop, after try-except block. This is because you need to run all the input validation for each user input.

while True: 
try:
...
except:
...


if age < 0:
print("Please enter number > 0")
continue
else:
break
...

After the while loop we will add an if block that checks if the age is greater than 20 or not and give final output.

if age >= 20: 
    print("You are eligible")
else:
    print("You are not eligible")

3. Create Function

It is convenient to put the above code in a function so that you can call it whenever you want. Here is the complete code to do it.

def get_age(age):
while True:
try:
age = int(input("Please enter your age: "))
except Exception as e:
print("Please enter numeric value")
continue

if age < 0:
print("Please enter number > 0")
continue
else:
break

if age >= 20:
print("You are eligible")
else:
print("You are not eligible")

You can call the above function as shown.

age = get_age("Please enter age:")

Of course, you can also include these validations in another function and call it, to simplify your code.

Conclusion

In this article, we have learnt how to ask user input in Python until valid values are received. The key is to call input() function inside a try…except block, which in turn is present in a loop. In each iteration of your loop, you can add custom validations to check if the value is as per your expectation. It is very important to add exception handling as well as input validation to make sure that invalid inputs are handled and your loop does not terminate unexpectedly.

Also read:

How to Dynamically Bind Events in JavaScript
How to Password Protect Directory in NGINX
Apache Deny Access to URL, Files & Directory
NGINX Restrict Access to Directory & Subdirectories