Python for Beginners 19: Validating User Input

As we’re getting to the end of our “Python for Beginners” series, we’re finally going to learn how to validate user input, i.e. how to make sure that the input corresponds to what you anticipated and that you can use it in your program.

There are basically two things that you need to validate:

  1. Does the user input have the right data type?
  2. What values can the user input take? Does a string have the correct length or is a number in the right range?

1. Does the user input have the right data type?

You may remember from previous lessons that if not indicated otherwise, user input will be considered to be in the data format of strings. Even though we have discussed the usefulness of strings just recently, there are going to be many cases when we are going to need a different data type, which is why we often converted the user input using the data type functions such as int() to take the input as an integer or float() for floating-point numbers. Considering our new knowledge on sequence-based data types such as lists and tuples, we have even more options. However, using these data type conversion functions may produce errors and stop the program, for instance if you enter a decimal number as data type integer. This is simply not going to work.

2. What values can the user input take?

To make sure that our user input does not take any values that lead to errors in our program, you should define the range of potential values of a number or the length of a string. To do this, you can just use functions that you already know such as range([start],stop) or len(string). But what should you do when the entered value is invalid?

How to implement validation

To validate the two aspects that we’ve just discussed (data type and values), you can use different methods. Usually, you either use a flag or an exception. A flag is basically a variable that changes from True to False or vice versa when the value is valid, thus allowing you to leave a while loop that otherwise keeps asking for a new entry.

Let’s do a quick example: We want to know the user’s age. We do not only want to make sure they are older than 18, but we also want a plausible entry, i.e. no more than 122 (highest age that a human being has ever reached and that was verified).

Using what we already know, we can just define the input as an integer. Then we set the allowed range and using a loop we ensure that the program continues even if there is an invalid entry.

This program is going to ask again and again for the age as long as the input is an invalid integer. However, if the input is not an integer, you get an error message from the console and the program stops executing. To avoid this, you can use the exception method that you can learn from Easy Python Docs.
#mastery19

Leave a comment