Python跨文件导入调用函数时输入no无法退出while循环问题
问题根因
bug不在fun_movies的内部循环里,出在main_menu.py的外层菜单循环:
- 你只在while循环启动前读了一次
option的输入值,循环跑起来之后从来没重新获取过用户的新菜单选择 - 你在
fun_movies()里输"no"的时候,其实已经正常跳出了函数内部的录入循环,函数会正常返回;但外层循环里option的值一直是你第一次输的1,循环判断option !=0永远成立,就会立刻再调一次fun_movies(),看起来就像输"no"根本没用、无限循环录电影 - 你单独跑
fun_movies的时候没有外层这个菜单循环,函数跑完进程就结束了,所以看起来功能正常
另外还有两个小问题会影响使用体验:
- yes/no的判断没做容错,用户要是不小心输了带空格、大小写不对的内容(比如" no"、"NO"、"Yes "),都会被判定为无效输入
functions.py里全局位置写的global movies是无效写法,global关键字只有在函数内部要修改全局变量的时候才需要用,全局位置直接定义变量就行
修复代码
main_menu.py 修正版
把菜单展示、输入读取的逻辑移到循环内部,每次执行完功能都重新读用户的菜单选择:
from functions import * def menu(): print("Press 1 for movies.") print("Press 2 to exit.") while True: menu() option = int(input("Input a number: ")) if option == 1: fun_movies() elif option == 2: print("Goodbye! ") break else: print("Wrong input")
functions.py 优化版
去掉无效的global声明,给输入加容错处理,删掉没必要的临时字典:
movies = {} def fun_movies(): name = input("Insert movie name: ") genre = input("Input genre: ") movies[name] = [genre] while True: query = input("Do you want to input another movie? (yes/no) ").strip().lower() if query == "yes": name = input("Insert movie name: ") genre = input("Input genre: ") movies[name] = [genre] elif query == "no": break else: print("Wrong input!") return movies
改完之后的流程:
- 启动程序展示菜单,读取用户输入
- 选1进入电影录入,输no就正常退出录入函数,回到菜单页重新等待用户选择
- 选2直接退出程序,不会再出现无限循环的问题
内容的提问来源于stack exchange,提问作者from stackoverflow import all
相关产品推荐
相关产品推荐

