Home › Errors › NameError

Python NameError: name '…' is not defined

Exception: NameErrorCategory: name lookupRaised at: runtime

What this error means

Python evaluated an expression containing a name — a variable, function, or class — and could not find that name in any reachable scope: not local, not enclosing, not global, not built-in. Unlike compiled languages, Python performs this lookup when the line runs, so a NameError can hide inside an if branch for weeks and only fire the day that branch executes.

The message always quotes the exact name it could not find. That quoted name is your entire investigation: either it was never created, it was created too late, it was created in a different scope, or it is spelled differently at the definition site.

A real example

message = "Welcome to PyDebug"
print(mesage)
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(mesage)
          ^^^^^^
NameError: name 'mesage' is not defined. Did you mean: 'message'?

One missing letter. Python 3.10+ even suggests the closest existing name — read the suggestion before anything else.

Why it happens

How to debug it

  1. Copy the quoted name from the message exactly — do not retype it from memory.
  2. Search the file for that spelling. Zero hits means a typo at the use site; one hit (the crash line itself) means the definition is missing or spelled differently.
  3. If the definition exists, verify it executes before the failing line at runtime — being higher up in the file is not enough if it sits inside a function or branch that never ran.
  4. If the definition is inside a function, remember it dies when the function returns; return the value instead of expecting the name to leak out.
  5. Check imports last: the name may live in a module you never imported on this code path.

Fix it interactively

These free PyDebug problems each ship a real NameError for you to repair in the browser — no setup:

Practice more Python bugs →
🇮🇳 Hindi में समझें

आपने ऐसा variable use किया जो Python को मिला ही नहीं। 90% cases में spelling की galti होती है — error message में quotes के अंदर जो नाम है, उसे file में search करो और मिलाओ। बाकी cases में variable use ऊपर हो रहा है और बन नीचे रहा है — Python file ऊपर से नीचे चलाता है, पहले बनाओ फिर use करो।

पूरी Hindi explanation पढ़ें →

Related errors

See also UnboundLocalError — raised when the name exists but is read before its local assignment — and the complete errors guide.