pythonnameerror

Variable "is not defined" error even though it is defined


I'm doing the python mega course on udemy, and I get an error.

I get an error even though I did exactly what the instructor did. It is supposed to show all your todo items when you type "show" but it gives an error. Here's the code:

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!")

And here's the error:

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

It says that "new_todos" isn't defined, but looking at the code it is.


Solution

  • new_todos is defined only when the case 'add' block has executed.

    If the case 'show' | 'display' block is executed before that, the variable will indeed be undefined.

    So, the user must have typed "show" or "display" first, before they typed "add".

    You can fix this by moving the line new_todos = [] to the very top of the code, so it is always executed.