从头开始学习python

时间:2019-09-25 18:39:07

标签: python

我正在从头学习python。我为剪刀石头布游戏编写了一个小代码。其中1条输入来自用户,另一条输入来自PC,使用随机库。我知道我的代码并不完美。但是当我尝试测试我的代码时,我不了解一件事。

这是我的代码。

import random
from time import sleep
print("Let's play the game")

print("For Rock Choose 1")
print("For Paper Choose 2")
print("For Scissors Choose 3")


a = int(input("Enter the number "))

if a == 1:
    print("You Choose Rock")
elif a == 2:
    print("You Choose Paper")
elif a == 3:
    print("You Chosse Scissors")
else:
    print("Invalid Input")

print ("Now taking input from PC")
sleep (3)

b = random.randint(1,3)
if b == 1:
    print("PC has given Rock")
elif b == 2:
    print ("PC has given Paper")
elif b==3:
    print ("PC has given Scissors")

if a == b:
    print ("Match Tie")
elif a ==1 & b == 3:
    print ("You Win")
elif a == 2 & b == 1:
    print ("You Win")
elif a == 3 & b == 2:
    print ("You Win")
else:
    print ("You Loose")

您可以清楚地看到我选择了2,PC选择了1。然后我得到的输出是“ You Loose”,如果a == 2和b == 1打印(“ You Win” )

在测试此代码(图像的选定代码)时,我发现了一件事,感到很困惑。

2 个答案:

答案 0 :(得分:2)

您需要使用and而不是&

在Python中,&bitwise operator,而您想使用conditional

if a == b:
    print ("Match Tie")
elif a ==1 and b == 3:
    print ("You Win")
elif a == 2 and b == 1:
    print ("You Win")
elif a == 3 and b == 2:
    print ("You Win")
else:
    print ("You Loose")

答案 1 :(得分:2)

您正在使用位运算符。拥有1和2的&

1 = 00001
2 = 00010

1 & 2 = 0

您应该使用and而不是&