NameError: name 'x' is not defined is one of the first errors beginners see. It means Python looked up a name (variable, function, or class) and could not find it in the current scope. This guide explains why that happens and how to fix it.

What this error means

Python keeps a list of names it knows in each scope (module, function, class). When you use a name—for example total or result—Python looks for it in the current scope and, if needed, in enclosing scopes. If the name is never defined there, you get NameError: name '…' is not defined. The message tells you exactly which name Python could not find.

Common causes

  • Using a variable before assigning it. You refer to a name on a line above its first assignment, or in a branch that never runs.
  • Typos. A misspelled variable or function name (e.g. lenght instead of length) creates a new name that was never defined.
  • Scope. You use a name that only exists inside a function or loop, but you use it outside that block. See UnboundLocalError when the name is used before assignment inside the same function.
  • Wrong module or import. You expect a name from another module but did not import it, or imported it under a different name.

Example: using a variable before it is defined

print(total)   # NameError: total not defined yet
total = 10

Fix: define the name before you use it

Assign (or import) the name before any line that uses it. Order of execution matters.

total = 10
print(total)   # OK: total is defined first

Example: name only exists inside a function

Variables created inside a function are local to that function. Using them outside causes NameError.

def compute():
    result = 5 + 3
    return result

print(result)  # NameError: result is only inside compute()

Fix: use the return value

Do not reference the inner variable outside. Use the function’s return value instead.

def compute():
    result = 5 + 3
    return result

value = compute()
print(value)   # OK: 8

Example: typo in a name

message = "Hello"
print(mesage)  # NameError: mesage (typo for message)

Fix: correct the spelling so it matches the name you defined.

Check your scope and imports

If the name should come from another file, make sure you have an import statement and that you use the correct name (including alias, e.g. import numpy as np → use np). For names that might be assigned in a function but used before assignment, see UnboundLocalError.

Next steps: Errors & Exceptions · Getting Started · Data types