我仍在学习python,所以让我很幽默。我正在尝试进行文本冒险,将其作为一种学习的方式,并且正在尝试实现一种方式,使玩家能够响应提示,提示要进行“交互”的事物列表(从嵌套词典中返回字符串)。我正在尝试使程序打印“ self.location [“ interper”]“”的值。
这是给我一些问题的代码。
# give the player the ability to "talk" and touch things
# if there is nothing to interact with, say that there is nothing
if "interobj" not in self.location and "interper" not in self.location:
dismiss_fx.play()
print("There's nothing of interest here.")
# proceed if there is
else:
# print the things that are in the room
confirm_fx.play()
print("In the area, these things stand out to " + self.name + ": ")
if "interobj" in self.location:
print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + self.location["interobj"])
if "interper" in self.location:
print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + self.location["interper"])
# prompt the user to interact with one of the things
interaction = input(colorama.Fore.CYAN + colorama.Style.BRIGHT + "\nWhich do you want " + self.name + " to interact with?: ")
# determine if the thing the user interacted with is in the location
try:
raise KeyError(interaction)
except KeyError as e:
if str(e) != self.location["interobj"]:
raise
elif interaction == self.location["interobj"]:
# return whatever was noteworthy about the object
confirm_fx.play()
print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + self.location["intercom"])
print("")
checkprog(self,interaction)
except KeyError as e:
if str(e) != self.location["interper"]:
raise
elif interaction == self.location["interper"]:
# return whatever the character had to say
confirm_fx.play()
print(colorama.Fore.YELLOW + colorama.Style.BRIGHT + self.location["intersay"])
print("")
checkprog(self,interaction)
except KeyError:
# input is invalid
invalid_fx.play()
print(self.name + " couldn't find a '" + interaction + "'.")
print("")
这应该做的是:
实际上,它只是告诉我,我处理异常的方式正在创建更多的异常。
TL; DR:有人可以以一种易于理解的方式解释异常处理吗?我不了解“筹款”功能。如果可以帮助我,请提前谢谢。
答案 0 :(得分:0)
使用try:
块时,正在检查该块中的代码是否引发异常(有错误)。如果有异常,解释器将立即跳转到except块并在那里执行代码。如果没有异常,则解释器仅执行try:
块中的代码,然后移至except
块之后的行。当您在try块中调用raise
时,您正在这样做,以便即使您的代码正常工作,也会引发“异常”,因为raise函数会自动引发异常。您只想将普通代码放在try块中而不用引发,如果有异常,它将在except块中处理它。