NamePython Error

NameError

NameError: name 'foo' is not defined

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    result = calcualte_total(items)  # typo in function name
NameError: name 'foo' is not defined

What causes this error

A name was used that has not been defined in local, enclosing, global, or built-in scope. Typos, missing imports, and using variables before assignment are the typical causes.

How to fix it

Check spelling of the variable name carefully. Add missing import statements. Define variables before using them. Use an IDE with autocompletion and linting to catch these early.

Code that causes this error

Broken
result = calcualte_total(items)  # typo in function name

Fixed code

Fixed
result = calculate_total(items)

About NameError

This specific NameError message indicates that a name was used in code before being defined in any accessible scope. The Python interpreter follows the LEGB rule when looking up names: Local, Enclosing, Global, Built-in. If the name is not found in any of these scopes, NameError is raised.

The most common causes are simple typos (e.g., `pritn` instead of `print`), using a variable before assigning it, forgetting to import a module or name, and referencing a variable from a different function without passing it as an argument. Python 3.12+ includes helpful suggestions like 'Did you mean: foo_bar?' when a similar name exists. Case sensitivity also matters — `True` is defined but `true` is not.

When the error mentions a common function or class name, it usually means a missing import statement.

Common scenarios

1

Typos in variable or function names that are hard to spot

2

Using a variable before it has been assigned a value

3

Forgetting to import a module or function before using it

4

Variable shadowing issues between local and global scope

Related errors