Validated user input (ensure correct/expected data entry)

--Originally published at Sierra's Blog

there are many options to validate a user input, i’ll show you some of them:

user1 = input(“digite un numero: “)
while user1.isdigit():
print(“cool”)
break
else:
print(“bad”)
isdigit is a function that checks if the input is a number or a string, if it’s a number it will return the value “true”.

this works like this:

while True:
UserChoice = input(“give me the value: “)
try:
IntUserChoice = int(UserChoice)       #if it’s an int then return the value
return IntUserChoice
except ValueError:                                   #if it’s not, then choose another number
print(“Error, elige un número”)

it works the same with “isalpha” function:

user1 = input(“digite una cadena: “)
while user1.isalpha():
print(“cool”)
break
else:
print(“bad”)