NameError Python Origin: Application & API Last updated 14 Oct 2026

NameError: name 'x' is not defined

Python doesn’t know the name — it was never assigned/imported in this scope, or it’s misspelled.

Exact message you may see is not defined
Seen on: Python

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

  1. Add the import
  2. Initialize the variable before branches
  3. Replace Python 2 built-ins (raw_input → input)

Detailed fix by platform

Python

  1. Linters (ruff, pyflakes) catch undefined names before runtime.

Code examples

Variable only set in one branch

python
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

  1. Name — Spelling and case
  2. Import — Imported in this module?
  3. Flow — Assigned on every code path before use?
  4. 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:

Where this error sits

Origin: Application & API. Errors that are often confused with or caused by this one (click to open):

already declared — SyntaxError: Identifier 'x' has already been declared (JavaScript)already declaredCS0103 — error CS0103: The name 'x' does not exist in the current context (.NET)CS0103IndentationError — IndentationError: unexpected indent / expected an indented block (Python)IndentationErrorModuleNotFoundError — ModuleNotFoundError: No module named 'x' (Python)ModuleNotFoundErrorReferenceError — ReferenceError: x is not defined (JavaScript)ReferenceErrorTDZ — ReferenceError: Cannot access 'x' before initialization (JavaScript)TDZUnboundLocalError — UnboundLocalError: cannot access local variable 'x' where it is not associated with a value (Python)UnboundLocalErrorNameError

Explore the map of this error Full error map →

🧠 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.