为什么这个简单的“石头-布-剪刀”程序不能在Python中工作?

2024-04-20 10:05:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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")

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

^{pr2}$

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


Tags: and程序youforifcomputerpaperprint
3条回答

这应该可以解决它

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

因为playerResultstr,而{}是{}。比较string和int总是得到False

改变

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

^{pr2}$

代码的问题是假设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()函数,可以将输入转换为整数。在

相关问题 更多 >