我有这个hw在这里,我目前坚持。我的教授给我们提供的类异常,但我不知道有没有人能告诉我它是如何工作的,由于某种原因,当我运行这个程序,我得到这个:提升类例外通岩石剪刀游戏
Traceback (most recent call last):
File "C:\Python34\lab3.1.py", line 32, in <module>
rps_game_winner(game_2)
File "C:\Python34\lab3.1.py", line 5, in rps_game_winner
raise WrongNumberOfPlayersError('Wrong number of players!')
WrongNumberOfPlayersError: Wrong number of players!
所以想知道,如果有人能告诉我是什么做错了,或者我可以做些什么来使这个计划更好。 TY给大家
class WrongNumberOfPlayersError(Exception): pass
class NoSuchStrategyError(Exception): pass
def rps_game_winner(game):
if len(game) != 2:
raise WrongNumberOfPlayersError('Wrong number of players!')
return print ("A WrongNumberOfPlayers error has occurred. \n\n")
# Write the code for the NoSuchStratgyError
stop_words = ['R', 'P', 'S']
if stop_words not in game[0]:
raise NoSuchStrategyError('No such strategy!')
# Write the code to determine the winner
# Write the code to return a List with the winner's name and strategy
if ("R" in game[0]) and ("S" in game[1]):
return print (game[0], "wins since Rock beat Scissor\n\n")
elif ("P" in game[0]) and ("R" in game[1]):
return print (game[0], "wins since Paper beat Rock\n\n")
elif ("S" in game[0]) and ("P" in game[1]):
return print (game[0], "wins since Scissor beat Paper\n\n")
elif ("S" in game[1]) and ("P" in game[0]):
return print (game[1], "wins since Scissor beat Paper\n\n")
elif ("P" in game[1]) and ("R" in game[0]):
return print (game[1], "wins since Paper beat Scissor\n\n")
elif ("R" in game[1]) and ("S" in game[0]):
return print (game[1], "wins since Rock beat Scissor\n\n")
game = [["Armando", "P"], ["Dave", "S"]]# ["Dave", "S"] wins
game_2 = [['Joe','R']] # wrong number of players
game_3 = [['Joe','R'],['Walter','Q']] # no such strategy as 'Q'
rps_game_winner(game)# returns the list ["Dave", "S"] wins since Scissors beat Paper
rps_game_winner(game_2)# raises exception wrong number of players
rps_game_winner(game_3)# raises exception no such strategy as 'Q'
看起来就是这样的结果。请记住,你在这里定义EXCEPTIONS,然后故意抛出它们。你应该得到一个带有回溯的错误消息 –
你应该阅读[关于错误的教程](https://docs.python.org/2.7/tutorial/errors.html)。如果你觉得有些混乱,你也应该问问你的教授。这就是他们在那里的原因。 – jonrsharpe