我正在为用户和计算机编写一个石头剪子布游戏,我希望用户在三个选项中输入一个,即"石头";但是我不确定如果用户输入"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()
在这种情况下,您可能不需要异常。
您可能想要在input()上再次循环。
下面的代码更明确:
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.)
try|except机制更适合在上层处理错误。
如果您想在每次尝试失败后提醒用户输入选项,那么使用像None
这样的哨兵值是非常有用的:
class RockPaperScissors:
def getUserChoice(self):
choice = None
while choice not in ('rock', 'paper', 'scissors'):
if choice is not None:
print('Please enter only rock, paper, or scissors.')
choice = input('Type in your choice: rock, paper, scissors: ').lower()
return choice
你也可以在以后的Python版本中使用更短的版本:
class RockPaperScissors:
def getUserChoice(self):
prompt = 'Type in your choice: rock, paper, scissors: '
choices = 'rock', 'paper', 'scissors'
while (choice := input(prompt).lower()) not in choices:
print('Please enter only rock, paper, or scissors.')
return choice
另一个选项是让用户输入一个数字。这样,你就不用担心拼写了:
class RockPaperScissors:
def getUserChoice(options = ("rock", "paper", "scissors")):
options_str = "nt" + "nt".join(f'{x+1}. {opt}' for x,opt in enumerate(options))
while True:
userchoice = input(f"Type in your choice:{options_str}n").lower()
try:
userchoice = int(userchoice)
if 1 <= userchoice <= len(options):
return options[int(userchoice) - 1]
except:
if userchoice in options:
return userchoice
print("Invalid Input.")
注意:这使用try/except
,但仅用于字符串到int的转换。此外,如果用户输入的是单词而不是数字,代码也可以工作。
示例运行:
>>> RockPaperScissors.getUserChoice()
Type in your choice:
1. rock
2. paper
3. scissors
4
Invalid Input.
Type in your choice:
1. rock
2. paper
3. scissors
3
'scissors'
输入单词:
>>> RockPaperScissors.getUserChoice()
Type in your choice:
1. rock
2. paper
3. scissors
Paper
'paper'
并且,它适用于任何选项:
>>> RockPaperScissors.getUserChoice(("C", "C++", "Python", "Java", "Prolog"))
Type in your choice:
1. C
2. C++
3. Python
4. Java
5. Prolog
3
'Python'