Skip to main content
 首页 » 编程设计

python之关于 boolean 运算符和 while 循环的理解困难

2025年05月04日15EasonJim

我正在研究“艰难地学习 Python”,并且对 while 循环和 boolean 运算符有一点理解上的问题。

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 = raw_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. 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 leg off.") 
        elif choice == "open door" and bear_moved: 
            gold_room() 
        else: 
            print "I got no idea what that means."  

我一输入“taunt bear”,脚本就会转到下一个“步骤”。然后我可以输入“open door”并继续下一个功能。

但是,while 循环是否应该一直运行直到出现false?在“ mock 熊”之后发生的事情是 bear_moved 被设置为 True。那下一步怎么走。此外,我不理解 and not bear_moved 语句。不应该将 bear_moved 设置为 false 吗?但它已经设置为 false。这让我很困惑。

感谢任何解释。

请您参考如下方法:

But, should a while loop not run endless until something is false?

至少有两种方法可以停止无限循环(while True:)。一种方法是使用 break 语句。它会打破循环。另一种是使用exit函数。这将结束程序。查看dead函数的定义:

def dead(why): 
    print why, "Good job!" 
    exit(0) #this ends the program (therefor ends loop) 

What happens after the "taunt bear" is that bear_moved is set to True.

每当 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() 

How can it go on the next step then.

这是一个无限循环。它会一次又一次地循环这些选项,直到它中断或退出。

Furthermore, I do not understand the and not bear_moved statement. Shouldnt that set bear_moved to false? But it is already set to false

not bear_moved 只是否定 boolean 值。如果您执行 not True,您将得到 False。如果您执行 not False,您将得到 True。那是否定。这不会改变 bear_moved 的值。它只计算 if/elif 语句。

旁注:您似乎对 Python 很陌生。我建议先放慢速度,学习更多语言基础知识,然后再跳到更大的代码链。