Py学习  »  Python

Python-尝试控制输入时出错

Andy • 5 年前 • 1436 次点击  

我想用Python写一个石头剪子练习。游戏的核心功能就在那里。但是,我试图为用户输入“石头”、“纸”或“剪刀”以外的内容时编写输出。从下面的代码可以看出,如果用户输入了三个预期答案中的一个以外的内容,则游戏结束时的else语句应该会捕获。如果他们这样做了,他们应该得到“出了问题!”作为输出。

程序代码如下:

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!")

然而,当我用“石头”、“纸”或“剪刀”以外的东西来回应玩家的回应时,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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50327
 
1436 次点击  
文章 [ 1 ]  |  最新文章 5 年前
U10-Forward
Reply   •   1 楼
U10-Forward    5 年前

因为您使用的是Python2,所以要么升级到Python3,要么替换:

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! ")