我在“艰难地学习python”中练习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)我不明白为什么会激活。在第6行中,我们写了bear_moved条件为False。因此,如果它是假的,而当它是真的时激活,它不应该激活!
b)我在IF和ELIF行中也遇到AND运算符问题。为什么我们要问bear_moved是否会改变价值?除了第33行之外,该块中没有其他指令会影响bear_moved(但该行会退出while)。
我不确定自己已经解释过了,如果我没有,请告诉我。谢谢你的回答,我是一个完整的新手。
答案 0 :(得分:2)
a)while
循环不会测试bear_moved
它测试True
,这总是正确的。
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
答案 1 :(得分:1)
while
循环执行其主体。 TRUE
总是如此,所以它是一个无限循环。
答案 2 :(得分:1)
a)它说While True
不是While bear_moved
,True
是一个常量,所以这个while循环将永远存在。
b)因为while循环会一直持续,所以一些答案(“taunt bear”)可以改变bear_moved
执行此功能将继续提问,直到您死亡或gold_room()
被执行。
编辑:使用die我的意思是执行dead()
函数,而不是你自己会死,我真的希望你在学习Python的同时保持身体健康: - )< / p>
答案 3 :(得分:1)
a)我不明白为什么会激活。在第6行中,我们写了bear_moved条件为False。因此,如果它是假的,而当它是真的时激活,它不应该激活!
此While True
构造会创建无限循环。这将循环,直到发生break
语句或其他控制流更改语句。
b)我在IF和ELIF行中也遇到AND运算符问题。为什么我们要问bear_moved是否会改变价值?除了第33行之外,该块中没有其他指令影响bear_moved(但该行退出时间)。
您提供的代码似乎可以模拟以下情况:用户被困在房间里,有熊。他们需要输入正确的动作,让熊离开门,然后他们需要离开门。
无限while循环保持如果用户提供的输入不会更改控件(函数dead(...
或gold_room()
),则程序将再次等待输入。
最初,熊没有移动,所以bear_moved
是假的。当用户输入taunt bear
时,这将使熊离开门,使bear_moved
成立。此时,如果用户尝试再次taunt bear
,那么熊将会杀死他们。但是,如果用户在他们嘲笑熊一次后输入open door
,他们就会移到下一个房间。
答案 4 :(得分:0)
a)我不明白为什么会激活。在第6行中,我们写了bear_moved条件为False。所以如果它是假的,而当它是真的时激活它,它不应该激活!
而True只是意味着无限循环直到休息。
每次while循环开始时,都会检查True是否为True(很明显是),所以它会永远循环(再次,或直到休息)。
bear_moved是一个与while循环执行无关的变量。