【问题标题】:Python - Can you explain this while-loop for me?Python - 你能为我解释一下这个while循环吗?
【发布时间】: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


【解决方案1】:

while True 只是意味着 while 循环将永远重复,直到有东西破坏它。因为True 永远是真的,所以它会继续下去。

我不明白这应该在哪里中断,所以这只是你的电话!

编辑:其他人指出的是,如果您真的想在没有break 调用的情况下退出循环,那么只需将while 循环的条件设置为while bear_moved == false。这样当熊移动并将bear_moved设置为True时,while循环将停止运行。

【讨论】:

  • 我猜方法 dead 将负责打破循环。
  • 我也这么认为! :D
  • 但是除非你直接在循环内,否则你不能打破循环。如果dead 调用break,那将是SyntaxError: 'break' outside loop。我猜dead 可以调用sys.exit,但这并没有破坏循环,而是破坏了整个程序。
  • 他说忽略方法调用,但那是真的。我只是以break为例,在循环内使用
【解决方案2】:

While True 将永远循环,因为我在代码中看不到任何中断。也许我误解了代码,但我看不到与 bear_room() 的任何关系

【讨论】:

  • While 条件:重复直到条件不满足
【解决方案3】:

while True: 意味着永远运行循环,或者直到遇到break。值True 与变量bear_moved 无关。您当前的循环将永远运行,除非 sys.exit() 存在于被调用函数之一中,因为没有“中断”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 2010-09-15
    • 2015-11-27
    相关资源
    最近更新 更多