
When programming in Python, encountering the error:
NameError: name 'xyz' is not defined
is common, especially for beginners. This error indicates that Python is trying to use a variable or function that has not been defined or is not accessible at the point where it’s being called. While the error may seem intimidating at first, the solution is often straightforward. This guide will help you understand what causes this error, how to debug it, and how to avoid it in your future code.
What Is a NameError in Python?
In Python, a NameError
is raised when the interpreter encounters a name (variable, function, or object) that it does not recognize. This usually means that:
- The name has not been defined yet.
- The name is out of scope.
- The name is misspelled.
- The required module or function has not been imported.
Python executes code from top to bottom. Therefore, any reference to a name that appears before its definition will result in a NameError
.
Common Scenarios That Cause NameError
1. Misspelled Variable or Function Name
One of the most frequent causes of NameError
is a typo in a variable or function name. Python is case-sensitive, so even a small error in spelling or casing can lead to this issue.
Incorrect Code:
username = "Alice"
print(usernme) # Misspelled variable name
Corrected Code:
username = "Alice"
print(username)
2. Using a Variable Before It Is Defined
You must define or assign a value to a variable before using it. Referencing a variable before assignment causes a NameError
.
Incorrect Code:
print(score)
score = 10
Corrected Code:
score = 10
print(score)
3. Referencing a Variable Outside Its Scope
If a variable is defined inside a function, it is local to that function and cannot be accessed outside of it.
Incorrect Code:
def calculate():
result = 100
print(result) # result is not accessible here
Corrected Code:
def calculate():
result = 100
return result
print(calculate())
4. Calling a Function Before Defining It
Python requires that functions be defined before they are called. If you try to use a function before its definition, it will raise a NameError
.
Incorrect Code:
greet("Alice")
def greet(name):
print(f"Hello, {name}")
Corrected Code:
pythonCopyEditdef greet(name):
print(f"Hello, {name}")
greet("Alice")
5. Using Modules or Functions Without Importing Them
If you use a function or class from a module like math
or random
without importing it, Python will not recognize it.
Incorrect Code:
print(sqrt(16)) # sqrt is not defined
Corrected Code:
from math import sqrt
print(sqrt(16))
Alternatively:
import math
print(math.sqrt(16))
How to Debug a NameError in Python
To effectively debug a NameError
, follow these steps:
- Check the Error Message
The error message includes the line number where the problem occurred. Read it carefully to identify which name caused the error. - Verify Variable and Function Names
Review spelling, capitalization, and scope of the name in question. - Check the Order of Execution
Make sure the variable or function is defined before it is used. - Use a Python IDE or Linter
Tools like VS Code, PyCharm, pylint, or flake8 can highlight undefined variables or functions in real time. - Print Debug Statements
Insertprint()
statements before the error line to confirm the existence and value of the variable or object.
Best Practices to Avoid NameError
- Define Before Use: Always define your variables, functions, and objects before referencing them.
- Use Consistent Naming Conventions: Stick to lowercase_with_underscores for variable names to improve readability and consistency.
- Modular Imports: Always import required modules at the beginning of your scripts.
- Avoid Hardcoding or Copy-Paste Errors: Manually typed and reviewed code is less error-prone than copied code.
- Test in Small Chunks: Run small sections of your script regularly to catch errors early.
- Initialize Variables Clearly: Even if a value is not known yet, initialize with
None
or a placeholder to avoid future NameErrors.
Example: Putting It All Together
Here’s a small program that avoids all the common mistakes:
import math
def calculate_area(radius):
area = math.pi * radius ** 2
return area
radius = 5
result = calculate_area(radius)
print(f"The area of the circle is {result:.2f}")
This example properly imports required modules, defines functions before calling them, and ensures all variables are declared before use.
Conclusion
The NameError: name 'xyz' is not defined
message may look intimidating at first, but it’s actually a helpful indicator that something is missing or out of order in your code. Understanding how Python handles name resolution, scope, and execution flow will help you identify and correct these errors more quickly and confidently. By following good coding practices and using the right tools, you can reduce the chances of encountering this error in your future Python projects.

I’m Shreyash Mhashilkar, an IT professional who loves building user-friendly, scalable digital solutions. Outside of coding, I enjoy researching new places, learning about different cultures, and exploring how technology shapes the way we live and travel. I share my experiences and discoveries to help others explore new places, cultures, and ideas with curiosity and enthusiasm.