为什么我的代码没有正确处理它会一直返回错误的行?

时间:2017-11-15 14:07:34

标签: python random

如果计算机随机选择某个字母,它应该返回某一行,但它只选择一个实例反复重复,即使满足要打印的另一个句子的条件。

poll()

此代码返回以下结果:

import random
Player_Score = 0
Computer_Score = 0
while Player_Score < 5 or Computer_Score < 5:
    Player_object = input("Would you like to choose R, P, or S?")
    Computer_object = str(random.sample(set(["R", "P", "S"]), 1))
    if Player_object == "R" or Player_object == "r":
        if str(Computer_object) == "R":
             print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have tied with the Computer and neither of you have scored a point.")
        elif str(Computer_object) == "P":
            Computer_Score = Computer_Score + 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ". You have been beaten by the Computer and it has scored a point.")
        else:
            Player_Score = Player_Score + 1
            print("You have chosen " +Player_object+ " and the Computer chose " +str(Computer_object)+ ".You have beaten the Computer scored a point.")

1 个答案:

答案 0 :(得分:3)

str(random.sample(set(["R", "P", "S"]), 1))返回"['S']",而不是'S',因此您的代码始终会返回其他条件。

相反,请尝试random.sample("RPS", 1)[0],它将返回列表的第一个(也是唯一的)元素或使用random.choice('RPS')