Python NameError: name is not defined
The code references a variable or function name that hasn't been defined.
Explanation
NameError occurs when Python encounters a name (variable, function, or class) that hasn't been defined in the current scope. Unlike many other languages, Python doesn't allow using variables before they are assigned. This commonly happens due to typos, scoping issues where a variable is defined in a different scope, misspelled function names, or trying to access a variable that was defined in a conditional branch that didn't execute.
Common Causes
- Variable name typo
- Variable used before assignment
- Function called before definition
- Variable in wrong scope
- Shadowing built-in names
Solution
Check for typos in variable and function names. Ensure all variables are defined before use. Verify the variable is in the correct scope (not defined inside a function but used outside). Use an IDE with code completion to catch undefined names. Initialize variables with default values before conditional assignments. Check import statements for misspelled module names.
Code Example
# Typo in variable name
user_name = "John"
print(user_nmae) # NameError: name 'user_nmae' is not defined
# Fix
print(user_name)
# Variable defined inside if block not available outside
if True:
x = 10
print(x) # this works
if False:
y = 20
print(y) # NameError: name 'y' is not defined
# Fix: initialize before conditional
y = None
if False:
y = 20
# Built-in function shadowed
list = [1, 2, 3] # shadows built-in list
list() # TypeError: 'list' object is not callable
# Fix: don't shadow built-ins
data_list = [1, 2, 3]
Error Information
Language
python
Difficulty
Beginner
Views
276
Related Errors
Python
Python ImportError: cannot import name
The module exists but the specific name (function, class) cannot be imported from it.
Python
Python PIL/Pillow Image Not Found
The PIL/Pillow library cannot locate an image file at the specified path.
Python
Python ImportError
Python found the module but failed to load it due to a dependency or attribute issue.
Python
Python AttributeError
The code tries to access an attribute or method that doesn't exist on an object.