2
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_moved哪个是True and True?这意味着循环将继续而不是取消它。

4

2 回答 2

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
    ...
于 2013-09-05T20:23:51.460 回答
0

elif在 python 中相当于else if. 如果其中一个elif块执行,其他块都不能,并且会跳到if.

Afternext == "taunt bear" and not bear_moved被执行并评估为真,并且块执行,程序的控制继续回到循环的前面,并将再次要求输入。

于 2013-09-05T20:28:37.620 回答