Skip to content

How to Fix NameError: name 'X' is not defined in Python

DodaTech Updated 2026-06-24 2 min read

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 -u to get immediate error output.

Common Mistakes with nameerror

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. 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

### Why does Python not check for NameError at compile time?

Python is dynamically typed and resolves names at runtime. A variable might be defined conditionally, so the interpreter cannot know until execution. Only linters can catch undefined names before running.

Can a NameError happen inside a function that is never called?

Yes, but only if that function is actually executed. Python does not check function bodies until they run. A function with an undefined name compiles without error and only fails when called.

What is the difference between NameError and AttributeError?

NameError means the name itself is not defined in any namespace. AttributeError means the name exists but does not have the attribute you are trying to access. For example, None.foo raises AttributeError, not NameError.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro