[英]While or loop not stopping after set integer in python
尝试与精通计算机的玩家一起制作石头剪刀布游戏以更新编码知识,但是我似乎无法在我的 while 循环中找到导致问题的原因。 我将它设置为在计算机或人达到 3 分时完成,但在总分等于 8 时停止。下面列出了完整代码
import random
rock = "rock"
paper = "paper"
scissors = "scissors"
humanscore = int(0)
compscore = int(0)
limit = int(3)
comp = ["paper", "rock", "scissors"]
while humanscore <= limit or compscore <= limit:
human = str(input("Choose rock, paper, or scissors, first to 3 wins! "))
answer = random.choice(comp)
if human == answer:
print("Tie, Computer chose, ", answer)
if answer == rock:
if human == paper:
humanscore += 1
print("You Win!")
elif human == scissors:
compscore += 1
print("Computer Won! Try again")
if answer == paper:
if human == rock:
compscore += 1
print("Computer Won! Try again")
elif human == scissors:
humanscore + 1
print("You Win!")
if answer == scissors:
if human == paper:
compscore += 1
print("Computer Won! Try again")
elif human == rock:
humanscore += 1
print("You Win!")
print("\n Computer Chose: ", answer, "computer score: ", compscore, "Human Score:", humanscore)
正如评论中已经说过的or
,问题出在您的休息条件下。 只要其中一个分数低于或等于 3,它就会继续运行。
例如,如果humanscore = 3 和comp score = 2,则条件的两个部分都是真实的,这意味着它会继续。
一旦humanscore = 4 和compscore = 4,humanscore <= 3 和compscore <= 3 都评估为false,这意味着它停止=> 总分为8。
因此,while 应该如下所示(也应该是<
而不是<=
,因为你想在一个有 3 个点时立即停止):
while humanscore < limit and compscore < limit:
一旦你理清了循环——如果你只想在分数都低于limit
的情况下继续前进,根据 schilli 的回答进行更正——你可能想考虑一个数据结构建议:
制作一个记录什么选择胜过给定选择的dict
:
whatBeats = {rock:paper, paper:scissors, scissors:rock}
# then later after choices are made...
if answer == whatBeats[human]:
# computer win
elif human == whatBeats[answer]:
# human win
else:
# draw
(几十年前,我在了解任何索引结构之前编写了一个排序程序——比如 arrays——你当前的方法让我想起了那种努力)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.