Python函数自调用后无法正确返回,该如何修复?
解决文本冒险游戏prompt函数的返回问题
嘿,我来帮你搞定这个递归返回的小bug!你的prompt()函数现在的核心问题是:当玩家输入错误内容后,你虽然递归调用了prompt(),但没有把这个递归调用的返回值传递回去。这就导致不管递归里有没有成功返回"opening",程序都会继续走到函数末尾,返回那个错误的"this is wrong"。
问题代码分析
看你原代码的else分支:
else: print "For this game to work, you're going to have to get" print "the hang of hitting the right key." print "Let's try that again." prompt() # 这里只调用了函数,但没返回它的结果
当玩家输入错误后,执行这段代码时,调用了新的prompt(),但这个新调用的返回值并没有被返回给上一层函数。等递归完成后,程序会继续执行下面的return "this is wrong",所以就算玩家最后输入了"y",最终返回的还是错误信息。
修正后的代码
只需要在递归调用的时候加上return,把递归的结果传递回去就好了:
def prompt(): print "Hit 'Y' to begin." action = raw_input("> ").lower() if action == "y": return "opening" else: print "For this game to work, you're going to have to get" print "the hang of hitting the right key." print "Let's try that again." return prompt() # 这里加上return,传递递归的返回值 return "this is wrong" # 现在这个语句永远不会被执行到了,可以考虑删掉 ret = prompt() print ret
为什么这样改?
当你在else分支里写return prompt()时,当前函数会把递归调用prompt()的返回值直接返回给它的调用者。这样不管玩家输错多少次,只要最后输入了"y",这个正确的返回值就会一层一层传递回来,最终被赋值给ret,而不会走到最后的错误返回语句。
另外,现在最后的return "this is wrong"已经永远不会被执行到了,你可以选择删掉它让代码更简洁。
内容的提问来源于stack exchange,提问作者A.Wittkamp
相关产品推荐
相关产品推荐

