Skip to content
NameError: name '...' is not defined

NameError: name '...' is not defined

DodaTech 2 min read

NameError: name '...' is not defined means you tried to use a variable, function, or class name that Python hasn’t seen before in the current scope.

What It Means

Python’s namespace doesn’t contain the name you’re referencing. Either it was never assigned, it was assigned in a different scope, or there’s a typo in the name.

Why It Happens

  • Variable or function used before it’s defined (order of code matters)
  • Typo in the variable name
  • Variable defined in a different scope (inside a function vs global)
  • Forgot to import a module
  • Variable defined inside an if __name__ == "__main__" guard
  • Misspelled built-in function name

How to Fix It

Step 1: Define before you use

# BAD — using total before it exists
print(total)
total = sum([1, 2, 3])

# GOOD — define first, then use
total = sum([1, 2, 3])
print(total)

Step 2: Check for typos

# BAD
first_name = "Alice"
print(firts_name)  # typo: firts_name vs first_name

# GOOD
first_name = "Alice"
print(first_name)

Step 3: Understand scope

Variables defined inside a function aren’t accessible outside it:

# BAD
def compute():
    result = 42

print(result)  # NameError: name 'result' is not defined

# GOOD — return the value
def compute():
    return 42

result = compute()
print(result)

Step 4: Import the module you need

# BAD
print(math.sqrt(16))  # NameError: name 'math' is not defined

# GOOD
import math
print(math.sqrt(16))

Step 5: Check for missing quotes

# BAD — Python thinks 'hello' is a variable name
print(hello)

# GOOD — quotes make it a string
print("hello")

Step 6: Verify built-in names aren’t overwritten

# BAD — you accidentally overwrote 'list'
list = [1, 2, 3]
print(list("abc"))  # TypeError or NameError

# GOOD — don't use built-in names as variable names
my_list = [1, 2, 3]
print(list("abc"))  # Works fine
Why does NameError appear even though the variable is defined in my file?
Check if the variable is defined inside a function or an if block that didn’t execute. Variables defined inside a function are local to that function. Also check if the variable is defined after the line that uses it — Python runs code top-to-bottom.
What's the difference between NameError and UnboundLocalError?
UnboundLocalError is a subclass of NameError. It happens when you reference a local variable before assigning it within the same function (often due to a variable being used both locally and globally). Use global or nonlocal declarations to fix it.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro