Mastery 29 Validated User input in Python

Sometimes in our code we want an special type of value and in this case we have to be ensure that the user enters the correct value. So with something we can be ensure, like in the next example is just for that:

while  True:
        try:
            q=int(input(“Please enter a non-negative integer number: “))
            break
        except ValueError:
            print(“this is not a integer number, try again: “)

while q<0:
        try:
            q=int(input(“this is not a positive number,try again: “))
        except ValueError:
            print (“this is not a integer number, try again:  “)
            while True:
                try:
                    q=int(input(“Please enter a non-negative integer number: “))
                    break
                except ValueError:
                    print (“this is not a integer number, try again: “)

 

In this example we want a value positive and integer. so first check that the value that the user enters has to be integer if enters an integer number the value would be through to next condition, and if is not a integer number it will be through to an except ValueError that  just when the user enter the correct value it will through the value to the next condition.

Ok let see, the next condition say that the number it has to be positive if is not, the value will be through to except ValueError again until the value enter for the users be correct.But also the user in this case can enter a positive number but no integer so we have to be ensure again of this with another while true that does the same operations of the last one.

Until the value complete all of the conditions the value will be through to  the funtion or operation that we want to do with them.

this is just an example, it depends of what value you want, you just has to write the statements of “try” and “except” in order of what you want.

 

 

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

Comments are closed.