The user input allows you to get your program to interact with a living being, the user. This can be helpful when you desire to get a value you have no control over, for instance a variable. It can also be applied to quickly test a program with multiple values many times.

To ask the user for a value or “input”, you first have to assign a variable to that value, next you use the “input” command to tell the computer to read and save in the variable we just created whatever the user types on the keyboard. After the “input” command you have to actually ask the user for the information that you desire to obtain, for example: “How many fingers do you have?”, then the user should answer the question returning the information and the input will assign that value to the variable we created.

X = input (“How many fingers do you have?”), user writes “5”, then “X = 5”

Although it is easy to write and very practical in itself, the fact that it generates a human-machine interaction can bring us many problems. For instance, we take it as granted that everyone has five fingers in each hand, but someone can count the fingers of BOTH of their hands, or they can have an extra finger, or just screw with you and give you a random number like 196. All of this outcomes have an impact in the way your program works.

Let’s say that your program is: n = input (“Give me a number”), and while (n>0): print (“Nom”) n=n-1. For this program you expect “n” to be an integer, but if the user gives you a string like “Banana”, then your program will die since the value of n is not valid for that condition.

This is the reason why we VALIDATE the user input, so that even if we can’t control what the user types we can filter that information and retrieve what we desire or just ask the user for a different input again and again until he gets it right.

Following the previews example, in order to avoid the “Banana” error:

We can use an “if”:

n = input (“Give me a number”)

if (n = int(n)) and (n>0):

while (n>0):

print (“Nom”)

n = n – 1

else:

n = input (“Give me another number”)

With this we have two conditions that “guard” the while, if the value of “n” is an integer and it is greater than zero then we can proceed with the loop, any other values will be discarded and the user will be asked for a new one. Of course there are lots of ways to validate, this was just an example of what you could do in this specific situation.

CC BY 4.0 Text based User input and Validation in Python by juansalvadorfernandez is licensed under a Creative Commons Attribution 4.0 International License.