Python NameError name is not defined Solution

Posted in /  

Python NameError name is not defined Solution

Vinay Khatri
Last updated on September 12, 2022

    Python NameError is one of the most common Python exceptions. And the " NameError: name is not defined Python Error" occurs in Python 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 debug it. We will also use some examples to demonstrate this Python error to get a better idea of how to solve this error in your Program.

    Python Error: NameError name is not defined

    The NameError is raised in Python when we try to access a variable or function, and Python is not able to find that name, because it is not defined in the program or imported libraries.

    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, which means if the cases of the two variables are different Python will treat them as different variables.

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

    That's why we are getting the NameError: name 'Message' is not defined Error, which is telling us that the variable Message is not defined in the program.

    You can also receive this similar error with the following error message

    • nameerror: name 'data' is not defined : When you are trying to access a data variable without defining it.
    • nameerror: name 'X' is not defined: When you are 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, and the line where you are receving that error.

    Solution The solution of the above example is very simple. We only need to make sure that the variable we are accessing has the same name as we have defined earlier in the program.

    Example Solution

    message = "Hello World!"
    
    print(message)

    Output

    Hello World!

    Common Error Examples

    There are many common scenarios where many new and experienced Python learners commit mistakes while writing programs and encounter Python NameError.

    1. Misspelt the variable or function name
    2. Try to call a variable or function before the declaration
    3. Forget to define a variable
    4. Trying to access a local variable.

    Scenario 1: Missplet the variable or function name

    This happened many times when the programmer misspelt the defined variable or function name, during accessing the variable or function. Python is a case-sensitive programming language, and even a single letter misspelt or case change is treated as a completely different variable or function name.

    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

    We are getting this NameError in the above program because we are trying to call the function sayhello() that is not defined in the program. The function in the program is defined by the name say_hello and we are calling the function sayhello which is two different function names, that's why Python is throwing the NameError.

    Solution

    To solve the above problem we need to make sure that the name of the function during the function call must be 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

    Scenario 2: Try to call a variable or function before the declaration

    Python is an interpreted programming language, and it executes its program code line by line, so before calling a function or accessing a variable value, it must be declared or defined. The function declaration and the variable initialization must be done before calling a function or accessing a variable, otherwise, we will 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 are getting 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 it keeps executing the program code line by line until it encounters an exception or error.

    In the above program when the Python interpreter reached line 5 and try to execute the say_hello(message) statement, it found that it has no function declaration statement by name say_hello() to call, so instead of executing the below further code Python raise the NameError that there is no name defined with say_hello .

    Solution

    To solve the above problem, we just move the function definition part above the function calling statement. 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

    Scenario 3: Forget to define a variable

    Many times we have a variable in mind but we forget to define it in the program. And 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 are trying to print the age variable that we haven't defined. That's why we are receiving the NameError.

    Solution

    To resolve the above error, we also need to define the age variable and its value before the print statement.

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

    Output

    Name: Rahul 
    Age: 30

    Scenario 4: Try to Access a Local Variable

    In Python, there are two variable scopes local and global . The program space that is outside the function is known as the global scope and the program space inside the functions 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 through any scope, 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 are encountering the NameError at line 17 with print(total) statement. We are receiving this nameerror" because we are trying to print the total variable value in the global scope, and the name is not defined in the local scope of add_name() function.

    Solution

    We can not access a local variable outside the function, but 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

    Wrapping Up!

    NameError is a common exception in Python, it is raised when the Python interpreter is not able to fnc the local or global name of the variable in the Program and imported libraries. To resolve this error, we have to look out for the error line and make sure that the name we are using to access a variable or call a function must be defined in the Program.

    If you are still getting this error in your Python program, please share your code in the comment section; we will try to help you in debugging.

    To gain in-depth insights into Python Exception handling, buy the course here.

    People are also reading:

    Leave a Comment on this Post

    0 Comments