Python - 尝试控制输入时出错

Python - Error when attempting to control inputs

我正在尝试在 Python 中编写剪刀石头布练习。游戏的核心功能就在那里。但是,我正在尝试为用户输入 "rock"、"paper" 或 "scissors." 以外的内容时编写输出。正如您从下面的代码中看到的那样,else 语句位于如果用户输入了三个预期答案之一以外的内容,游戏结束应该捕捉到。如果他们这样做,他们应该得到 "Something went wrong!" 作为输出。

程序代码如下:

print ("Rock...")
print ("Paper...")
print ("Scissors")

player_one = input("Player One, make your move! ")

player_two = input("Player two, make your move! ")

if player_one == "rock" and player_two == "paper":
    print ("Player Two Wins!")
elif player_one == "rock" and player_two == "scissors":
    print ("Player One Wins!")
elif player_one == "paper" and player_two == "rock":
    print ("Player One Wins!")
elif player_one == "paper" and player_two == "scissors":
    print ("Player Two Wins!")
elif player_one == "scissors" and player_two == "rock":
    print ("Player Two Wins!")
elif player_one == "scissors" and player_two == "paper":
    print ("Player One Wins!")
elif player_one == player_two:
    print ("Time Game!")
else:
    print("Something went wrong!")

但是,当我使用 "rock"、"paper" 或 "scissors" 以外的其他内容作为 player_one 响应时,我在 PowerShell 中收到以下错误。例如,当我输入 "rocks" 时,我得到这个:

Traceback (most recent call last):
  File "rpsbasic3.py", line 5, in <module>
    player_one = input("Player One, make your move! ")
  File "<string>", line 1, in <module>
NameError: name 'rocks' is not defined

折腾了一段时间,不知所措。

因为您使用的是 python 2,请升级到 python 3,或者更换:

player_one = input("Player One, make your move! ")

player_two = input("Player two, make your move! ")

与:

player_one = raw_input("Player One, make your move! ")

player_two = raw_input("Player two, make your move! ")