Skip to content

How to Resolve "NameError: name 'X' is not defined" in Python

How to fix Python's NameError when a variable, function, or module isn't defined in the current scope, with solutions for scope issues, typos, and missing imports.

The NameError: name 'X' is not defined error in Python occurs when you try to use a variable, function, class, or module name (X in the error message) that the Python interpreter doesn't recognize in the current scope.

This guide explains the various causes of this error and provides clear, actionable solutions.

Understanding Scope and Namespaces

Before diving into specific causes, it's important to understand scope and namespaces.

  • Namespace: A namespace is a mapping from names (variables, functions, classes, etc.) to objects. Think of it like a dictionary where the keys are names, and the values are the things those names refer to. Every module has its own global namespace. Each function has its own local namespace.
  • Scope: Scope refers to the region of your code where a particular name is accessible. The main scopes are:
    • Local: Inside a function. Names defined within a function are only accessible within that function.
    • Enclosing function locals: Inside a nested function, names in the parent function are accessible.
    • Global: Defined at the top level of a module (a .py file). Accessible from anywhere within that module.
    • Built-in: Pre-defined names like print, len, str, etc.

When you use a name (e.g., print(my_variable)), Python searches for it in a specific order: Local, Enclosing function locals, Global, Built-in (LEGB rule). If the name isn't found in any of these scopes, you get a NameError.

Common Causes and Solutions

Variable/Function/Class Not Defined

The most obvious cause: you're trying to use a name that hasn't been defined at all.

print(my_variable)

Solution: Define the variable, function, or class before you use it.

my_variable = "Now it's defined"
print(my_variable)  # Output: Now it's defined

Misspelled Name (Case Sensitivity)

Python is case-sensitive. myVariable, myvariable, and MyVariable are all different names.

employee = {
    'name': 'Tom Nolan',
    'age': 25,
}

print(employee)

Solution: Carefully check the spelling and capitalization of your variable, function, and class names. Modern IDEs are excellent at highlighting these errors.

Incorrect Order of Operations (Using Before Definition)

You must define a name before you can use it.


def do_math(a, b):
    return a + b
print(do_math(15,15))

Solution: Reorder your code so that definitions come before their uses. For functions and classes, this usually means placing them at the top of your file (or in a separate module that you import).

Incorrect String Literals

If you are trying to output a string but forget to use the quotes '' or "", you will likely see this error.

Missing Quotes around Dictionary Keys

When defining or accessing dictionary keys, make sure string keys are enclosed in quotes:


employee = {
    'name': 'Tom Nolan',
    'age': 25
}

Scope Issues (Local vs. Global vs. Nonlocal)

Variables defined inside a function are local to that function. They are not accessible outside the function's scope:

def get_message():
    message = 'tutorialreference.com'  # Local variable
    return message

get_message()
  • message is a local variable, which means it only exists within the get_message() function, and trying to access it outside will throw a NameError.

Solution 1 (Preferred): Return the value:

def get_message():
    message = 'tutorialreference.com'
    return message  # Return the value

result = get_message()  # Capture the returned value
print(result)         # Output: tutorialreference.com

Solution 2 (Generally Avoid): Use global (for global variables):

message = "" # Define it in the global scope.

def get_message():
    global message  # Declare that we're using the *global* message
    message = 'tutorialreference.com'
    return message

get_message() # This will change the global variable
print(message)  # Output: tutorialreference.com

Solution 3: (For nested functions): Use nonlocal:

def outer():
    message = '' # Local scope.
    def inner():
        nonlocal message # Use variable from the parent function
        message = 'tutorialreference.com'
        print(message)
    inner()
    print(message) # Output: tutorialreference.com

outer()

Missing import Statements

If you use a function, class, or variable from another module, you must import it first:


import math
print(math.floor(15.5))  # Output: 15
  • The import math line makes sure the math module is imported and you can use the math.floor() function.

import Statements within try/except

If you attempt to import a module inside a try block, make sure to also move the code that uses the imported module into that block, or import it in a different location:

try:
    import math # Import the math module.
    result = math.floor(15.5)
except ImportError:
    math.floor(18.5) # Use the imported module.

print(math.floor(20.5)) # Access member from the imported module.
  • If the import statement is inside a try block, the following statements that use the math module should be inside the same try block, or they should be placed after the import statement and outside of the try/except blocks.

Conclusion

The NameError: name 'X' is not defined error is a fundamental error in Python, and it always indicates a problem with variable scope, definition, or import.

By carefully checking variable names, the order of definitions, import statements, and understanding scope, you can quickly resolve this error and write more robust Python code. Use your IDE's debugging tools; they are invaluable for identifying the exact location and cause of NameError exceptions.

Navigation