NameError 🐍 Python

NameError: name 'x' is not defined

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

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.

How to diagnose

  1. Name — Spelled right?
  2. Import — Imported?
  3. Flow — Assigned on every path?

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