我不知道如何修复的错误,我是初学者,而且是新手

问题描述 投票:0回答:1

我正在 udemy 上学习 Python 大型课程,但出现错误

即使我完全按照教练的操作,我还是收到错误。当您输入“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!")

这是错误:

回溯(最近一次调用最后一次): 文件“C:\Python Programing - Ardit\Python Programs 2024 pp1\pythonProject iles\main.py”,第 28 行,位于 对于索引,枚举中的项目(new_todos): ^^^^^^^^^ 名称错误:名称“new_todos”未定义

它说“new_todos”未定义,但看看代码。请帮忙

python nameerror
1个回答
0
投票

new_todos
case 'add'
块中定义。

如果

case 'show' | 'display'
块在
case 'add'
块之前执行,则变量确实是未定义的。

© www.soinside.com 2019 - 2024. All rights reserved.