I am writing a program that accepts user input.
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
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.")
The program works as expected as long as the the user enters meaningful data.
Please enter your age: 23
You are able to vote in the United States!
But it fails if the user enters invalid data:
Please enter your age: dickety six
Traceback (most recent call last):
File "canyouvote.py", line 1, in
age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'
Instead of crashing, I would like the program to ask for the input again. Like this:
Please enter your age: dickety six
Sorry, I didn't understand that.
Please enter your age: 26
You are able to vote in the United States!
How do I ask for valid input instead of crashing or accepting invalid values (e.g. -1
)?