I was debugging a Python project where I kept running into the error:
NameError: name 'x' is not definedAt first, it was frustrating. I had been coding in Python for over a decade, yet this error still popped up in the simplest scripts.
The truth is, this error is one of the most common Python mistakes. It usually happens when Python cannot find a variable, function, or module name you are trying to use.
In this tutorial, I’ll explain why this error happens and show you multiple ways to fix it. I’ll also share real-world examples that I’ve personally encountered. So you can avoid the same mistakes.
What Does “NameError: name is not defined” Mean?
In Python, every variable or function must be defined before you use it. If Python doesn’t recognize the name you typed, it throws a NameError.
For example:
print(city)Output:
NameError: name 'city' is not definedHere, Python doesn’t know what city is because we never defined it.
Common Causes of NameError
From my experience, there are a few frequent reasons why this error occurs:
- Using a variable before declaring it
- Misspelling names
- Incorrect scope (local vs global variables)
- Using undefined functions
- Forgetting to import a module
Let’s go through each one with examples.
Method 1 – Define the Variable Before Using It
One of the most common mistakes is using a variable before assigning a value.
# Wrong
print(state)
# Correct
state = "California"
print(state)You can refer to the screenshot below to see the output.

When I was working on a U.S. census data project, I once tried to print variables before assigning them. The fix was as simple as defining them first.
Method 2 – Fix Spelling Mistakes
Python is case-sensitive. If you mistype a variable name, you’ll see this error.
# Wrong
City = "New York"
print(city) # lowercase 'c'
# Correct
city = "New York"
print(city)You can refer to the screenshot below to see the output.

I’ve lost count of how many times I made this mistake when analyzing city-level datasets. Always double-check your spelling and capitalization.
Method 3 – Check Variable Scope
Sometimes, a variable is defined inside a function but is not accessible outside it.
def get_state():
state = "Texas"
print(state)
get_state()
print(state) # Error: state not defined outside functionTo fix this, you can return the variable or declare it globally.
def get_state():
state = "Texas"
return state
state = get_state()
print(state)You can refer to the screenshot below to see the output.

This method demonstrates that variables defined inside a function are local and inaccessible outside, so returning them or declaring them globally fixes the issue.
Method 4 – Define Functions Before Calling Them
Another common cause is calling a function before defining it.
# Wrong
greet()
def greet():
print("Hello from Python")Output:
NameError: name 'greet' is not definedCorrect way:
def greet():
print("Hello from Python")
greet()You can refer to the screenshot below to see the output.

This method shows that functions must be defined before being called in Python to avoid a NameError.
Method 5 – Import Modules Correctly
If you forget to import a module, Python won’t recognize it.
# Wrong
print(math.sqrt(25))
# Correct
import math
print(math.sqrt(25))I once ran into this while working with U.S. financial data and forgot to import pandas. Always check your imports.
Method 6 – Use try/except to Handle Undefined Variables
Sometimes, you may not be sure if a variable exists. In such cases, you can handle it gracefully with try/except.
try:
print(city)
except NameError:
print("The variable 'city' is not defined yet.")This is especially useful in large projects where variables may or may not be initialized.
Method 7 – Check if a Variable is Defined
You can also check if a variable exists before using it.
if 'city' in globals():
print(city)
else:
print("city is not defined")This prevents the program from crashing unexpectedly.
Real-World Example: U.S. Sales Data
Imagine you’re analyzing U.S. sales data for different states. If you mistype a variable name, you’ll hit a NameError.
sales = {"California": 5000, "Texas": 3000}
# Wrong
print(Sales["California"])
# Correct
print(sales["California"])Python is strict about names, so always double-check dictionary keys and variable names.
Quick Checklist to Avoid NameError
Whenever I hit this error, I go through this quick checklist:
- Did I define the variable before using it?
- Did I spell the name correctly (case-sensitive)?
- Am I calling the function after defining it?
- Did I import all required modules?
- Is the variable in the correct scope?
The NameError: name is not defined is one of the first errors Python beginners encounter, and even experienced developers like me still run into it.
The good news is that it’s easy to fix once you know the common causes: undefined variables, misspellings, scope issues, missing imports, or calling functions too early.
Next time you see this error, walk through the checklist I shared. With practice, you’ll be able to spot and fix it in seconds.
You may also read other Python articles:
- Use Python Functions with Optional Arguments
- Use Lambda Functions in Python
- Use the Python Main Function with Arguments
- Set Global Variables in Python Functions

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.