Reputation: 474
Say I have a code snippet:
players_chosen_hit = int(input('Where do you want to try to hit the AI?: 1-9 '))
What if the user enters a letter? How can I handle it such that it will tell the user he screwed up and have him re-enter until he gets a number in?
How about this:
possibleusershipplaces = [1,2,3,4,5,6,7,8,9]
players_chosen_hit = int(input('Where do you want to try to hit the AI?: 1-9 '))
while players_chosen_hit not in possibleusershipplaces:
players_chosen_hit = input('Please tell me where the hit is: 1-9 (or Ctrl/Command+C to quit) ')
players_chosen_hit = int(players_chosen_hit)
Upvotes: 1
Views: 140
Reputation: 180502
possibleusershipplaces = {1,2,3,4,5,6,7,8,9}
while True:
try:
players_chosen_hit = int(input('Where do you want to try to hit the AI?: 1-9 '))
if players_chosen_hit in possibleusershipplaces:
break
except ValueError:
print("Invalid entry")
To also handle quitting:
while True:
try:
players_chosen_hit = input('Please tell me where the hit is: 1-9 (q to quit) ')
if players_chosen_hit == "q":
print("Goodbye")
break
players_chosen_hit = int( players_chosen_hit)
if players_chosen_hit in possibleusershipplaces:
break
except ValueError:
print("Invalid entry")
If you don't want a try/except and have only positive numbers you can use str.isdigit
but the try/except is the idiomatic way:
possibleusershipplaces = {"1","2","3","4","5","6","7","8","9"}
for players_chosen_hit in iter(lambda:input('Please tell me where the hit is: 1-9 (q to quit) '),"q"):
if players_chosen_hit.isdigit() and players_chosen_hit in possibleusershipplaces:
players_chosen_hit = int(players_chosen_hit)
iter
takes a second argument sentinel
which will break the loop if entered.
It might also be better to use a function and to return when we reach a condition:
def get_hit():
while True:
try:
players_chosen_hit = input('Please tell me where the hit is: 1-9 (q to quit) ')
if players_chosen_hit == "q":
print("Goodbye")
return
players_chosen_hit = int(players_chosen_hit)
if players_chosen_hit in possibleusershipplaces:
return players_chosen_hit
except ValueError:
print("Invalid entry")
Upvotes: 1