• Xander Stevenson

Input Validation for Python with PyInputPlus

For basic Python users, input can be validated by taking the user input through input().

For example:

print(‘How old are you?’)

user_age = input()

This prompts the user and assigns their input to the variable user_age. After that, we can make sure the input is of the correct type, length, etc. and throw an exception or prompt the user to enter data again.

That’s the basic way. A better way to validate input is by using PyInputPlus. However, this is not a standard Python library. I downloaded and installed like so (for Mac):

pip3 install pyinputplus

Here are the methods that come with it PyInputPlus:

inputStr() Is like the built-in input() function but has the general PyInputPlus features. You can also pass a custom validation function to it

inputNum() Ensures the user enters a number and returns an int or float, depending on if the number has a decimal point in it

inputChoice() Ensures the user enters one of the provided choices

inputMenu() Is similar to inputChoice(), but provides a menu with numbered or lettered options

inputDatetime() Ensures the user enters a date and time

inputYesNo() Ensures the user enters a “yes” or “no” response

inputBool() Is similar to inputYesNo(), but takes a “True” or “False” response and returns a Boolean value

inputEmail() Ensures the user enters a valid email address

inputFilepath() Ensures the user enters a valid file path and filename, and can optionally check that a file with that name exists

inputPassword() Is like the built-in input(), but displays * characters as the user types so that passwords, or other sensitive information, aren’t displayed on the screen

**these methods were copied verbatim from https://automatetheboringstuff.com/2e/chapter8/

You can run Python code directly in the IDE, but I like to use the Bash terminal in VScode. Here’s my code, I saved it as input_valid.py

import pyinputplus as pyip

print('How old are you?')

answer = pyip.inputNum()


Here is the interaction when I ran the program in the terminal

How old are you?


'f' is not a number.



As you can see, it works for me. I did have some issues at first with the module. After I installed it, I couldn’t import it. I had to make sure the location of the module was included in my PATH. After I did that, it worked just fine.

284 views0 comments