How to take input from the user until they enter valid input in Python?

Consider you are solving a problem in which you need to take input from the user and validate the same. You will simply use the input() method and typecast it accordingly for the same. However, if the input provided is not what was expected, you may just end up with an error. Instead of this, you may want to keep asking the user for input until the right input is provided.
In this tutorial, you will learn how to take input from the user until they enter valid input in Python.

Understanding the Problem Statement

One of the most common examples to understand the above problem is when you want to take age as input from the user.
The below code takes age as input from the user (in integer type) and displays if the entered age is adult or not.

age = int(input("Enter Age: "))
if age >= 18:
   print("Adult")
else:
   print("Not an Adult")
Enter Age: 50
Adult
age = int(input("Enter Age: "))
if age >= 18:
   print("Adult")
else:
   print("Not an Adult")
Enter Age: fifty
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-1bb0ea8ad070> in <module>
----> 1 age = int(input("Enter Age: "))
      2 if age >= 18:
      3    print("Adult")
      4 else:
      5    print("Not an Adult")

ValueError: invalid literal for int() with base 10: 'fifty'

In such a situation, we would prefer asking for the right input and waiting until valid input is entered. Let us now see how to achieve the same.

In order to take input from the user until they enter valid input, you can repeatedly ask for input. This can be achieved in two ways;

  1. Using loop statement.
  2. Through recursion.

Using looping

We use the while loop to iterate and take input until valid input is entered. You can make use of the if clause to validate the user input. Once valid input is received, we exit the loop by using the break statement.

while True:
     if (valid input):
          break

Implementing the above solution on the example we discussed earlier;

while True:
    try:
        age = int(input("Enter age: ")) 
        if age>18:
            print("Valid Input \nAdult")
            break;
        else:
            print("Not an Adult")
            break;
    except ValueError:
        print("Provide an integer value...")
        continue
Enter age: fifty
Provide an integer value...
Enter age: 50
Valid Input 
Adult

Using recursion to take input from the user until they enter valid input in Python

You can repeatedly ask for input without using any loop. However, if the user takes too many attempts, i.e., if the user enters invalid inputs too many times, you may encounter the error ‘maximum recursion depth exceeded ‘.
A sample code for the same is as follows;

def wait_until_valid_input():
    try:
        age = int(input("Enter Age: "))
    except ValueError:
        print("Provide an integer value...")
        return wait_until_valid_input()
    return age
x = wait_until_valid_input()
if x > 18:
    print("Adult")
else:
    print("Not an Adult")
Enter Age: eighteen
Provide an integer value...
Enter Age: 18
Not an Adult

We hope this tutorial answered your questions.

Also read, Python input( ) function

Leave a Reply

Your email address will not be published.