python - 在 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))
解决方案
您必须在每次迭代结束时使 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
推荐阅读
- jenkins-pipeline - 詹金斯插件没有安装
- python - sklearn随机森林查找所选特征的分数
- css - React Native Align Self Flex End 未按预期工作
- powershell - 如何使用 powershell 将此文本文件输出为表格格式?
- reactjs - 您可以使用 this.props.history.push 将道具传递给与路径名不同的组件吗?
- c - 为什么使用指向结构的指针而不是直接使用结构(C)
- docker - Docker镜像rstudio/rstudio-server-pro挂载持久化配置目录时无法运行容器实例
- c++ - 如何进行矩阵*向量乘法并将此结果传递给 R 中 TMB 中的向量?
- java - 如何使用 Java API 列出 Kafka 集群中的所有可用代理?
- typescript - 打字稿:使用解构缩小类型