Python递归搭配while循环输入no第二次无法跳出循环是什么原因
问题原因
- 你的代码通过递归调用
hello()实现流程重启,实际会产生多层while True循环嵌套,而break语句仅能跳出当前所在层级的循环,无法作用于外层循环,具体执行逻辑如下:- 初始运行
hello()时,程序进入第一层while循环,等待用户输入 - 第一次输入
yes后触发递归调用,程序进入第二层hello()函数的while循环,再次等待输入 - 此时输入
no,触发的break只会跳出第二层while循环,程序回退到第一层while循环的执行逻辑,因此会再次弹出输入询问 - 第二次在第一层循环中输入
no,才会触发第一层的break,程序正常退出
- 初始运行
修复方案
推荐优先去掉递归调用,改用单层循环实现需求,逻辑更简洁,也不会有递归栈溢出风险:
import time def hello(): while True: print("hello") answer = input("what do u wanna do") if answer == "yes": # continue直接回到循环开头,重新执行print("hello")和输入逻辑,等价于原需求的重启流程 continue elif answer == "no": input("Press Enter To Close") print("bye") time.sleep(1) break else: print("I didn't understand that") hello()
如果要保留原递归逻辑,也可以在递归调用结束后直接跳出当前层循环:
def hello(): print("hello") while True: answer = input("what do u wanna do") if answer == "yes": hello() # 递归返回后直接跳出当前层循环,避免回到外层循环继续等待输入 break elif answer == "no": input("Press Enter To Close") print("bye") import time time.sleep(1) break else: print("I didn't understand that") hello()
内容的提问来源于stack exchange,提问作者William Yar
相关产品推荐
相关产品推荐

