Python函数调用问题:输入no后return menu()未生效如何修复?
问题代码
def thing(): e = input("Are you sure you want to enter this menu?") if e == "yes": while True: placeholder() elif e == "no": return menu() #<-- 此处未达到预期效果 else: print("invalid response") def menu(): print(""" what do you want to do? 1. Enter thing 2. Don't enter thing """) ans = input("Enter your response here:\n") if ans == "1": thing() elif ans == "2": pass else: print("invalid response")
问题原因
当在thing()中输入"no"时,return menu()会调用menu(),但执行完这个menu()后,程序会回到最初调用thing()的那个menu()函数上下文,而该上下文已经执行完thing()调用,没有后续代码,因此程序直接终止。
修复方案
方案一:调整函数调用逻辑
修改thing()函数,直接调用menu()后退出当前函数,而非通过return调用:
def thing(): e = input("Are you sure you want to enter this menu?") if e == "yes": while True: placeholder() elif e == "no": menu() return else: print("invalid response") thing() # 输入无效时重新询问 def menu(): print(""" what do you want to do? 1. Enter thing 2. Don't enter thing """) ans = input("Enter your response here:\n") if ans == "1": thing() elif ans == "2": pass else: print("invalid response") menu() # 输入无效时重新显示菜单 # 启动程序 menu()
方案二:用循环管理主流程(推荐)
给menu()添加循环,确保用户退出前菜单持续可用,同时简化thing()的返回逻辑,避免递归嵌套:
def thing(): e = input("Are you sure you want to enter this menu?") if e == "yes": while True: placeholder() elif e == "no": return # 直接返回,回到menu的循环 else: print("invalid response") thing() def menu(): while True: print(""" what do you want to do? 1. Enter thing 2. Don't enter thing """) ans = input("Enter your response here:\n") if ans == "1": thing() elif ans == "2": print("退出程序") break # 退出循环,结束程序 else: print("invalid response") # 启动程序 menu()
说明
方案二的循环方式更易维护,避免了递归调用可能导致的栈溢出问题,流程逻辑更清晰,用户选择"no"后会回到持续运行的菜单循环中,不会出现程序终止的情况。
内容的提问来源于stack exchange,提问作者aether86
相关产品推荐
相关产品推荐

