【发布时间】:2018-02-02 14:34:33
【问题描述】:
有人可以帮我理解这个while循环中的逻辑吗? bear_room() 已定义。熊在门前,以 bear_moved = False 开头。我不明白为什么循环需要以 while True: 开头。 Bear_room() 以 False 开头,那么为什么代码会进入循环开始呢?循环不应该以 while 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.")
【问题讨论】:
-
您可能认为
while True:的意思是“而在此循环之前定义的最后一个变量为真”。然后你会期望循环永远不会执行,因为bear_moved不是 True。但这不是while True:的工作方式。它根本不关心bear_moved的状态。如果您希望循环在bear_moved为 False 时继续,您需要执行while bear_moved == False。
标签: python python-3.x