[英]Python while loop continues even when false (even if variable declared global)
我在 python 中有一个 while 循环,它在 false 时不会停止,但与其他问题不同的是,我遇到堆栈溢出时,我声明了我的全局变量。
import random
score = 0
health = 75
maxhealth = 100
keys = 0
health_potions = 0
skip_stage = 1
cmd = ""
inc = 0
def hiahelp():
#code
def stats():
#code
def oCmds():
global cmd
global inc
global health
if cmd == "stats":
stats()
inc = 0
elif cmd == "help":
hiahelp()
inc = 0
elif cmd == "use health potion":
#healing code
elif cmd == "use":
print("incomplete command")
else:
inc = 1
#intro code
while health > 0:
#more intro code
print("What is HungryIronApple's favorite music artist (besides himself, include proper capitalization)?")
def stage1():
r = True
while r:
global inc
global cmd
global health
if inc == 1:
print("incorrect, try again")
health = health - 10
cmd = input("answer: ")
if cmd == "Alan Walker":
inc = 0
r = False
elif cmd == "left" or cmd == "right":
print("originally I would take health away for such a dumb mistake but because we are just getting started, I'll ignore it")
else:
oCmds()
stage1()
print("the door opens")
quit()
print(f"you died {username}")
我希望它在我死后停止,但它继续询问答案。 有人可以解释一下吗? 请注意我几乎不使用标签注释,它们只是替代品。 下面是运行代码的示例:
您的 while 循环受health
值的约束。 循环中唯一一次health
发生变化是 if inc == 1
。
鉴于您的代码片段,不可能说inc
在您的循环中是否发生过变化(我确实看到了#more code
,所以我猜那里有什么东西?)。 因为它从 0 开始并且永远不会改变,所以health
也永远不会改变。
要对此进行调试,请查看inc
和health
的值并跟踪它们随时间的变化。 它还可以帮助您暂时将while health > 0
的迭代更改为for x in range(100)
以便您限制重复并可以调试health
和inc
值变化中的模式。
很明显inc
设置为0
,然后health
根本没有被修改。
因此, while
循环条件永远不会中断。
global
语句是多余的,在 python 中,作用域被限制为 3 种可能性(全局、局部、非局部)。 不像 C,每个块都有自己的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.