How to Fix NameError: name 'X' is not defined in Python
In this tutorial, you'll learn about How to Fix NameError: name 'X' is not defined in Python. We cover key concepts, practical examples, and best practices.
Python raises NameError: name 'X' is not defined when code references a variable, function, or module name that has not been assigned or imported yet.
The Wrong Way
print(message)
message = "Hello"
This produces:
Traceback (most recent call last):
File "script.py", line 1, in <module>
print(message)
NameError: name 'message' is not defined
The Right Way
Define the variable before using it:
message = "Hello"
print(message)
Output:
Hello
Step-by-Step Fix
1. Check the order of definitions
# Wrong -- function called before definition
greet()
def greet():
print("Hi")
# Right -- define first, then call
def greet():
print("Hi")
greet()
Output:
Hi
2. Verify imports are present
# Wrong -- missing import
print(sqrt(25))
# Right
import math
print(math.sqrt(25))
Output:
5.0
3. Check variable scope
Variables defined inside a function are not accessible outside it:
def set_value():
x = 10
set_value()
print(x) # NameError
Move the variable to the global scope or return it:
def get_value():
return 10
x = get_value()
print(x)
Output:
10
4. Look for typos
user_name = "Alice"
print(usern_name) # typo -- NameError
Prevention Tips
- Define all variables at the top of their scope before use.
- Import all modules at the top of the file.
- Use a linter (
flake8,pylint) to catch undefined names before runtime. - Use descriptive variable names to reduce typo risk.
- Run scripts with
python3 -uto get immediate error output.
Common Mistakes with nameerror
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro