The purpose of the input validation code is to verify that user-inputted items, like text from the input()
method, are formatted appropriately. For example, if we wanted to input a user’s age, the words or negative numbers do not make sense. Additionally, input validation can stop errors or security flaws.
Ensure the amount is a positive number if you implement a withdrawFromAccount()
function that accepts an argument for deducting the amount from an account. The withdrawal will result in additional funds if the withdrawFromAccount()
function deducts a negative amount from the account.
Let’s see an example code where we ask the user to enter the age. Typically, we’ll iterate through the inputs and check if it’s valid; if not, we’ll ask it repeatedly. For a better understanding, check the code given below:
def inputAge():# Loop to iterate through the inputswhile True:# Getting the input by userage = input()# Check if the entered value is not an integertry:age = int(age)except:print('Please enter a numeric value')continue# Check if the entered value is negativeif age < 1:print('Age cannot be negative, please enter a Positive value')continuereturn ageage = inputAge()print("Your Age is: ", age)
Enter the input below
Run this code by providing some invalid entries to check the input validation on the age.
Note: Make sure to enter some invalid values before entering an valid value to check the actual working of the code.
Let’s see the code by exploring the important lines of code in the code:
Line 3: We created a loop that will keep iterating until we get the valid input for our age.
Line 5: We use this line to get the input from the user.
Lines 7–11: We use these lines to create a check for the data type of values entered by the user.
Lines 13–15: We use these lines to check the negative values entered by the user.
We successfully created a method that will be used to get the input for the age. However, writing input validation logic for every input()
call in your program gets tiring. Additionally, we can overlook some situations and let erroneous information go past our checks.
PyInputPlus
moduleSimilar to input()
, there is another module in Python named PyInputPlus
. This module offers routines for various data types, including dates, email addresses, numbers, and more. The PyInputPlus
module prompts the user for input, exactly as our code in the previous section did if they ever enter invalid data, such as a date not properly formatted or a number outside of an acceptable range. Other helpful features include a countdown on how often users can be prompted and a timeout when users must reply within a set amount of time.
As PyInputPlus
is not included in the Python Standard Library, we must use pip
to install it independently. Use the following command to install this module on your local machine:
pip install PyInputPlus
This module has several methods for the input, some of the methods are listed below:
inputStr()
: This method is the same as the built-in input()
function, but with the PyInputPlus
features to add custom validations.
inputNum()
: This method ensures that the user has entered a numeric value. It also specified the type of variable depending on the value if a number has decimal points in it.
inputChoice()
: This method ensures that the user enters one of the provided choices.
inputMenu()
This method is similar to the `inputChoice()` method but provides a menu of choices.
inputDatetime()
: This method ensures that the user has entered a date and time.
inputYesNo()
: This method ensures the user has entered a “yes” or “no” value.
inputBool()
: This method ensures the user has entered a “True” or “False” value.
inputEmail()
: This method ensures that the user has entered an email.
inputFilepath()
: This method ensures the user has entered a valid path or file name.
inputPassword()
: This method is the same as built-in input()
method but displays *
characters when the user types anything.
Let’s get through the same example of getting input from the user about the age, but with PyInputPlus
module.
import pyinputplus as pyipage = pyip.inputNum(min = 0)print("Your age is: ", age)
Let’s see the code by exploring the important lines of code in the code:
Line 1: We import the PyInputPlus
module.
Line 2: The inputNum()
method is used to ensure that the user has entered a numeric value. The min
parameter to this method defines that this will allow 0
as the minimum value. It will not accept any negative value.
Note: Connect this terminal to see the execution of the code.
Free Resources