我正在 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”未定义,但看看代码它是。请帮忙
new_todos
仅当 case 'add'
块执行时才定义。
如果在此之前执行
case 'show' | 'display'
块,则该变量确实是未定义的。
因此,用户必须先输入“show”或“display”,然后再输入“add”。
您可以通过将行
new_todos = []
移动到代码的最顶部来解决此问题,因此它始终会被执行。