Last modified: Feb 23, 2025 By Alexander Williams

Understanding NameError in Python

A NameError in Python occurs when the interpreter encounters a name that it doesn't recognize. This usually happens when you try to use a variable or function that hasn't been defined yet.

Why Does NameError Occur?

NameError typically occurs due to typos, scope issues, or forgetting to define a variable or function before using it. It's a common mistake, especially for beginners.

Common Causes of NameError

Here are some common scenarios where you might encounter a NameError:

  • Using a variable before it's defined.
  • Misspelling a variable or function name.
  • Accessing a variable outside its scope.

Example of NameError

Let's look at a simple example where a NameError occurs:


# Example of NameError
print(undefined_variable)
    

In this code, undefined_variable is not defined before it's used in the print function. This will raise a NameError.

Output


NameError: name 'undefined_variable' is not defined
    

How to Fix NameError

Fixing a NameError is usually straightforward. Here are some steps you can take:

  • Check for typos in your variable or function names.
  • Ensure the variable or function is defined before it's used.
  • Make sure the variable is within the correct scope.

Example of Fixing NameError

Let's fix the previous example by defining the variable before using it:


# Fixing NameError
undefined_variable = "Hello, World!"
print(undefined_variable)
    

Now, the code will run without any errors.

Output


Hello, World!
    

Scope and NameError

Scope plays a crucial role in NameError. Variables defined inside a function are not accessible outside it. This can lead to NameError if you try to access them incorrectly.

Example of Scope-Related NameError

Here's an example where a variable is defined inside a function and accessed outside it:


# Scope-related NameError
def my_function():
    local_variable = "I'm local"
    
print(local_variable)
    

This will raise a NameError because local_variable is not accessible outside the function.

Output


NameError: name 'local_variable' is not defined
    

Conclusion

A NameError in Python is a common error that occurs when the interpreter encounters an undefined name. By understanding its causes and how to fix it, you can avoid this error in your code. Always ensure variables and functions are defined and spelled correctly before using them.