The Best Way to Request User Input in Python

Take advantage of the PyInputPlus Module

The Best Way to Request User Input in Python
Photo by Jonas Stolle on Unsplash

Requesting user input is a topic of frequent discussion. There are lots of opinions and strategies out there, but it’s important to be willing to change. I’ve recently come across what I consider now the best way to request user input in Python and I want to share it with you.

An Inferior Option

I previously wrote about indefinitely requesting user input in Python and while there are some benefits to manually building a framework/strategy around the input() function, it’s fair to say for normal requests that this is overkill.

The struggle between “off the shelf” and “fully custom” is as old as time. The important takeaway is to have enough understanding of the “off the shelf” solution to know when it will satisfy your needs and when you have to roll up the sleeves and build it ground up.

Using the PyInputPlus Module

The “off the shelf” solution for requesting user input in Python is the PyInputPlus module.

First things first, PyInputPlus does not come natively installed in Python so we’ll need to install the module using either pip or pip3.pip install pyinputplus

We also need to make sure we include the library in any Python files that will make use of it. Note that I’ll be assigning a shorter local name: pyinput.import pyinputplus as pyinput

Now, let’s recreate the example in my other article and prompt the user for their age, which must be a positive integer.prompt = 'How old are you: '
age = pyinput.inputInt(prompt=prompt, greaterThan=0)

Here’s what the execution of our code looks like with some sample input attempts.How old are you: -1
Number must be greater than 0.
How old are you: 11.5
'11.5' is not an integer.
How old are you: 14

It’s really that easy.

Conclusion

The PyInputPlus module has several methods including inputStr(), inputNum(), and inputMenu() for each specific type. Moreover, parameters such as limit, applyFunc, and validationFunc are just a small preview of the exponential power that this module offers.


I hope you liked this article! Subscribe to be notified when I publish new articles or even better, support me by joining the Medium community as a paid subscriber.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe