Validated user input

--Originally published at Python

When writing a user influenced program you need to ensure that the user does what he is expected to. Usually you want the user to type a certain type of variable, and there’s times when the user will type in something else. You need to validate the user input, otherwise, the program will crash and it won’t work. The simplest way I could find to do this is by using a While Loop using “try” and “except”. Here’s some code that you can use as a guide.

Code:

while True:
try:
age = int(input(“Please enter your age in years: “))

except ValueError:
print(“Only numbers please”)

else:
break

print(“Thanks for the info”)

2validating

The program enters a while loop and asks for an input. When the input is given, the program will check for exceptions, the exception here being when there’s a value error. This means that when someone inputs something that isn’t an integer, the program will enter the exception part which tells the user to type numbers only. Then it will continue looping until an integer is given. Once it is, the program will move on to the else, in case no exception was made. This else has a break which will end the loop, and after that, the processes outside the loop are done, and the program ends.