Friday, 14 September 2018

Asking the user for input until they give a valid response

I am writing a program that must accept input from the user.

#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.")

This works as expected if the user enters sensible data.

C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!

But if they make a mistake, then it crashes:

C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Traceback (most recent call last):
  File "canyouvote.py", line 1, in <module>
    age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'

Instead of crashing, I would like it to try getting the input again. Like this:

C:\Python\Projects> canyouvote.py
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 can I accomplish this? What if I also wanted to reject values like -1, which is a valid int, but nonsensical in this context?



from Asking the user for input until they give a valid response

No comments:

Post a Comment