Python NameError: name is not defined Solution

Posted in /  

Python NameError: name is not defined Solution
vinaykhatri

Vinay Khatri
Last updated on December 21, 2024

    Python NameError is one of the most common Python exceptions . And the " NameError: name is not defined Python Error" occurs when we try to access a Python variable before initializing or defining it.

    In this Python guide, we will walk through this Python error and discuss how to solve it. We will also highlight some examples to demonstrate how this error occurs (its causes) and how to solve it.

    Python Error: NameError name is not defined

    Before we move on to the actual error, let's first discuss the NameError.

    What is NameError?

    NameError occurs when we use an invalid variable or function in a program .

    The Python interpreter executes the code from top to bottom. Hence, you have to declare a variable before using it. If you use it without declaration, you get NameError. The most common type of NameError is NameError: name not defined.

    Here is an example to help you understand how the error occurs.

    For example

    message = "Hello World!"
    print(Message)

    Output

    Traceback (most recent call last):
    File "main.py", line 3, in <module>
    print(Message)
    NameError: name 'Message' is not defined

    Break the Code

    Python is a case-sensitive programming language, meaning if the two variables' cases are different, Python will treat them as different variables.

    In the above program, in line 1, we have defined a variable with the name message but in line 3, we used the variable Message , which is a different variable and not defined in the program.

    That's why we got the error - NameError: name 'Message' is not defined , which tells us that the variable Message was not defined in the program.

    You can also receive a similar error with the following error message:

    • nameerror: name 'data' is not defined : When trying to access a data variable without defining it.
    • nameerror: name 'X' is not defined : When trying to access any X variable without defining it.

    Note: The "nameerror name is not defined" is a very common error, and it can easily be solved by analyzing the code or the line where you receive it.

    Solution

    The solution to the above example is straightforward. We only need to ensure that the variable we are accessing has the same name as we defined earlier in the program.

    Example Solution

    message = "Hello World!"
    
    print(message)

    Output

    Hello World!

    Causes of the NameError: name not defined

    The following are the most common causes due to which you receive the NameError: name not defined:

    1. Misspelled variable or function name
    2. Try to call a variable or function before the declaration
    3. Forget to define a variable
    4. Try to access a local variable
    5. Try to print a single word

    Cause 1: Misspelled Variable or Function Name

    We, humans, have the ability to interpret words with spelling mistakes, but Python does not. You may often misspell the defined variable or function name while accessing it in a program.

    Python is a case-sensitive programming language, and even a single letter misspelled or case change is treated as a completely different variable or function name. This results in NameError: name not defined.

    Example

    def say_hello(message):
        print(message)
    
    # the message to print
    message = "Welcome to techgeekbuzz"
    
    # error
    sayhello(message)

    Output

    Traceback (most recent call last):
    File "main.py", line 8, in <module>
    sayhello(message)
    NameError: name 'sayhello' is not defined

    Break the Code

    In the above program, we tried to call the function sayhello() , which is not defined. We defined it as say_hello . So, when we call the function sayhello , Python throws the NameError.

    Solution

    To solve the above problem, we need to make sure that the name of the function during the function call is the same as the function name defined using the def keyword.

    def say_hello(message):
        print(message)
    
    # the message to print
    message = "Welcome to techgeekbuzz"
    
    # print message
    say_hello(message)

    Output

    Welcome to techgeekbuzz

    Cause 2: Call a Variable or Function Before its Declaration

    Python is an interpreted programming language that executes the code line by line, from top to bottom. So, before calling a function or accessing a variable value, you must declare or define it. The function declaration and the variable initialization must be done before calling a function or accessing a variable. Otherwise, we receive the NameError.

    Example

    # the message to print
    message = "Welcome to techgeekbuzz"
    
    # function call
    say_hello(message)
    
    # declare function after funtion call
    def say_hello(message):
        print(message)

    Output

    Traceback (most recent call last):
    File "main.py", line 5, in <module>
    say_hello(message)
    NameError: name 'say_hello' is not defined

    Break the Code

    In the above program, we get the NameError for the say_hello(message) function call statement. This is because the Python interpreter starts its execution from the top line of the program and executes it line by line until it encounters an exception or error.

    When the Python interpreter reaches line 5 and executes the say_hello(message) statement, it finds that the function is not declared. Hence, instead of executing the below code, Python raises the NameError: name say_hello is not defined.

    Solution

    We move the function definition part above the function call statement to solve the problem. So, the Python interpreter could store the say_hello() function in the heap memory and execute it when the function is called.

    # the message to print
    message = "Welcome to techgeekbuzz"
    
    # declare function before the funtion call
    def say_hello(message):
        print(message)
    
    # function call
    say_hello(message)

    Output

    Welcome to techgeekbuzz

    Cause 3: Forget to Define a Variable

    Many times, we have a variable in mind, but we forget to define it in the program. When we try to access it, we receive the NameError.

    Example

    name = "Rahul"
    
    print("Name:",name, "\nAge:", age )

    Output

    Traceback (most recent call last):
    File main.py", line 3, in <module>
    print("Name:",name, "\nAge:", age )
    NameError: name 'age' is not defined

    Break the Code

    In the above program, we tried to print the age variable that was not defined. Hence, we receive the NameError.

    Solution

    Before the print statement, we must define the age variable and its value to resolve the above error.

    name = "Rahul"
    age = 30
    
    print("Name:",name, "\nAge:", age )

    Output

    Name: Rahul 
    Age: 30

    Cause 4: Try to Access a Local Variable

    In Python, there are two variable scopes - local and global . The program space outside the function is known as the global scope, and the program space inside the function is known as the local scope.

    The variables defined in the global scope are known as global variables, and the variables defined inside the local scope are known as local variables.

    The global variable can be accessed throughout the program, but a local variable can only be accessed in its local scope (inside the function). If we try to access the local scope variable outside its function scope , we get the NameError.

    Example

    names = ["rahul", 'rajesh', 'aman', 'vikash']
    
    def add_name(name):
        # local variable total
        total = len(names)
    
        # add new name to names
        names.append(name)
    
    # add new name to names list
    add_name("ravi")
    
    # access all names
    print(names)
    
    # accessing local variable total
    print(total)

    Output

    ['rahul', 'rajesh', 'aman', 'vikash', 'ravi']
    Traceback (most recent call last):
    File "main.py", line 17, in <module>
    print(total)
    NameError: name 'total' is not defined

    Break the Code

    In the above program, we encountered the NameError at line 17 for the print(total) statement. The reason is that we tried to print the total variable value, which is a local variable,  in the global scope.

    Solution

    We can not access a local variable outside the function. Still, if we want the value of the local variable, we can return it using the function return statement and save that value in a global variable with the same name.

    names = ["rahul", 'rajesh', 'aman', 'vikash']
    
    def add_name(name):
        # add new name to names
        names.append(name)
    
        # local variable total
        total = len(names)
    
        # return the value of total
        return total
    
    # add new name to names list
    total = add_name("ravi")
    
    # access all names
    print(names)
    
    # print the value of total
    print(total)

    Output

    ['rahul', 'rajesh', 'aman', 'vikash', 'ravi']
    5

    Cause 5: Try to Print a Single Word

    If you want to print any single word in Python, we must enclose it in double quotes. The Python interpreter treats a word enclosed in double quotes as a string and prints it on the screen.

    If you do not use double quotes for a word, the Python interpreter considers it part of the program and throws the NameError.

    Example

    print(techgeekbuzz)

    Output

    Traceback (most recent call last):
      File "/home/main.py", line 1, in <module>
        print(techgeekbuzz
    NameError: name 'techgeekbuzz' is not defined

    Solution

    The solution is to enclose techgeekbuzz inside double quotes. The Python interpreter then prints 'techgeekbuzz' on the console.

    print("techgeekbuzz")

    Output

    techgeekbuzz

    Wrapping Up!

    This was all about Python NameError: name not defined. It occurs when we use a variable or function before declaring it in a program. The five major causes of this error are misspelled variables or functions, calling a function or variable before declaring, trying to print a single word, or accessing a local variable.

    We have tried to mention all causes of the NameError and their corresponding examples with solutions. Hopefully, this article might have helped you understand the error in detail.

    If you still get this error, please share your code in the comment section; we will try to help you debug your code.

    People are also reading:

    Leave a Comment on this Post

    0 Comments