真实& Python中的False布尔值

时间:2013-09-05 20:15:47

标签: python python-2.7

bear_moved = False 

while True: 
    next = raw_input("> ") 

    if next == "take honey": 
        dead("The bear looks at you then slaps your face off.") 
    elif next == "taunt bear" and not bear_moved: 
        print "The bear has moved from the door. You can go through." 
        bear_moved = True 
    elif next == "taunt bear" and bear_moved: 
        dead("The bear gets pissed off and chews your leg off.") 
    elif next == "open door" and bear_moved: 
        gold_room() 
    else: 
        print "I got no idea what that means. 

这是为了表明我对布尔的理解。在测试next == "taunt bear" and not bear_moved中,如果我的输入为taunt bear,则结果为True and True,这将继续循环。

令我困惑的是线路测试next == "taunt bear" and bear_moved。如果我的输入为taunt bear,那么它是"taunt bear" == "taunt bear"bear_movedTrue and True吗?这意味着循环将继续而不是取消它。

2 个答案:

答案 0 :(得分:0)

while True:将无限期地继续(除非你输入break - 通常break是像Python这样的语言中的糟糕设计)。

您可能想要这样做:

while something == True: #Or - as has been pointed out, `while something` - which is equivalent and more Pythonic
    ...
    some code which eventually sets something to False
    ...

答案 1 :(得分:0)

python中的

elifelse if等效。如果其中一个elif块执行,则其他任何一个都无法执行,并且会跳到if的底部。

执行next == "taunt bear" and not bear_moved并计算为真,并执行该程序后,程序的控制将继续回到循环的前面,并再次请求输入。