用最难的方式学Python,第35练习
我在“Learn Python the Hard Way”这本书的第35个练习中遇到了一些问题。
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:
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 it now."
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."
a) 我不明白为什么While会被激活。在第6行我们写了bear_moved的条件是False。所以如果它是False,而While在True的时候才会激活,那它就不应该被激活啊!
b) 我在IF和ELIF行中的AND运算符也有问题。我们为什么要问bear_moved的值是否改变了呢?在这个代码块中,除了第33行,其他的指令都没有影响bear_moved(而且那一行会退出while循环)。
我不确定我有没有解释清楚,如果没有请告诉我。谢谢你们的回答,我还是个完全的新手。
5 个回答
while
循环会在条件为真的时候一直执行里面的内容。TRUE
这个条件永远为真,所以这个循环会一直不停地执行下去,形成一个无限循环。
a) 我不明白为什么While会激活。在第6行我们写了bear_moved的条件是False。所以如果它是False,而While在True时激活,那它就不应该激活啊!
这个While True
的结构会创建一个无限循环。这个循环会一直进行,直到出现break
语句或者其他改变控制流程的语句。
b) 我在IF和ELIF行的AND运算符上也有问题。为什么我们要问bear_moved的值是否改变了呢?在这个代码块中,除了第33行,没有其他指令会影响bear_moved(但那一行会退出while)。
你提供的代码似乎模拟了以下情况:用户被困在一个房间里,里面有一只熊。他们需要输入正确的动作,让熊离开门口,然后才能出去。
这个无限的while循环保持着,如果用户输入的内容没有改变控制(比如函数dead(...
或gold_room()
),那么程序会再次等待输入。
一开始,熊没有移动,所以bear_moved
是false。当用户输入taunt bear
时,这会让熊离开门口,变成bear_moved
为true。此时,如果用户再次尝试taunt bear
,熊就会杀了他们。不过,如果用户在嘲弄熊一次后输入open door
,他们就会进入下一个房间。
a) 这个while
循环并不是在检查bear_moved
,而是在检查True
,而True
永远都是对的。
b) 这里的区别是,你只能移动熊一次,第二次移动就会出事。这是为了区分不同的情况。不过我觉得这样写不太好,应该有更好的写法。
elif next == "taunt bear":
if bear_moved:
dead("The bear gets pissed off and chews your leg off.")
else:
print "The bear has moved from the door. You can go through it now."
bear_moved = True