NameError: name 'x' is not defined
Python doesn’t know the name — it was never assigned/imported in this scope, or it’s misspelled.
is not defined Meaning
Equivalent to JavaScript’s ReferenceError. Common after forgetting an import, using a variable before assignment in a branch that didn’t run, or Python 2 code (raw_input, unicode) on Python 3.
Common causes
- Missing import
- Typo or wrong case
- Variable only defined inside an if branch that didn’t run
- Python 2 names on Python 3
⚡ Quick fix
- Add the import
- Initialize the variable before branches
- Replace Python 2 built-ins (
raw_input→input)
Detailed fix by platform
Python
- Linters (ruff, pyflakes) catch undefined names before runtime.
Code examples
Variable only set in one branch
if user.is_admin:
role = "admin"
print(role) # ❌ NameError when the user is not an admin
role = "member" # ✅ initialise before branching
if user.is_admin:
role = "admin"How to diagnose
- Name — Spelling and case
- Import — Imported in this module?
- Flow — Assigned on every code path before use?
- Python 2 — raw_input / unicode / xrange in old code?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
Most viewed in Python
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 14 Oct 2026