NameError: Name is Not Defined in Python

I was debugging a Python project where I kept running into the error:

NameError: name 'x' is not defined

At 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 defined

Here, 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:

  1. Using a variable before declaring it
  2. Misspelling names
  3. Incorrect scope (local vs global variables)
  4. Using undefined functions
  5. 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.

name is not defined python

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.

python nameerror

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 function

To 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.

nameerror python

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 defined

Correct way:

def greet():
    print("Hello from Python")

greet()

You can refer to the screenshot below to see the output.

python name is not defined

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:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.