为什么这个简单的“石头剪刀”程序不是用Python工作的?

时间:2016-08-30 17:25:14

标签: python python-3.x

我是python的新手,我正在尝试编写一个程序,用户在计算机上播放石头剪刀。但是,我不知道为什么它不起作用。这是代码:

import random

computerResult = random.randint(1,3)

print("Lets play Rock Paper Scissors")
playerResult = input("Type 1 for Rock, 2 for Paper or 3 for Scissors: ")

if computerResult == 1:
    print("Computer says Rock")
if computerResult == 2:
    print("Computer says Paper")
if computerResult == 3:
    print("Computer says Scissors")


if playerResult == computerResult:
    print("Its a draw")
elif playerResult == 1 and computerResult == 2:
    print("You lose")
elif playerResult == 1 and computerResult == 3:
    print("You win")
elif playerResult == 2 and computerResult == 1:
    print("You win")
elif playerResult == 2 and computerResult == 3:
    print("You lose")
elif playerResult == 3 and computerResult == 1:
    print("You lose")
elif playerResult == 3 and computerResult == 2:
    print("You win")

当我运行程序并玩游戏时,这就是我得到的:

Lets play Rock Paper Scissors
Type 1 for Rock, 2 for Paper or 3 for Scissors: 1
Computer says Scissors

它没有说我是赢还是输,我不知道为什么

4 个答案:

答案 0 :(得分:6)

因为playerResultstrcomputerResultint。将字符串与int进行比较总会产生False

更改

playerResult = input("Type 1 for Rock, 2 for Paper or 3 for Scissors: ")

playerResult = int(input("Type 1 for Rock, 2 for Paper or 3 for Scissors: "))

答案 1 :(得分:1)

这应该解决它

playerResult = input("Type 1 for Rock, 2 for Paper or 3 for Scissors: ")
playerResult = int(playerResult)

答案 2 :(得分:0)

您的代码的问题在于您假设input()函数返回一个整数。它没有,它返回字符串。改变这一行

playerResult = input("Type 1 for Rock, 2 for Paper or 3 for Scissors: ")

到此:

playerResult = int(input("Type 1 for Rock, 2 for Paper or 3 for Scissors: "))

使用int()函数将输入转换为整数。

答案 3 :(得分:0)

将修复问题,将用户输入转换为整数。

我还会添加一个检查来处理错误的输入casistic:

goodResult = False

playerResult = 0

while not goodResult:

    inp = input("Type 1 for Rock, 2 for Paper or 3 for Scissors: ")

    try:
        playerResult = int(inp)
        goodResult = (playerResult > 0 and playerResult < 4)

    except:
        goodResult = False