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