Fix Python NameError: name 'x' is not defined — 5 Patterns and Fixes
Python NameError means a variable, function, or module doesn't exist in the current scope when Python tries to use it. Here are the 5 patterns that cause almost every NameError — with exact fixes and code examples for each.
What NameError Actually Means
Python throws NameError when you reference a name — variable, function, class, or module — that doesn't exist in the current scope at the time of execution.
Python's name lookup order (LEGB):
- Local scope (inside the current function)
- Enclosing scope (outer functions, for closures)
- Global scope (module level)
- Built-ins (
len,print,range, etc.)
If the name isn't found in any of these four places, you get NameError.
Pattern 1: Variable Used Before Assignment
Python doesn't scan ahead. The variable must be assigned before the line that uses it.
Fix: Move assignment above usage.
Pattern 2: Typo in Variable or Function Name
Python is case-sensitive. userName, user_name, and username are three different names.
Fix: Check spelling and case. Use your IDE's autocomplete — it only suggests names that exist in scope.
Pattern 3: Variable Defined in Wrong Scope
result is local to calculate(). It doesn't exist in the outer scope after the function returns.
Fix: Return the value.
Note: If you need genuinely shared state, use a class or pass as a parameter — not
global. Global variables create hidden coupling and make bugs harder to trace.
Pattern 4: Module Used Without Import
Fix: Import the module at the top of the file.
Common ones you might forget:
Pattern 5: Conditional Assignment Not Covering All Paths
Fix: Initialize with a default before the conditional.
Finding the Error Fast
Stack trace always includes file name and line number:
Go to app.py line 23. Trace backward — where was config supposed to be assigned? Was it inside an if block that didn't run? Was it in a function that wasn't called? Was it in a different file that wasn't imported?
Tip: In VS Code, hover over any name before running the code. The editor shows if the name is unresolved (undefined). Catches most
NameErrorbefore execution.
Quick Diagnosis Table
| Error message | First check |
|---|---|
name 'x' is not defined | Is x assigned above this line? |
name 'pd' is not defined | Did you import pandas as pd? |
name 'X' is not defined (capital) | Check case — Python is case-sensitive |
free variable 'x' referenced before assignment in enclosing scope | Closure scope issue — restructure, don't use global |
For NameError that appears only at runtime based on specific inputs (conditional paths that rarely execute), paste the function and the call stack into DebugAI. It traces which conditional branch failed to assign the name and shows the path that triggered the error.
Debug faster starting today.
Free VS Code extension. 10 sessions/day. No credit card.