Name not found in local or global scope
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.
- 1A typo in a variable or function name.
- 2Attempting to use a variable before any value has been assigned to it.
- 3A variable is defined in a different scope (e.g., inside a function) and is not accessible.
This error is triggered by an attempt to access a variable that has not been created yet.
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.
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.
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.
print(undefined_variable) # NameError: name not defined
try:
val = undefined_var
except NameError as e:
print(f"Variable not defined: {e}")
val = Noneresult = None
if condition:
result = compute()
# result always defined before use✕ 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.
cpython/Python/sysmodule.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev