The NameError occurs when you try to use a variable, function, or module name that Python doesn't recognize. This means the name hasn't been defined yet, is misspelled, or is out of scope.
# ❌ Problem
print(message) # NameError: name 'message' is not defined
# ✅ Solution: Define the variable first
message = "Hello, World!"
print(message)
# ✅ Check for typos
username = "John"
print(username) # Not 'userName' or 'user_name'
The most common cause - trying to use a variable before it has been assigned a value.
Misspelling a variable name or using incorrect case (Python is case-sensitive).
Trying to access a variable defined inside a function from outside, or vice versa.
Using a module or function without importing it first.
Forgetting quotes around strings makes Python think it's a variable name.
print(total) # NameError!
total = 100
total = 100 # Define first
print(total) # Then use
user_name = "Alice"
print(username) # NameError: 'username' vs 'user_name'
firstName = "Bob"
print(firstname) # NameError: case mismatch!
user_name = "Alice"
print(user_name) # Exact match
firstName = "Bob"
print(firstName) # Exact case match
# Use consistent naming convention (snake_case recommended)
user_name = "Alice"
first_name = "Bob"
def calculate():
result = 100
print(result) # NameError: result is local to calculate()
# Solution 1: Return the value
def calculate():
result = 100
return result
result = calculate()
print(result)
# Solution 2: Use global variable (not recommended)
result = 0
def calculate():
global result
result = 100
calculate()
print(result)
# Solution 3: Define outside function
result = 100
def calculate():
print(result) # Can read global variable
calculate()
result = math.sqrt(16) # NameError: name 'math' is not defined
data = json.loads('{"key": "value"}') # NameError!
import math
result = math.sqrt(16)
import json
data = json.loads('{"key": "value"}')
# Or import specific functions
from math import sqrt
result = sqrt(16)
from json import loads
data = loads('{"key": "value"}')
name = Alice # NameError: name 'Alice' is not defined
print(Hello) # NameError!
name = "Alice" # Add quotes for strings
print("Hello") # Strings need quotes
NameError occurs when you try to use a variable, function, or module name that hasn't been defined, is misspelled, or is out of scope.
Define the variable before using it, check for typos, ensure correct case, import required modules, or check if the variable is in the correct scope.
Check for typos, case sensitivity (Python is case-sensitive), or scope issues. The variable might be defined in a different function or block.
NameError means the name itself doesn't exist. AttributeError means the object exists but doesn't have the attribute you're trying to access.
Use a Python-aware IDE with autocomplete, run linters like pylint or flake8, follow PEP 8 naming conventions, and always define variables before use.
Explore 500+ free tutorials across 20+ languages and frameworks.