NameError in Python — What It Means and How to Fix It

What Python's NameError exception means and how to resolve it.

Published October 27, 2026

NameError is raised when you use a variable or function name that has not been defined in the current scope.

What it means and why it happens

Typical causes: typos, using a name before assignment, scope mistakes or forgetting to import.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
NameError: name 'total' is not defined

Practical examples

Code that triggers it

print(total)
total = 5

The fix

total = 5
print(total)

Import what you use

import math
print(math.sqrt(16))

Common mistakes

  • Using a variable before it is assigned.
  • Misspelt names.
  • Forgetting imports.

Key takeaways

  • NameError: NameError is raised when you use a variable or function name that has not been defined in the current scope.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

NameError vs UnboundLocalError?

UnboundLocalError happens when a local variable is used before assignment inside a function.

How do I find which line caused NameError?

The error message and stack trace show the file and line; start there and work backwards.

More Python articles