已定义new_todos却触发NameError:变量未定义问题排查
待办事项程序NameError问题解决
我在Udemy平台学习Python Mega课程,编写待办事项程序时遇到错误。完全按照讲师的步骤操作,但输入“show”命令本应显示所有待办项,却触发报错。
我的代码
prompt = "Type add, show, edit, complete or exit: " while True: user_action = input(prompt) user_action = user_action.strip() match user_action: case 'add': todo = input("Enter a todo:") + '\n' file = open('../todos.txt', 'r') todos = file.readlines() file.close() todos.append(todo) file = open('../todos.txt', 'w') file.writelines(todos) file.close() new_todos = [] for item in todos: new_item = item.strip('\n') new_todos.append(new_item) case 'show' | 'display': file = open('../todos.txt', 'r') todos = file.readlines() for index, item in enumerate(new_todos): item = item.title() row = f"{index + 1}-{item}" print(row) case 'edit': number = int(input("Number of the to do to edit:")) number = number - 1 new_todo = input("Enter new todo:") todos[number] = new_todo case'complete': number = int(input("Number of the to do to complete:")) todos.pop(number - 1) case 'exit': break print("Bye!")
报错信息
Traceback (most recent call last): File "C:\Python Programing - Ardit\Python Programs 2024\app1\pythonProject\files\main.py", line 28, in <module> for index, item in enumerate(new_todos): ^^^^^^^^^ NameError: name 'new_todos' is not defined
问题原因与修复
问题根源:
new_todos变量仅在add分支内定义,只有先执行过add命令,这个变量才会被创建。如果直接运行show命令,程序从未进入add分支,自然找不到new_todos,触发NameError。修复方案:
直接在show分支里处理读取到的todos内容,不依赖其他分支的变量:case 'show' | 'display': file = open('../todos.txt', 'r') todos = file.readlines() file.close() # 关闭文件避免资源泄漏 for index, item in enumerate(todos): # 直接清理换行符并格式化标题 cleaned_item = item.strip('\n').title() row = f"{index + 1}-{cleaned_item}" print(row)额外优化建议:
edit和complete分支同样存在问题——它们直接使用todos变量,但该变量仅在add或show分支执行后才存在。建议每个需要操作待办项的分支都先读取文件,操作完成后再写入文件,确保变量始终有效。
内容的提问来源于stack exchange,提问作者Nathan Nuke
相关产品推荐
相关产品推荐

