I am on Windows 11 home, Python 3.12.2. I am playing with the rock, paper scissors application. I would like to check if the user input is a valid choice. I experimented with try / except and if / in. I would like to restart the loop if the user enters a value other than the valid entries. I ve commented out the current attempt. Otherwise the program works OK. Suggestions?
import random
valid_values = ["rock", "paper", "scissors", "quit"]
victories = [
["paper", "rock"],
["rock", "scissors"],
["scissors", "paper"]
]
# create while loop until user exits
while True:
# prompt user to challenge computer to a game
user_input = input("Choose rock, paper, scissors, or quit ")
challenge = user_input.lower()
# check if user_input is valid
# if challenge in valid_values:
# continue
# else:
# print("this is not a valid value")
if challenge == "quit":
print("OK, bye")
break
else:
# generate random rock, paper, scissors
guess = random.choice(valid_values[0:2])
# determine winner and display result
if challenge == guess:
print("Tie!")
elif [challenge, guess] in victories:
print(f"The {challenge} beats the {guess}, you win!")
else:
print(f"The {guess} beats the {challenge}, you lose!")type here
如果该条目无效,我想重新开始。 我要么既得不错,又得起/损失,要么可以放弃。 或许是因为继续