Summary: To accept valid inputs from the user either use a While Loop With Custom Validations or use the PyInputPlus module to avoid tedious validation definitions. You can also use recursion to prompt the user for entering the valid input.
Overview
Problem: Given a user input; accept the input only if it is valid otherwise ask the user to re-enter the input in the correct format.
Any user input must be validated before being processed, without proper validation of user input the code is most certainly going to have errors or bugs. The values that you want a user to enter and the values that they provide as input can be completely different. For example, you want a user to enter their age as a positive valid numerical value, in this case, your code should not accept any invalid input like a negative number or words.
⭐Note: In Python 2.7, raw_input() is used to get a user input whereas in Python 3 and above input() is used to get user input. input() always converts the user input into a string, so you need to typecast it into another data type if you want to use the input in another format.
Let us have a look at an example to understand our problem statement.
Example:
age = int(input("What is your age: ")) if age >= 18: print("You are an Adult!") else: print("You are not an Adult!")
Output:
What is your age: 25 You are an Adult!
However, the code does not work when the user enters invalid input. (This is what we want to avoid. Instead of an error, we want the user to re-enter a valid input.)
What is your age: twenty five Traceback (most recent call last): File "C:/Users/Shubham-PC/PycharmProjects/pythonProject/main.py", line 1, in <module> age = int(input("What is your age: ")) ValueError: invalid literal for int() with base 10: 'twenty five'
Now that we have an overview of our problem, let us dive straight into the solutions.
Method 1: Implement Input Validation Using While Loop And Exception Handling
The easiest solution is to accept the user input in a while loop within a try statement.
- If the user input is invalid then we use the
continue
keyword within theexcept
block to move on to the next iteration. - Other validations can be specified within the
else
block, such that, when the user enters a valid input we use thebreak
statement to come out of the loop otherwise if the user enters an invalid input, the while loop continues and the user has to enter the correct input again.
Let us have a look at the following code to understand this concept:
while True: try: age = int(input("What is your age: ")) except ValueError: print("Please Enter a valid age.") continue else: if age > 0: break else: print("Age should be greater than 0!") if age >= 18: print("You are an adult!") else: print("You are not an adult!")
Output:
What is your age: twenty five Please Enter a valid age. What is your age: -25 Age should be greater than 0! What is your age: 25 You are an adult!
Method 2: Using Python’s PyInputPlus module
Another way of managing user inputs is to use the PyInputPlus
module which contains the different functions for accepting specific data inputs from the user like numbers, dates, email addresses, etc. You can read more about this module in the official documentation here.
❖ The function to accept an integer as an input from the user is inputInt()
.
Using the PyInputPlus
module we can ensure that the user input is valid because if a user enters invalid input, PyInputPlus
will prompt the user to re-enter a valid input. We can also specify other validations using arguments within the function.
❖ min = 1
: argument used by us to ensure that the age in our example is greater than 1.
Let us have a look at the code given below to get a better grip on the usage of PyInputPlus
for validating user input.
Disclaimer: PyInputPlus is not a part of Python’s standard library. Thus you have to install it separately using Pip.
import pyinputplus as pyip # User is prompted to enter the age and the min argument ensures minimum age is 1 age = pyip.inputInt(prompt="Please enter your age: ", min=1) if age >= 18: print("You are an Adult!") else: print("You are not an Adult!")
Output:
Please enter your age: -1 Number must be at minimum 1. Please enter your age: twenty five 'twenty five' is not an integer. Please enter your age: 25 You are an Adult!
Method 3: Implementing Recursion
Another way of prompting the user to enter a valid input every time the user enters an invalid value is to use recursion. Recursion allows you to avoid the use of a loop. However, this method works fine most of the time unless the user enters the invalid data too many times. In that case, the code will terminate with a RuntimeError: maximum recursion depth exceeded
.
Solution:
def valid_input(): try: age = int(input("Enter your Age: ")) except ValueError: print("Please Enter a valid age. The Age must be a numerical value!") return valid_input() if age <= 0: print("Your Age must be a positive numerical value!") return valid_input() else: return age x = valid_input() if x >= 18: print("You are an Adult!") else: print("You are not an Adult!")
Output:
Enter your Age: -1 Your Age must be a positive numerical value! Enter your Age: twenty five Please Enter a valid age. The Age must be a numerical value! Enter your Age: 25 You are an Adult!
Method 4: A Quick Hack Using Lambda Function
Though this method might not be the best in terms of code complexities, however, it might come in handy in situations where you want to use a function once and then throw it away after the purpose is served. Also, this method displays how long pieces of codes can be minimized, hence this method makes a worthy entry into the list of our proposed solutions.
Let us have a look at this trick in the program given below:
valid = lambda age: (age.isdigit() and int(age) > 0 and ( (int(age) >= 18 and "You are an Adult!") or "You are not an Adult")) or \ valid(input( "Invalid input.Please make sure your Age is a valid numerical vaule!\nPlease enter your age: ")) print(valid(input("Please enter your age: ")))
Output:
Please enter your age: -1 Invalid input. Please make sure your Age is a valid numerical vaule! Please enter your age: 0 Invalid input. Please make sure your Age is a valid numerical vaule! Please enter your age: twenty five Invalid input. Please make sure your Age is a valid numerical vaule! Please enter your age: 25 You are an Adult!
Conclusion
Thus proper validation of user input is of utmost importance for a bug-free code and the methods suggested above might prove to be instrumental in achieving our cause. I prefer the use of PyInputPlus
module since defining custom validations might get tedious in case of complex requirements. Also, the use of recursive methods must be avoided unless you are sure about your requirements since they require more memory space and often throw Stack Overflow Exceptions when operations are too large.
I hope you found this article helpful and it helps you to accept valid user inputs with ease. Please subscribe and stay tuned for more interesting stuff in the future!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.