Here I will show show an easy way to validate what the user inputs specially what type of data is typing.

That means that you can restrict the user to type something no longer than 10 characters, or to type only an integer or a float. Here I going to show you those three cases (something no longer than ten characters, an integer, and a float).

 

So let’s start with the easiest one; to restrict the number of character the user can type, it is easy to use the length command.

len(variable)

it will return the number of characters in case of a string, the number of elements it has in case of a list.

REMEMBER, in order to do this, the variablke must be either a string or a list, otherwise it won’t work

With a loop with the condition of what the user is typing is longer than ten characters, you can r4estrict the interaction of the user and don’t let him go until he types what you want

So for the program we will ask a nickname no longer than ten characters, the loop after asking the nickname will be:

string

So it will loop untill the user types it correctly

 

Then, we will review a little harder one; to restrict the user to only type an integer; that means the input won’t have a “.” inside of it, and it can be converted to integer via python.

There exists a common way to validate that which is by exceptions in a loop. With a loop that it’s only condition is to be true, you will use the command try, to, well, try to do something, in this case, to convert the input of the user to integer via python, variable = int(variable); if it results like an error, represented in python as ValueError, then it will ask again for the number. This loop is to make sure the user didn’t input letters, just numbers.

After doing that, is necessary to verify if the input has a decimal point”.”, in that case, it will ask again for the number

So it will look like this

integer

 

The last one, the float, its a little more ease, it just have to work if you try to convert it to float; you will use the same structure, but you will try to convert it to float instead to int variable = float(variable)

It will result like this:

float

Here you saw not just how to validate, but learned the basic types of data

The strings, that are just characters

The integers, that are just numbers, not fractions, not decimals

The floats, that are numbers with decimal points

 

It is easy isn’t it?

Eazy-E.jpg

CC BY 4.0 Masteries 29,9: Validate what the user inputs by charliegdrummer is licensed under a Creative Commons Attribution 4.0 International License.