Mastery 29. Validated User input in Python

There are some cases where we create a function in our program destined to receive an special type of value. Here is where we want to ensure that the user enters the correct value and not any other type that will cause our program to crash, thats why we validate the user input by using some tools that I will show you.

Lets see the next example:

In this case we want our user to enter a positive integer number.

There are 3 possible cases in this input:

a) The user enters a positive integer number: In this case, the input will be correct and Python will get out of the loop, continuinh with the rest of the code.

 

b) The user enters a negative integer number: In this case the input will be validated with the built-in type “int” function and it will not return any error, but as it is not positive, it will enter in the loop, asking the user to enter a positive number instead of a negative one.

 

c) The user does not enter an integer number: Any value different from an integer value will return “ValueError” because we are using the built-in type “int” function. As the program tries this value and returns the “ValueError” it will passes to the “except” statement, where it will tell the user his mistake and will send the user to the beginning again, entering in the “try” statement.

 

This is just an example of validating user inputs, but there may be many variants, depending on what value you want to get from the user. You can use as many different of built-in type functions as you wish, it is just matter of playing with the “try” and “except”statements.

 

CC BY 4.0 Mastery 29. Validated User input in Python by Manuel Madrigal is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.