How to Fix NameError: name ‘x’ is not defined in Python

3D isometric tech render of a glowing magnifying glass searching empty memory slots on a motherboard to fix a NameError.

Python just reached into active memory for a variable, function, or moduleโ€”and came up empty. A NameError: name 'x' is not defined means your syntax is valid, but the identifier you referenced does not exist in the current scope at the moment that line executes.

Whether you forgot import pandas as pd at the top of the file, mistyped a variable’s capitalization, or ran a Jupyter Notebook cell out of order, the fix always starts with tracing where that name was supposed to be created.

Reading the NameError Traceback

Read the traceback from the bottom up. Python tells you exactly which name it failed to find, and points you to the line where it attempted the execution.

(Note: The precise ^^^^ carets underneath the failing line were introduced in Python 3.11).

Traceback (most recent call last):
  File "/var/www/app/main.py", line 5, in <module>
    print(tax_rate)
          ^^^^^^^^
NameError: name 'tax_rate' is not defined

Tested Environment: Python 3.10.16 (Linux) | Python 3.11+ carets and 3.12+ self. suggestion noted; not run.

Part of: The Ultimate Python Debugging Guide

If Python cannot find your variable, you must prove that you actually put it into memory before that line of code executed.

The Fix:

  1. If the missing name is pd, np, or os, you’re missing an import. Add it to the top of your file.
  2. Otherwise, copy the exact variable name inside the single quotes of your error message (e.g., 'tax_rate').
  3. Press Ctrl + F (or Cmd + F on Mac) in your editor.
  4. Search your file for where you assigned that variable (e.g., tax_rate = ).

If you get zero search results, you never created the variable, or you misspelled it. If you do find it, it means you either defined it below where you tried to use it, or it is trapped inside a local function scope.

Common Causes of NameError

Because a NameError always boils down to “I can’t find this in memory,” it manifests in several specific ways depending on how you structured your code. Here are the most common culprits.

1. The Forgotten Import (pd, np, os)

One of the most common causes of this error is trying to use a library without actually importing it at the top of your file.

  • The Trigger: Calling pd.DataFrame() or os.listdir() without the corresponding import pandas as pd or import os.
  • The Fix: Add the missing import statement at the top of your script. (Note: If you add the import and Python still crashes saying “No module named pandas”, you need our ModuleNotFoundError Guide).
  • How to tell it’s this one: The error complains that name 'pd', name 'np', name 'os', or name 'math' is not defined.

2. The Case-Sensitivity Typo

Python is strictly case-sensitive. User_score and user_score are two entirely different locations in memory.

  • The Trigger:
user_score = 100
print(User_score) # Fails: Capital 'U'
  • The Fix: Ensure the capitalization matches perfectly.
  • How to tell it’s this one: Your Ctrl + F search finds a variable that looks almost identical to the error, but the capitalization or spelling is slightly off.

3. Pasting JSON Data (null, true, false)

If you copy a raw JSON payload from an API and paste it directly into Python as a dictionary, it will crash. JSON uses lowercase booleans (true, false) and null, which Python interprets as undefined variables.

  • The Trigger:
# Fails: Python looks for a variable named 'true'
payload = {"is_active": true, "user": null}
  • The Fix: Capitalize Python booleans (True, False), and change null to None. Alternatively, wrap the raw JSON in a string and parse it safely: import json; payload = json.loads('{"is_active": true}').
  • How to tell it’s this one: The traceback explicitly says name 'true' is not defined or name 'null' is not defined.

4. Forgetting the self. Prefix in Classes

When working inside an Object-Oriented Class, you cannot access class attributes just by calling their name.

  • The Trigger:
class User:
    def __init__(self, name):
        self.name = name

    def print_name(self):
        print(name) # Fails: Python looks for a global 'name', not the instance attribute
  • The Fix: Change it to print(self.name). (Note: Python 3.12+ will actively suggest this in the traceback: Did you mean: 'self.name'?).

5. Using self Where it Doesn’t Belong

You might accidentally try to use self at the class or module level where it isn’t defined.

  • The Trigger:
class User:
    print(self.name) # Fails: You cannot use 'self' at the class level outside a method
  • The Fix: Move the code inside a method. (Note: If you simply forget the self parameter in a method signature like def get_name(): and call it on an instance, Python throws a TypeError: takes 0 positional arguments but 1 was given, not a NameError).

6. Python 2 Code in Python 3

If you copy a very old snippet from Stack Overflow, it might contain built-in functions that Python 3 deleted entirely.

  • The Trigger: Using xrange(), raw_input(), or unicode().
  • The Fix: Translate them to modern Python. Use range(), input(), or str().
  • How to tell it’s this one: The missing name is a legacy Python 2 built-in.

7. The Scope Trap (Local vs. Global)

Variables created inside a function are “local” to that function. The moment the function finishes running, Python deletes those variables from memory to save space.

  • The Trigger:
def calculate_tax():
    tax_rate = 0.20 # Local variable created

print(tax_rate) # Fails: tax_rate was deleted from memory when the function ended
  • The Fix: Use the return keyword to pass the data out of the function, and assign it to a new variable in the global scope.
  • How to tell it’s this one: You find the variable definition, but it is indented inside a def block, while the crash happened outside of it.

NameError: free variable referenced before assignment in enclosing scope

If you write nested functions, you might run into a highly specific NameError with a different message: NameError: free variable 'x' referenced before assignment in enclosing scope.

(Note: In Python 3.11+, this message was updated to “cannot access free variable ‘x’ where it is not associated with a value in enclosing scope”).

Why it happens: A “free variable” is a variable used inside an inner function, but created in an outer function. If the inner function is executed before the outer variable is ever assigned, the inner function searches for a memory address that doesn’t exist yet.

def outer():
    def inner():
        print(x) # Fails: x doesn't exist yet
    inner()      # Called before x is assigned
    x = 10

The Fix: Ensure the variable is assigned in the outer function before you execute the inner closure.

Python 3.10+ “Did you mean?” Hints

Starting in Python 3.10, the interpreter includes a built-in spell checker. When a NameError occurs, Python scans your active memory for names that are a close string match and appends a Did you mean: prompt to your traceback.

Always treat this as a hint, not a strict instruction.

If you type df = pd.DataFrame() but forget to import pandas as pd, Python will try to be helpful by finding any built-in function that looks like pd.

Traceback (most recent call last):
  File "/var/www/app/test.py", line 1, in <module>
    df = pd.DataFrame()
NameError: name 'pd' is not defined. Did you mean: 'id'?

Changing pd to Python’s built-in id() function won’t fix your DataFrame. The true diagnosis is that you missed the import.

Stop NameErrors with Linters

A NameError is a runtime crash, meaning it could easily happen in production if that specific line of code is rarely executed.

Stop this from ever happening by using a linter. If you configure Ruff or Flake8 in your editor, they run static analysis on your code as you type. If you use a variable before assigning it, or misspell a variable, they will flag it immediately with rule F821 (undefined-name), underlining the typo in red before you even save the file.

Worked Example: pandas Is Not Defined After import pandas as pd

Let’s look at a real-world scenario involving module aliases.

The Code:

import pandas as pd

def generate_report():
    data = {"users": [1, 2, 3]}
    # The developer forgot they aliased pandas as 'pd'
    df = pandas.DataFrame(data) 
    return df

generate_report()

The Traceback:

Traceback (most recent call last):
  File "/var/www/app/main.py", line 9, in <module>
    generate_report()
  File "/var/www/app/main.py", line 6, in generate_report
    df = pandas.DataFrame(data) 
NameError: name 'pandas' is not defined

The Thought Process & Fix:

  1. Python crashed inside generate_report(), pointing to the word pandas.
  2. The developer assumes pandas is installed, so why is it missing?
  3. Looking at line 1, the developer imported it using import pandas as pd.
  4. By using the as pd alias, the name pandas is never loaded into the file’s namespace memoryโ€”only the abbreviation pd is.
  5. The Result: The developer changes the code on line 6 to pd.DataFrame(data). The script compiles perfectly.

Frequently Asked Questions

Why do I get a NameError inside a try/except/finally block?

Imagine you assign a variable inside a try block (e.g., x = 5), but the code crashes before the assignment completes. Python immediately jumps to the except or finally block. When you try to print x in the finally block, it throws an error because the variable was never successfully created in memory.

This behavior manifests differently depending on your scope:

* At the module level, it throws a standard NameError.
* Inside a function, it throws an UnboundLocalError (which is a subclass of NameError).

To prevent this, always define fallback variables (e.g., x = None) before the try block begins.

How do I check what variables are currently in memory?

If you are debugging a complex script, insert print(locals().keys()) (if inside a function) or print(globals().keys()) (if outside a function) just before the line that crashes. This will print a list of every single variable currently active in Python’s memory for that scope. If your variable name isn’t in that list, Python can’t use it.

Why does my Jupyter Notebook say a variable is undefined when it is right there on the screen?

Jupyter Notebooks execute code in the exact order you run the cells, not the order they appear on the page. If you define a variable in Cell 2, but execute Cell 3 before running Cell 2, Python will throw a NameError because the variable hasn’t been pushed into the active memory session yet.

In Jupyter, click Kernel > Restart & Run All.
In Google Colab, click Runtime > Restart and run all.

Similar Posts

Leave a Reply