🔧 Error Fixes
· 1 min read

Python NameError: Name 'X' Is Not Defined — How to Fix It


NameError: name 'my_variable' is not defined

Python can’t find a variable, function, or module with that name. It either doesn’t exist, is misspelled, or isn’t in scope.

Fix 1: Typo in the name

The most common cause:

# ❌ Typo
username = "Alice"
print(usrname)  # NameError!

# ✅ Correct spelling
print(username)

Python is case-sensitive:

# ❌ Wrong case
Name = "Alice"
print(name)  # NameError! 'name' ≠ 'Name'

Fix 2: Using a variable before defining it

# ❌ Used before assignment
print(total)
total = 100

# ✅ Define first
total = 100
print(total)

Fix 3: Missing import

# ❌ Forgot to import
data = json.loads('{"key": "value"}')  # NameError: name 'json' is not defined

# ✅ Import first
import json
data = json.loads('{"key": "value"}')

Common ones people forget: os, sys, json, re, math, random, datetime.

Fix 4: Variable defined inside a function (scope)

# ❌ Variable only exists inside the function
def calculate():
    result = 42

calculate()
print(result)  # NameError!

# ✅ Return it
def calculate():
    return 42

result = calculate()
print(result)  # 42

Fix 5: Variable defined inside an if block that didn’t run

# ❌ If the condition is False, 'message' never gets created
if False:
    message = "hello"

print(message)  # NameError!

# ✅ Define a default
message = "default"
if some_condition:
    message = "hello"
print(message)

Fix 6: Using Python 2 syntax in Python 3

# ❌ Python 2 syntax
print "hello"  # SyntaxError in Python 3

# ✅ Python 3
print("hello")
📘