首页 > 解决方案 > 在 Python 中重复测试用例后 if 子句不会改变输出

问题描述

我有以下场景:我必须根据大爆炸理论的石头剪刀布蜥蜴斯波克游戏用 Python 编写代码。我以为我已经非常正确地理解了代码的结构,但是在测试时,我尝试通过输入 3 作为测试用例的数量,然后在第一轮中输入“纸摇滚”来制作一个输赢的场景,第二个是“蜥蜴剪刀”,第三个是“Spock Spock”​​。问题是预期的结果应该是赢 - 输 - 平,但在所有这些输出中都是赢。谁能帮我找出我在这里缺少什么?谢谢!

T = int(input("Enter the number of desired test cases from 1 to 100: "))

Win = Lose = Tie = False

for i in range(T):
    Sheldon, Raj = input("Enter Sheldon's and Raj's plays: ").split(' ')

    if(Sheldon == Raj):
        Tie = True
    elif((Sheldon == "rock" and (Raj in ["scissors","lizard"])) or
         (Sheldon == "paper" and (Raj in ["rock","Spock"])) or
         (Sheldon == "scissors" and (Raj in ["paper","lizard"])) or
         (Sheldon == "Spock" and (Raj in ["rock","scissors"])) or
         (Sheldon == "lizard" and (Raj in ["paper","Spock"]))
        ):
        Win = True
    else:
        Lose = True

    if(Win == True):
        print("Case #{0}: Bazinga!".format(i+1))
    elif(Lose == True):
        print("Case #{0}: Raj cheated!".format(i+1))
    elif(Tie == True):
        print("Case #{0}: Again!".format(i+1))

标签: pythonpython-3.xif-statement

解决方案


您必须在每次迭代结束时使 all(Win, lost and Tie) = False,这样循环每次都会重新开始。

您可以使用 if(Win) 而不是 if(Win == True) 因为 if 语句只会在条件为 True 时执行。

T = int(input("Enter the number of desired test cases from 1 to 100: "))

Win = Lose = Tie = False
for i in range(T):
    Sheldon, Raj = input("Enter Sheldon's and Raj's plays: ").split(' ')

    if(Sheldon == Raj):
        Tie = True
    elif((Sheldon == "rock" and (Raj in ["scissors","lizard"])) or
         (Sheldon == "paper" and (Raj in ["rock","Spock"])) or
         (Sheldon == "scissors" and (Raj in ["paper","lizard"])) or
         (Sheldon == "Spock" and (Raj in ["rock","scissors"])) or
         (Sheldon == "lizard" and (Raj in ["paper","Spock"]))):
        Win = True
    else:
        Lose = True

    if(Win):
        print("Case #{0}: Bazinga!".format(i+1))
    elif(Lose):
        print("Case #{0}: Raj cheated!".format(i+1))
    elif(Tie):
        print("Case #{0}: Again!".format(i+1))

    # Again make all false on each iteration
    Win = Lose = Tie = False

推荐阅读