我在“学习Python困难之路”一书中练习35,我似乎无法弄清楚这个错误。这可能是愚蠢的事情,但我似乎无法弄明白。
错误在第75,69和26行,模块start(),start bear_room()和bear_room next2 = raw_input(“>”)
from sys import exit
def gold_room():
print "This room is full of gold. How much do you take?"
next1 = raw_input("< ")
if "0" in next1 or "1" in next1:
how_much = int(next1)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print "Nice you're not greedy, you win!"
exit(0)
else:
dead("You greedy bastard!")
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:
next2 = raw_input("> ")
if next2 == "take honey":
dead("The bear looks at you then pimp slaps your face off.")
elif next2 == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next2 == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your crotch off.")
elif next2 == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
def cthulu_room():
print "Here you see the great evil Cthulu."
print "He, it, whatever stares at you and you go insane."
print "Do you flee for your life of eat your head?"
next3 = raw_input("> ")
if "head" in next3:
dead("Well that was tasty!")
elif "flee" in next3:
start()
else:
cthulu_room()
def dead(why):
print why, "Good job!"
exit(0)
def start():
print "You are in a dark room."
print "There is a door to your right and left."
print "Which one do you take?"
next4 = raw_input("> ")
if next4 == "left":
bear_room()
elif next4 == "right":
cthulu_room()
else:
dead("You stumble around the room until you starve.")
start()
答案 0 :(得分:0)
我没有遇到您的具体错误,但很难说我是否根据您的描述。将来,您应该使用行异常发布堆栈跟踪。
我发现你的代码中有一个无限循环。这部分:
while True:
next2 = raw_input("> ")
if next2 == "take honey":
# snip
永远不会退出。 True将始终为True,因此它会一直提示您使用raw_input。通过将该函数的其余部分更改为这样......
while True:
next2 = raw_input("> ")
if next2 == "take honey":
dead("The bear looks at you then pimp slaps your face off.")
elif next2 == "taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved = True
elif next2 == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your crotch off.")
elif next2 == "open door" and bear_moved:
gold_room()
else:
print "I got no idea what that means."
...我们告诉Python将存储在next2中的提示结果,并评估其余的检查。这样,它将通过调用其他函数(例如dead()或gold_room())来退出函数。这将退出bear_room()函数,即使while True条件从未退出。当条件计算为False时退出循环。因为True永远不会等于False,所以我们必须退出其他方式,例如调用另一个函数,如dead(),它将通过调用exit()来终止。