Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-你能为我解释一下这个while循环吗?_Python_Python 3.x - Fatal编程技术网

Python-你能为我解释一下这个while循环吗?

Python-你能为我解释一下这个while循环吗?,python,python-3.x,Python,Python 3.x,有人能帮我理解一下while循环的逻辑吗? 定义了bear_room()。熊在门前,以熊_moved=False开头。我不明白为什么循环需要以while True开头:。bear_room()以False开头,那么为什么代码会进入循环开始呢?循环不应该以while False开始吗(我也试过了)?在我看来,这种逻辑似乎是倒退的。我尝试删除while循环,只是请求用户输入 这只是代码的一部分,所以请忽略对其他函数的调用 def bear_room(): print ("There is a

有人能帮我理解一下while循环的逻辑吗? 定义了bear_room()。熊在门前,以熊_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
仅仅意味着while循环将永远重复,直到有东西打破它。因为
True
将始终为True,所以它将继续运行

我不明白这应该在哪里打破,所以这只是你的决定


编辑:其他人指出的一点是,如果您确实想在不进行
中断
调用的情况下退出循环,那么只需将
while
循环的条件设置为
while bear\u moved==false
。这样,当熊移动并将
bear\u moved
设置为
True
时,while循环将停止运行。

while True将永远循环,因为我看不到代码中有任何中断。也许我误解了代码,但我看不出与bear_room()有任何关系,而True:意味着永远运行循环,或者直到遇到
中断。值
True
与变量
bear\u moved
无关。当前循环将永远运行,除非被调用函数之一中存在
sys.exit()
,因为没有“中断”。

您可能会觉得
while True:
表示“在此循环之前定义的最后一个变量为True”。然后您会期望循环永远不会执行,因为
bear\u moved
不是真的。但这不是
的工作方式,而True:
的工作方式。它根本不关心
bear_moved
的状态。如果你想让循环继续,只要移动的熊是假的,你就需要在移动熊时执行
操作==False
。while condition:重复,直到没有任何metI-guess方法
死亡
将负责打破循环。我也会这样假设!:但是你不能打断一个循环,除非你直接在循环中。如果
dead
调用
break
,那将是一个
语法错误:“break”外部循环
。我猜
dead
可以调用
sys.exit
,但这与其说破坏了循环,不如说破坏了整个程序。他说忽略方法调用,但那是真的。我只是使用break作为在循环中使用的示例