Pedindo entrada ao usuário até que ele dê uma resposta válida
Estou escrevendo um programa que deve aceitar a entrada do usuário.
#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.")
Isso funciona como esperado se o usuário digitar dados sensíveis.
C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!
Mas se eles cometerem um erro, ele trava:
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'
Em vez de travar, gostaria de tentar obter a entrada novamente. Como isso:
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!
Como posso fazer isso? E se eu também quisesse rejeitar valores como-1
, que é um válidoint
, mas sem sentido neste contexto?