I'm writing a rock, paper, scissors, game for a user and computer and I want the user to type in one of the three options i.e "rock" but I'm not sure what kind of exception to use if the user enters say "monkey."
class RockPaperScissors:
def getUserChoice(userchoice):
while True:
try:
userchoice = input("Type in your choice: rock, paper, scissors: ")
if userchoice != "rock" or userchoice != "paper" or userchoice != "scissors":
raise ValueError("Try typing in your choice again")
break
except:
print("Invalid Input.")
return userchoice.lower()
In this case, you probably do not need an exception.
You probably want to loop again on input().
The following code is more explicit:
class RockPaperScissors:
def getUserChoice():
while True:
userchoice = input("Type in your choice: rock, paper, scissors: ").lower()
if userchoice in ( "rock", "paper" "scissors"):
return userchoice
else:
print( "Invalid input. Try again.)
The try|except mechanism is more appropriate when you want to handle the error at an upper level.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments