You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python待办脚本执行complete操作时触发NameError:todos未定义

待办事项Python脚本NameError问题排查与解决

问题场景

执行添加新待办后,直接执行complete操作时触发以下错误:

File "C:\Users\HP\OneDrive\Desktop\python apps\app1.py", line 40, in <module>
    row=todos.pop(int(number))
NameError: name 'todos' is not defined

错误原因

  1. 变量未提前定义:todos变量仅在add和show的代码块中从文件读取并定义,complete和edit操作直接使用该变量,但未提前从文件加载。如果当前会话未执行过add/show,或程序重启后直接执行complete/edit,todos变量会未定义。
  2. 索引逻辑错误:complete操作中使用pop(int(number)),但用户输入的是从1开始的序号,列表索引从0开始,即使todos存在也会导致索引越界。
  3. 修改未持久化:edit和complete操作修改todos后未写回文件,修改不会保存到本地。

解决方案

针对上述问题,对代码进行如下修改:

修改后的完整代码

prompt = "    Type add, show, edit, complete or exit:       "

while True:
    user_action = input(prompt.strip())
    match user_action:
        case "add":
            todo = input("Enter a todo:") + "\n"
            # 使用with语句自动管理文件生命周期
            with open("todos.txt", "r") as file:
                todos = file.readlines()
            todos.append(todo)
            with open("todos.txt", "w") as file:
                file.writelines(todos)
        
        case "show" | "display":
            with open('todos.txt', "r") as file:
                todos = file.readlines()
            for index, item in enumerate(todos):
                item = item.strip("\n")
                row = f"{index+1}-{item.capitalize()}"
                print(row)  
        
        case 'edit':
            # 先从文件读取todos,确保变量存在
            with open("todos.txt", "r") as file:
                todos = file.readlines()
            try:
                number = int(input("Enter a number: "))
                new_todo = input("Enter new todo:") + "\n"
                todos[number - 1] = new_todo
                # 将修改写回文件
                with open("todos.txt", "w") as file:
                    file.writelines(todos)
                print("Todo updated successfully!")
            except (ValueError, IndexError):
                print("Invalid number, please try again.")
        
        case "complete":
            # 先从文件读取todos,确保变量存在
            with open("todos.txt", "r") as file:
                todos = file.readlines()
            try:
                number = int(input("Number of the todo:"))
                completed_todo = todos.pop(number - 1).strip("\n")
                # 将修改写回文件
                with open("todos.txt", "w") as file:
                    file.writelines(todos)
                print(f"Completed todo: {completed_todo}")
            except (ValueError, IndexError):
                print("Invalid number, please try again.")
        
        case "exit":
            break
        
        case _:
            print("Invalid command, please try again.")

print('Bye!')

关键修改点

  • 确保变量存在:edit和complete操作开头先从文件读取todos,彻底避免NameError。
  • 修复索引错误:将complete中的pop(int(number))改为pop(number-1),匹配用户输入的1开始序号。
  • 持久化修改:edit和complete操作修改todos后,立即将内容写回文件,确保修改生效。
  • 优化文件操作:使用with语句自动关闭文件,避免手动关闭遗漏导致的资源泄漏。
  • 异常处理:添加try-except捕获输入非数字或索引越界的情况,提升程序健壮性。
  • 默认命令处理:添加case _处理无效命令,提示用户正确输入。

内容的提问来源于stack exchange,提问作者Taher Ali Patrawala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:40:38