We have worked on many problems in Python, till now, right? But have you ever wondered how to write programs to take in inputs until they get valid responses? Thus, in this program, we will see how to write programs that keep asking the user for input until they give a valid response in Python. So, without wasting any more time let us get to the topic in greater depth.

Introduction

We know how to get inputs from the user. But, there can be cases wherein we may ask for inputs. Say, ask for integers but by mistake, the user enters a string as input. Thus, we need to ask again for a valid input until the user enters the correct input, isn’t it?

Note: In Python 2.7, we make use of raw_input() to ask for user input whereas in Python 3 and above simply the input() function is employed for user input. The input() function always converts the user input into a string, by default. If we want to input any other type of element then we need to typecast it into that data type.

Let us have a glance at an example to understand it better.

age = int(input("What is your age ? :  "))
if age >= 18 :
print("You are eligible to vote ! ")
else:
print("You are not eligible to vote ! ")

# Output :
What is your age ? : 24
You are eligible to vote ! 

This program works nicely we have entered the correct input. Now, suppose by mistake we have entered an input of wrong data type, then, the code doesn’t work. It rather outputs an error message.

# Output :
What is your age ? : Twenty Four

Traceback (most recent call last):
File "C:/Users/Shubham/Project/main.py", line 1, in
age = int(input("What is your age ? :  "))
ValueError: invalid literal for int() with base 10: 'Twenty Four"

Now, let us look for solutions to our problem.

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

There are many ways we can get this work done. Let us look at the many methods that we have at our disposal.

Using excception handling and while loop to validate inputs

The easiest solution is to simply accept the user input taking the help of a while loop with exception handling.

If the user input is invalid then we use the continue keyword within the except block to maneuver on to the subsequent iteration. Other validations are often specified within the else block, such that, when the user enters a legitimate input we use the break statement to return out of the loop otherwise if the user enters an invalid input, the while loop continues and therefore the user has got to enter the right input again.

Let us have a glance at the subsequent code to know this concept:

while True :
      try :
           age = int(input("What is your age ? :  "))
     except ValueError :
           print("Invalid Input !! ")
           continue
     if age > 0 :
                break
     else:
          print("You have entered an invalid age")
     if age >= 18:
           print("You are eligible to vote ! ")
     else:
           print("You are not eligible to vote ! ")

# Output:
What is your age ? : Twenty Four
Invalid Input !! 

What is your age ? : -4
You have entered an invalid age

What is your age: 24
You are eligible to vote !

Using Recursion

Another method to ask the user to enter an acceptable input whenever the user enters an invalid value is to use recursion.

Recursion allows you to avoid the utilization of a loop. However, this method works fine most of the time unless the user enters the invalid data too repeatedly. If that is the case, then the code will terminate with a RuntimeError: maximum recursion depth exceeded.

def valid_input():
       try:
          age = int(input("Enter your Age :  "))
      except ValueError:
          print("Invalid input ! ")
return valid_input()
if age >= 18:
      print("You are eligible to vote ! ")
else:
      print("You are not eligible to vote ! ")

# Output :
Enter your Age : -1
Invalid input !

Enter your Age : Twenty Four
Invalid input !

Enter your Age : 24
You are eligible to vote !

How can I read inputs as numbers !!

Using Lambda Function

Though this method won’t be the simplest in terms of code complexities, however, it’d come in handy in situations where you would like to use a function. Also, this method displays how long pieces of codes are often minimized, hence this method makes a worthy entry into the list of our proposed solutions.

valid = lambda age: (age.isdigit() and int(age) > 0 and (
(int(age) >= 18 and "You are eligible to vote ! ") or "You can't vote ! ")) or \
valid(input(
"Invalid input ! \n Please enter your age: "))
print(valid(input("Please enter your age: ")))

# Output :
Please enter your age : -4
Invalid input !

Please enter your age : 0
Invalid input !

Please enter your age : Twenty Four
Invalid input !

Please enter your age: 17
You can't vote!

Please enter your age: 24
You are an eligible to vote!

WRAPPING UP !!

Thus, proper validation of user input is of utmost importance for a bug-free code. Hence, the methods mentioned above help in achieving what we set out for. I, for instance, prefer using the while loop with exception handling, as a method to ask for valid input from the user. Also, the utilization of recursive methods shall be avoided unless you’re sure about your requirements since they require more memory space and sometimes, even throw exceptions. Hope this article serves you well. For further queries do not hesitate, but post them in the comments box. Until next time! See-ya 🙂