NameError
PythonERRORNotableRuntime ErrorHIGH confidence

Name not found in local or global scope

What this means

Raised when a local or global name (e.g., a variable or function) is not found. This means you are trying to use a name that has not been defined or is not accessible in the current scope.

Why it happens
  1. 1A typo in a variable or function name.
  2. 2Attempting to use a variable before any value has been assigned to it.
  3. 3A variable is defined in a different scope (e.g., inside a function) and is not accessible.
How to reproduce

This error is triggered by an attempt to access a variable that has not been created yet.

trigger — this will error
trigger — this will error
x = 10
if x > 5:
    y = 20

print(y_oops)  # Typo in variable name

expected output

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
NameError: name 'y_oops' is not defined

Fix 1

Correct the typo in the name

WHEN When you have misspelled a variable or function name.

Correct the typo in the name
x = 10
if x > 5:
    y = 20

print(y)  # Corrected variable name

Why this works

By matching the variable name exactly to its definition, Python can find and use it.

Fix 2

Define the variable before use

WHEN When a variable is used before it is assigned a value.

Define the variable before use
message = "Hello, world!"
print(message)

Why this works

Initializing the variable with a value ensures that it exists in the current scope before it is accessed.

Code examples
Triggerpython
print(undefined_variable)  # NameError: name not defined
Handle with try/exceptpython
try:
    val = undefined_var
except NameError as e:
    print(f"Variable not defined: {e}")
    val = None
Avoid with default initializationpython
result = None
if condition:
    result = compute()
# result always defined before use
What not to do

Using `global` keyword excessively to fix scope issues

Overuse of `global` can make code difficult to debug and understand by creating hidden dependencies between functions and modules.

Sources
Official documentation ↗

cpython/Python/sysmodule.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors