有人可以帮我理解这个while循环中的逻辑吗? bear_room()已定义。熊在熊门前以熊_moved = False开头。我不明白为什么循环需要以True开头: bear_room()从False开始,为什么代码会进入循环开始?不应该循环开始而False(我也尝试过)?这个逻辑对我来说似乎是倒退的。我尝试删除while循环,只是要求用户输入。
这只是代码的一部分,所以请忽略对其他函数的调用......
def bear_room():
print ("There is a bear here.")
print ("The bear has a bunch of honey.")
print ("The fat bear is in front of another door.")
print ("How are you going to move the bear?")
bear_moved = False
while True:
choice = input("> ")
if choice == "take honey":
dead("The bear looks at you then slaps your face off.")
elif choice == "taunt bear" and not bear_moved:
print ("The bear has moved from the door.")
print ("You can go through it now.")
bear_moved = True
elif choice == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your legs off.")
elif choice == "open door" and bear_moved:
gold_room()
else:
print ("I got no idea what that means.")
答案 0 :(得分:2)
while True
只是意味着while循环将永远重复,直到某些东西破坏它。因为True
永远都是真的,所以它会继续下去。
我不明白应该在哪里打破,所以这只是你的电话!
编辑:其他人指出的是,如果你真的想要在没有break
调用的情况下逃避循环,那么只需将while
循环的条件设置为while bear_moved == false
即可。这样当熊移动并将bear_moved
设置为True
时,while循环将停止运行。
答案 1 :(得分:0)
While True将永远循环,因为我没有看到代码中的任何中断。也许我误解了代码,但我没有看到与bear_room()的任何关系
答案 2 :(得分:0)
while True:
表示永远运行循环,或者直到遇到break
。值True
与变量bear_moved
无关。你的当前循环将永远运行,除非其中一个被调用函数中存在sys.exit()
,因为没有'break'。