Python | Asking the user for input until they give a valid response

Asking the user for input until they give a valid response in Python

In this article, we are going to create a Python program that will be asking the user for input until they give a valid response.

Taking input from users is a kind of hurdle especially when you are designing applications, you don’t know if the users are going to enter valid input. If your program is not written in an error-handling manner, your application will crash. Hence, it is always the ideal way to use error handling while writing a program. Your code must handle all the possible errors.

Understanding problem

Let’s first understand what actually the problem arises. Here, I will design a code to know if the user is eligible to vote or not.

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

if(age>=18):
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

Output:

Enter your age: 20
You are eligible to vote.

What if the user entered, ‘twenty’, what will the program say? Will it say, ‘You are eligible to vote.’ or ‘You are not eligible to vote.’? No! If you are thinking of one of these answers, let’s check what it will actually say:

Output:

Enter your age: twenty
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'twenty'

Can you guess what is the error actually? In the program, we are taking input as an integer, but we are passing a string as input, and thus the program is failing to typecast this string to an int, hence the error.

Now one might say that we can remove the typecasting actually, but anyways the program will not handle any inputs then, as in the conditionals it will be confused.

How should the program work?

So, the solution to our problem will be asking the user for input until they give a valid response. Something like:

Enter your age: twenty
Seems you have entered a wrong input! Please correct it again.
Enter your age: ty
Seems you have entered a wrong input! Please correct it again.
Enter your age: 20
You are eligible to vote.

Different ways to implement a Python program that will be asking the user for input until they give a valid response

1. Use a loop with a try-except block

try-except block in Python provides a solid way to deal with all types of errors. We can use this block to handle the errors and then put some custom messages inside the exception part. For that infinite looping until the user enters the correct input, use a loop.

while True:
    try:
        age = int(input("Enter your age:"))
        break
    except ValueError:
        print("Seems you have entered a wrong input! Please correct it again.")
if(age>=18):
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

Output:

Enter your age:twenty
Seems you have entered a wrong input! Please correct it again.
Enter your age:ty
Seems you have entered a wrong input! Please correct it again.
Enter your age:20
You are eligible to vote.

Perfect!

Now, you might wonder, what if the name of the error is not known? Well, you can just simply replace the error name with the Exception keyword and you can also print the error if you want.

while True:
    try:
        age = int(input("Enter your age:"))
        break
    except Exception as e:
        print("Seems you have entered a wrong input! Please correct it again.")
if(age>=18):
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

This is for handling all sorts of errors.

2. Create a function for validation

You can further include these validations in a function and call for the function when needed. This is best if you are taking input multiple times, so the code will look more readable plus, you don’t have to write code for each time. Let’s understand this with a clear example.

Imagine you are writing a code that takes the input of the marks obtained in different subjects and depicts the percentage of the student. Here also ValueError (especially) needs to be handled. And like above, you won’t write the same input code from the loop n times! Here comes the function. We can write the input code inside the function and you can pass your own custom different input messages for each time. Here’s how:

def input_num(message):
    while True:
        try:
            num = int(input(message))
            break
        except Exception as e:
            print("Seems you have entered a wrong input! Please correct it again.")
    return num


maths = input_num("Enter marks obtained in the Mathematics: ")
science = input_num("Enter marks obtained in the Science: ")
english = input_num("Enter marks obtained in the English: ")
social = input_num("Enter marks obtained in the Social Science: ")
drawing = input_num("Enter marks obtained in the Drawing: ")

per = (maths+science+english+social+drawing)/5

print(f"You got {per}%")

Output:

Enter marks obtained in the Mathematics: fifty-six
Seems you have entered a wrong input! Please correct it again.
Enter marks obtained in the Mathematics: 56
Enter marks obtained in the Science: 67
Enter marks obtained in the English: 45
Enter marks obtained in the Social Science: ninety-eight
Seems you have entered a wrong input! Please correct it again.
Enter marks obtained in the Social Science: 98
Enter marks obtained in the Drawing: eighty-one
Seems you have entered a wrong input! Please correct it again.
Enter marks obtained in the Drawing: 81
You got 69.4%

Now, the above program will be working perfectly and will be continuously asking the user for input until they give a valid response in Python

3. Chain and repeat from itertools

Let’s implement one more method that will be continuously asking the user for input until they give a valid response.

This is one of the ways you can try if you are not comfortable with the loops and try-except. This can be used when the program isn’t that complex. Check this out:

from itertools import chain, repeat

input_msg = "Enter your age: "
bad_input_msg = "Sorry, I didn't understand that."
prompts = chain([input_msg], repeat('\n'.join([bad_input_msg, input_msg])))
replies = map(input, prompts)
valid_response = next(filter(str.isdigit, replies))
age=int(valid_response)
if(age>=18):
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

The code above handles the bad input without for and try-except.

itertools module in Python works for iterators. iterators.chain and iterators.repeat will create iterators that yield strings for bad input messages and input messages an infinite number of times. map() will apply to all the prompt messages in the input function. The filter() and isdigit() are used to find out the strings that can be a digit and then the valid string is converted into a number and it is validated.

Well, we have solved the problem!

The itertools approach is not always recommended as it can be a little tricky to apply. Instead, using try-except in the code is always a good practice to handle errors.

Hope this works!

I hope your problem of asking the user for input until they give a valid response in Python has been solved.

Thank you for visiting our website.


Also read:

Share:

Author: Ayush Purawr