NameError: name is not defined in Python [with 4+ Examples]

Did you hit by NameError: name is not defined in Python? Let me tell you what the NameError: name is not defined in Python error is, How we get into this, and also how to fix this.

In this Python article, I will discuss everything about NameError: name is not defined in Python with examples.

While working on a project in Python, I also came across the NameError name is not defined error. So, I started searching about this. So, I considered telling my search in a summary as this article.

NameError in Python occurs when a variable is used before being declared in the Program or when we use a module without importing it.

What is NameError: name is not defined in Python.

Python is growing daily, and getting errors while programming is a mistake from where one learns the best.

One of the most common is the dreaded NameError.This error arises when Python encounters a variable or function name it doesn’t recognize.

In Python, a NameError occurs when the interpreter fails to find a defined variable or function within the current scope.

You can see the screenshot below for the error message:

nameerror: name is not defined in Python

Name is not defined Python reasons

The nameerror name is not defined error in Python typically happens due to one of the following reasons:

  1. Misspelled Names: If you inadvertently misspell a variable or function name, Python won’t be able to recognize it.
  2. Undefined Names: Attempting to use a variable or function before it’s defined leads to a NameError.
  3. Incorrect Scope: Variables must be defined within the appropriate scope to be accessible.
  4. Functions from Different Modules: Using the function from any module without importing it can lead to a NameError.
READ:  Python Program for Selection Sort [Detail explanation with 3 Examples]

Let’s see them all one by one in detail.

Case 1: NameError name is not defined when misspelled

When we misspell a variable or function name in Python, the interpreter won’t recognize it because it doesn’t match any defined names in the Python program.

This is a common mistake that can lead to NameErrors in Python. Misspelled names can occur in variable assignments, function calls, or any other place where names are used.

Here is an instance:

cities = ['New York', 'Texas', 'California']
print(city)

Here is the screenshot taken after running the above code:

Python nameerror: name is not defined

We have created a Python variable named ‘cities‘; when printing this, we mistakenly typed ‘city‘ instead. This caused a NameError in Python.

Case 2: NameError name is not defined when undefined names are used

NameError in Python occurs when we try to use a variable or function before it’s defined.

Python operates sequentially, so if you reference a name before assigning any value or defined as a function, the interpreter won’t find it in the current scope, leading to a NameError name is not defined.

Here is the instance:

print(USA_Cities)

The output can be seen in the screenshot below after executing the code in PyCharm.

name is not defined python

Here, we have not defined any variable but are trying to print a variable, hence, hit by NameError in Python.

Case 3: Name not defined error in Python when used

Scope refers to the region of a program where a variable or function is accessible. Python has rules governing variable scope, and if you try to access a name from outside its defined scope, Python raises a NameError.

READ:  Python - Create Dictionary Of Tuples

Variables can be local (inside a function), global (defined at the top level of the script), or enclosed in nested scopes.

For example:

City = ['New York', 'Texas', 'California', 'Austin']
def city_names(a):
    States = []
    for x in City:
        States.append(x)

print(States)

The screenshot below shows the code implemented in the PyCharm editor.

nameerror name is not defined python

In the above examples, we defined a variable named “States” inside a function in Python. Later, we tried to access that variable outside the function and raised a NameError: name is not defined error in Python.

Case 4: Name is not defined error in Python in calling functions without importing module.

When we try to use the function from a module and forget to import the module before, Python raises NameError.

Here is an instance:

city = random.randint(4, 12)
print(city)

After executing the code in Pycharm, the output can be seen in the screenshot below.

nameerror in python

Here, we are using the random.randint() function without importing the random module, and that’s why Python raises a NameError.

How to fix NameError: name is not defined in Python

In Python, there are several ways to handle NameError depending on the specific scenario and requirements of our code.

Here are some common approaches:

1. How to solve NameError in Python by checking for name existence

Before using a variable or calling a function, check if it exists to avoid NameError: name is not defined in Python. We can use the in-operator or hasattr() function in Python to determine if a name is defined.

The in operator checks if the value exists in the provided iterable or not in Python.

The hasattr() function returns True if the specified object has the specified attribute; otherwise False in Python.

Here is the code:

import random
# Using 'in' operator
if 'random' in dir(random):
    random_number = random.random()
    print(random_number)
else:
    print("random function is not available in the import random module")

# Using 'hasattr' function
if hasattr(random, 'random'):
    random_number = random.random()
    print(random_number)
else:
    print("random function is not available in the import random module")

Output:

0.6530812491463261
0.3926650672500255

Below is the screenshot mentioned after implementing the code in the Pycharm editor.

Python nameerror name 'a' is not defined

2. NameError: name ‘error’ is not defined in Python by try-except block

We can handle any error using the try-except block in Python, as the try block takes the code that may throw errors, and the except block can handle the handle if mentioned.

READ:  Encode function in Python string

Here is an instance:

from random import randint
try:
    random_number = random()
    print(random_number)
except NameError:
    print("An error occured")

Output: We can see that this except block has excepted the NameError in Python and hence printed the message.

An error occured

Upon executing the code in PyCharm, the output can be viewed in the screenshot below.

python name is not defined

3. NameError name is not defined in Python 3 by providing default values:

If the variable might not exist but still needs a value, we can use the get() method for dictionaries or provide default values using the or operator in Python.

Here is an instance:

USA = {}
default_value = 'Null'
variable_value = USA.get('key', default_value)

# Using 'or' operator
usa = 'United States of America'
variable_value = variable_value or default_value

4. Check before the NameError in Python occurs

One of the easiest ways to solve the NameError: name is not defined in Python is to check before and write the code correctly:

  1. Check for the spelling and case sensitivity after seeing a NameError in Python.
  2. Ensure the variable is a global or local variable before using it in the code in Python.
  3. If variables are conditionally defined, ensure they’re defined before use, possibly within conditional blocks in Python.
  4. In cases where NameError is due to complex code structure, consider rewriting the code to make it clearer and more organized, thus reducing the errors in Python.
  5. Encapsulate related code in modules and functions and import them appropriately in Python. This ensures proper scoping and reduces the chances of encountering NameError in Python.

Conclusion

Knowing about the NameError: name is not defined in Python, why it happens, and how to fix it is essential for smooth coding. Understanding these basics helps us quickly find and solve problems when writing Python code.

I hope this article helps you in all manner.

You may also like to read these articles: