--Originally published at Just A Turtle Coding.
When validating user entries, you have to know what you’re looking for. When a function uses a specific type of variables, it might crash if the user inputs something that the function can’t use. To apply this, you can call a try function.
For more info, you can consult: http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response
while True:
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
if age >= 18:
print("You are able to vote in the United States!")
else:
print("You are not able to vote in the United States.")