On this page
article
NameError: name 'x' is not defined (variant 8)
How to fix NameError in Python — name ‘x’ is not defined.
Error Message
NameError: name 'x' is not defined
What It Means
Python raised NameError because something in your code violated language rules or runtime expectations.
Common Causes
- Typo in variable, function, or module name
- Wrong data type for the operation
- Missing import or uninstalled dependency
- Incorrect indentation or syntax
How to Fix
Define the variable before use; check spelling and scope.
Example
# Problem scenario related to NameError
# ... code that triggers the error ...
# Fixed version
# Apply the fix described above
Prevention
- Run
python -m py_compile script.pybefore committing - Use a linter (
ruff,flake8) and type checker (mypy) - Write tests for edge cases (empty input, None, zero)