学习 Python 艰难之路 ex35 熊屋

Learn Python the Hard Way ex35 Bear Room

在我继续之前,我试图理解 Learn Python The Hard Way example 35 问题中的一段特定代码。

按照本书的要求,我一直在几乎每一行(或每一块)代码上方写评论,以分解正在发生的事情,这样我就可以测试我对正在发生的事情的理解。

我在 while 循环中使用了一些分支逻辑时遇到了一些麻烦,我将 post(我正在 posting 一个应该有帮助的修改版本展示我一直在做什么以确保我理解事物)。

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 # default status of bear


while True:
    bear_loop_counter = 0
    choice = input("bear room input>  ")

    if choice == "take honey":
        dead("The bear looks at you and 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_loop_counter += 1
        print("The bear room loop has iterated",bear_loop_counter, "time.")
        bear_moved = True
    elif choice == "taunt bear" and bear_moved:
        dead("The bear gets pissed off and chews your leg off.")
    elif choice == "open door" and bear_moved:
        gold_room()
    else:
        print("I got no idea what that means")

如您所见,我实现了一些用于调试的东西,包括将输入提示更改为显示我正在处理的代码块的内容,以及显示我通过循环的次数的计数器做了。

我正在尝试理解以下代码片段:

elif choice == "taunt bear" and not bear_moved

我知道这个 while 循环基本上是在等待您进入将退出循环的分支之一(dead() 或 other_room() 位之一)。我也知道熊的默认 "status" 是 "not_moved" 并且 "taunt_bear" 分支会改变熊的状态。不过,我没有得到那段代码的 "and not" 部分。

我的理解是:

bear_moved = False

在我看来,这意味着 "and not bear_moved" 将被解释为 "and not bear_moved(False)",如果您要简化该逻辑,则又会读作 "and bear_moved(True)"。所以,用简单的英语写成,"If your choice is to taunt the bear, AND the bear IS MOVED, execute some print statements... increment the counter, etc." 显然这不是代码的工作方式。我可以从我的计数器和 运行 程序中看到 "and not" 语句没有像我刚才解释的那样工作。

我想我是在假设 bear_moved 在我编写代码时被我设置为 False 的情况下操作的。如果 bear_moved 被 Python 假定为 True 或其他什么,我可以理解它在做什么。我在想:

bear_moved = False

因此:

not bear_moved == True

这就是我要澄清的问题。

提前致谢。

这里,not bear_moved表示bear_movedFalse

引用 the python doc:

The operator not yields True if its argument is false, False otherwise.

要使分支继续进行,语句必须在其条件下为真。

如果您输入嘲讽熊,则表示第一个为真。

在第二部分('and' 的另一边)'not bear_moved' 这也必须计算为真。布尔值表示如果 bear 为假且使用 'not' 则变为真。基本上是 bear = true 。

现在分支有 2 个正确。

认为熊已经移动,造成混乱。实际上,这只是一个变量,您可以在其中存储 false 一词,直到您更改它为止。分支机构想要的只是一所干净的房子来进步。不将假变为真。