NameError
Core Python Errors and Exceptions Error explained

Python NameError

1NameError: overview

A NameError means Python looked for a name (a variable, function or module) in every scope it checks and found nothing called that, so the line cannot run.

GoalBy the end you can read a NameError traceback, identify which of six common causes triggered it and fix it.

Before this lesson: Python Variables, Python Exceptions: try, except, else and finally

2NameError: diagram

Python NameErrorBuilt-in scope (searched last)print, len, sum, True, NoneGlobal scope (the module)price = 20, import math, def add_tax(...)Local scope (inside add_tax)total = price * 1.2Python searches inside-out. If the name is in no layer: NameError: name 'x' is not defined
Python checks the innermost scope first and moves outwards. Names created in another function, or not created yet, are not in any layer it can see, so the lookup fails with a NameError.

3NameError: explained step by step

A NameError means Python met a name (a variable, function or module) that it has never heard of at that moment. The message always quotes the culprit: NameError: name 'totl' is not defined. Nothing is wrong with the line's grammar; Python simply looked for that name and found nothing.

What "name is not defined" really means

When Python reads a name, it searches in a fixed order: the current function, any enclosing functions, the module (global) level, and finally the built-ins such as print and len. If none of them holds the name, you get a NameError. The search happens when the line runs, not when the file is read. That is why a program can print several lines and then crash. For the full lookup rules see Python scope.

Python
price = 20
try:
    print(prce * 2)
except NameError as err:
    print("NameError:", err)
    print("Missing name:", err.name)

How to read a NameError traceback

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(totl / len(prices))
          ^^^^
NameError: name 'totl' is not defined. Did you mean: 'total'?
  1. Read the last line first: it names the missing word.
  2. The line above shows the file and line number, and the ^^^^ marks exactly where the name appears.
  3. If you see Did you mean, Python found a similar name. That is usually your typo.
  4. Ask yourself one question: "Was this name created before this line ran, and in a place this line can see?"

Cause 1: a typo or the wrong capitalisation

Python is case-sensitive, so Total, total and totl are three different names. The same goes for built-ins: it is print, not Print, and True, not true. Values copied from JSON (true, null) cause this too.

Python
total = 99
try:
    print(Total + 1)
except NameError as err:
    print("NameError:", err)

try:
    active = true
except NameError as err:
    print("NameError:", err)

active = True
print("Fixed:", total + 1, active)

Cause 2: using a name before you assign it

Python runs top to bottom. A variable or a function must exist before the line that uses it. Calling a function above its def is the most common version of this, and so is a variable that only gets a value inside an if branch that never ran.

Python
try:
    welcome("Asha")
except NameError as err:
    print("NameError:", err)

def welcome(name):
    return f"Welcome, {name}!"

print(welcome("Asha"))

Move the def (or the assignment) above the first use. Learn more about defining functions in Python functions and about naming values in Python variables.

Cause 3: forgetting the quotes around text

Without quotes, Python treats Asha as a name to look up instead of a piece of text. If you meant a string, wrap it in quotes.

Python
try:
    print(Asha)
except NameError as err:
    print("NameError:", err)

print("Asha")

Cause 4: forgetting to import a module

Modules such as math or random are not available until you import them. Using math.sqrt(16) without import math gives name 'math' is not defined. Put imports at the top of the file. More in Python modules.

Python
try:
    print(math.sqrt(16))
except NameError as err:
    print("NameError:", err)

import math
print(math.sqrt(16))

Cause 5: a variable that lives in another scope

A variable created inside a function exists only while that function runs. Code outside cannot see it. Return the value instead of hoping it leaks out.

Python
def add_tax(price):
    total = price * 1.2
    return total

add_tax(50)
try:
    print(total)
except NameError as err:
    print("NameError:", err)

total = add_tax(50)
print(total)

Cause 6: deleting a name with del

del total removes the name completely. Any later use raises a NameError, which can surprise you when del sits in a cleanup step. Assign the name again, or avoid deleting it.

A defensive pattern: define before you branch

If a value is created only inside an if or a loop, give it a starting value first. That way the name always exists, even when the branch never runs. Reserve try/except NameError for experiments, not for normal control flow (see Python exceptions).

Python
scores = [55, 62, 48]
best = None                      # always defined
for score in scores:
    if score > 90:
        best = score
print("Best above 90:", best)

NameError vs UnboundLocalError vs AttributeError

  • NameError: the name does not exist anywhere Python looked.
  • UnboundLocalError: the name exists in a function but was read before it got a value. It is a subclass of NameError.
  • AttributeError: the name exists, but the object has no such attribute, like math.sqroot.
Python
import math
print(issubclass(UnboundLocalError, NameError))
try:
    math.sqroot(4)
except AttributeError as err:
    print("AttributeError:", err)

If the line has a grammar problem instead, you get a SyntaxError, which is reported before any line runs.

4NameError: syntax

NameError: name 'x' is not defined          # message format
x = 10                       # define a name before using it
import math                  # import a module before math.sqrt(...)
from math import sqrt        # or import just the function
"Asha"                       # quotes make text, Asha is a name
result = my_function()       # return values out of functions
best = None                  # give a default before a branch or loop

5NameError: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
prices = [20, 35, 15]
total = sum(prices)

try:
    print("Average:", totl / len(prices))
except NameError as err:
    print("NameError:", err)

try:
    print(math.sqrt(total))
except NameError as err:
    print("NameError:", err)

import math
print("Average:", total / len(prices))
print("Root:", round(math.sqrt(total), 2))
Expected outputNameError: name 'totl' is not defined
NameError: name 'math' is not defined
Average: 23.333333333333332
Root: 8.37

7NameError: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1-2prices and total are created, so both names exist from here on.
  2. Line 4-7totl is a typo. Python finds no such name and raises a NameError. The except block prints the message, so the program continues.
  3. Line 9-12math has not been imported yet when this line runs, so Python cannot find it. Imports run in order like any other statement.
  4. Line 14import math binds the name math from this point onwards. Earlier lines were not affected.
  5. Line 15-16With the correct spelling and the module imported, both calculations work.

8NameError: common mistakes

A typo in a variable name

✗ Wrong

prices = [20, 35, 15]
total = sum(prices)
print(totl / len(prices))
NameError: name 'totl' is not defined. Did you mean: 'total'?

✓ Right

prices = [20, 35, 15]
total = sum(prices)
print(total / len(prices))

The name in the message does not match any variable you created. Compare it with the assignment letter by letter and use the spelling Python suggests.

Text without quotes

✗ Wrong

print(Asha)
NameError: name 'Asha' is not defined

✓ Right

print("Asha")

A bare word is a variable name, not text. Wrap it in quotes so Python treats it as a string.

Using a module without importing it

✗ Wrong

print(math.sqrt(16))
NameError: name 'math' is not defined. Did you forget to import 'math'?

✓ Right

import math
print(math.sqrt(16))

Import the module before you use it, ideally at the top of the file.

Reading a variable that only exists inside a function

✗ Wrong

def make_total(price):
    total = price * 2

make_total(5)
print(total)
NameError: name 'total' is not defined

✓ Right

def make_total(price):
    total = price * 2
    return total

total = make_total(5)
print(total)

total disappears when the function ends. Return it and store the returned value in a variable outside.

Calling a function before it is defined

✗ Wrong

say_hi("Asha")

def say_hi(name):
    print("Hi", name)
NameError: name 'say_hi' is not defined

✓ Right

def say_hi(name):
    print("Hi", name)

say_hi("Asha")

Python runs from top to bottom, so the def must run before the call. Move the definition above the call.

9NameError: exercises

Write your answer, then press Check. The checks run in your browser.

1. Fix the misspelled variable

Fix the bug Easy

This code should store 10% of the cart subtotal in tax and print it. It raises a NameError. Fix the misspelling without renaming subtotal.

Your code
cart = [12.5, 8, 4.5]
subtotal = sum(cart)
tax = subtotl * 0.1
print(tax)

2. Predict the NameError output

Predict the output Easy

Read the code and type exactly what it prints. Then press Check.

Read this code
def make_label():
    label = "sale"
    return label

try:
    print(label)
except NameError:
    print("no label yet")

label = make_label()
print(label)
del label

try:
    print(label)
except NameError as err:
    print(err)

2 more exercises → 6 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

Why do I get NameError: name 'x' is not defined when I just defined x?

Usually one of three things: the assignment runs after the line that uses it, x lives inside a function and you are reading it outside, or the spelling or capitalisation differs. Python reads top to bottom, so print the name right before the failing line to confirm it exists there.

How do I fix NameError: name 'math' is not defined?

Add import math at the top of the file, or use from math import sqrt to bring in a single function. Modules such as math, random and datetime are never available until you import them.

What is the difference between NameError and UnboundLocalError?

NameError means the name does not exist at all. UnboundLocalError (a subclass of NameError) means the name is assigned somewhere inside the current function, so Python treats it as local, but you read it before it received a value.

Further reading

10Next lesson

Up nextPython SyntaxErrorA SyntaxError means Python could not parse your code because it breaks the language's grammar, so the whole file is rej…

Related:
Python Variable ScopePython Exceptions: try, except, else and finallyPython SyntaxErrorPython UnboundLocalError

← Python IndexError: list index out of range · All Errors and Exceptions lessons · Practise in the IDE