Python嵌套递归调用下check_input函数偶现返回None的原因咨询
递归函数未返回值导致的None返回问题
嘿,这个坑我之前踩过!咱们来一步步拆解问题:
问题根源
你遇到的问题核心是递归调用时没有返回递归函数的结果。看你的代码:
当首次输入错误时,代码会进入else分支,打印提示后调用check_input(...)递归获取输入,但这个递归调用的返回值并没有被传递回最初的函数调用。
也就是说:
- 第一次输入错误:执行
else里的打印,然后触发递归调用 - 递归的那次调用输入正确,返回了1或2,但这个值只停留在上一层的
else分支里,没有被return出去 - 最初的
check_input函数执行完else里的代码后,没有任何return语句,Python函数默认会返回None,所以decision最终拿到的是None
修复方案
只需要在递归调用前加上return,把递归的结果传递回去就行:
def check_input(input_message, option1, option2): response = input(input_message + ":\n").lower() if int(response) == option1: return 1 elif int(response) == option2: return 2 else: print_pause("I'm sorry I don't recognize that response. Try again!", 2) # 加上return,将递归调用的结果返回给上层函数 return check_input(input_message, option1, option2) decision = check_input("Please type 1 to go into the dark cave. 2 to go into the dwelling", 1, 2)
更稳妥的替代方案:用循环代替递归
其实这类输入校验的场景,用循环比递归更直观,也不容易出现这种返回值遗漏的问题,比如:
def check_input(input_message, option1, option2): while True: response = input(input_message + ":\n").lower() if int(response) == option1: return 1 elif int(response) == option2: return 2 else: print_pause("I'm sorry I don't recognize that response. Try again!", 2) decision = check_input("Please type 1 to go into the dark cave. 2 to go into the dwelling", 1, 2)
内容的提问来源于stack exchange,提问作者i_feel_dumb
相关产品推荐
相关产品推荐

