blog / errors explained

how to fix a Python NameError: causes and solutions

by Luke published 8 min read

the short answer

A NameError means Python met a name it does not recognise. The usual causes are a typo or wrong capital letter, text without quotes, using a variable before the line that creates it, a name made inside a function or an if that did not run, or a module that was never imported. Read the last line of the error, find the name it mentions, and check where that name is made.

A NameError means Python met a name it does not know. It looked for a variable, function or module with that name, found nothing, and stopped:

try it · python
Print("Hello!")
  File "<exec>", line 1, in <module>
NameError: name 'Print' is not defined. Did you mean: 'print'?

Here the name is Print with a capital P, and Python only knows print. The fix is one letter. Most NameErrors are that quick once you know where to look. This guide shows how to read the message, then walks through each common cause with a box that triggers it and the fix.

How to read the message

Start with the last line. It names the error and the name Python could not find, here 'Print'. The line above says where it happened: line 1. In a longer program there may be more lines above, showing how Python got there, but the last two are what you need first.

Python also checks for similar names that do exist. When it finds a close match, it adds a Did you mean suggestion. That hint is often the whole answer.

Why the error appears halfway through

Python only checks a name when it reaches the line that uses it. Everything above that line has already run:

try it · python
print("Starting")
print(scroe)
print("Never reached")
Starting
  File "<exec>", line 2, in <module>
NameError: name 'scroe' is not defined

So a NameError can hide for a long time in a part of the program that rarely runs, such as inside a function nobody has called yet. Mistakes in the shape of the code, like a missing bracket, are different: Python spots those before running anything, as a SyntaxError.

Cause 1: a typo or the wrong capitals

try it · python
player_name = "Sam"
print(player_nme)
  File "<exec>", line 2, in <module>
NameError: name 'player_nme' is not defined. Did you mean: 'player_name'?

Python is case-sensitive and spelling-sensitive, so player_nme, Player_name and player_name are three unrelated names. Copy the name from the line where you made it rather than retyping it.

Built-in names count too. lenght(fruits) gives a NameError, because the real function is len.

Cause 2: text without quotes

try it · python
print(hello)
  File "<exec>", line 1, in <module>
NameError: name 'hello' is not defined. Did you mean: 'help'?

Without quotes, hello is a name, not text, so Python looks for a variable called hello. Its suggestion, help, is a real built-in name, but not what you meant. Add the quotes: print("hello").

Cause 3: using a name before it exists

Python runs a program from top to bottom. A variable only exists once the line that makes it has run:

try it · python
print(total)
total = 5
  File "<exec>", line 1, in <module>
NameError: name 'total' is not defined

The same goes for functions. A def line makes the function when Python reaches it, so calling it any earlier fails:

try it · python
greet("Ava")

def greet(name):
    print("Hello, " + name)
  File "<exec>", line 1, in <module>
NameError: name 'greet' is not defined

Move the def above the call, or put the calls at the bottom of your file.

Cause 4: a name made only on one path

If a variable is made inside an if, it only exists when that branch runs:

try it · python
age = 9
if age > 12:
    group = "teen"
print(group)
  File "<exec>", line 4, in <module>
NameError: name 'group' is not defined

This one is sneaky, because the program works for some ages and fails for others. Give the variable a starting value before the if:

try it · python
age = 9
group = "child"
if age > 12:
    group = "teen"
print(group)
child

Cause 5: a name made inside a function

Variables made inside a function belong to that function. They vanish when it finishes:

try it · python
def make_total():
    total = 5 + 3

make_total()
print(total)
  File "<exec>", line 5, in <module>
NameError: name 'total' is not defined

Hand the value back with return, and store it where you call the function:

try it · python
def make_total():
    total = 5 + 3
    return total

total = make_total()
print(total)
8

Cause 6: a missing import

Modules like math and random have to be imported before you use them:

try it · python
print(math.sqrt(16))
  File "<exec>", line 1, in <module>
NameError: name 'math' is not defined. Did you forget to import 'math'

Add import math at the top of the file. The run boxes use Python 3.12. Newer versions show the same message with a question mark at the end.

Watch out for the other style of import too. After from math import sqrt, you write sqrt(16) on its own. That line brings in only the name sqrt, so math.sqrt(16) still gives a NameError for math.

Cause 7: true, false and none in small letters

try it · python
done = true
  File "<exec>", line 1, in <module>
NameError: name 'true' is not defined. Did you mean: 'True'?

In Python they are True, False and None, each with a capital letter. Many other languages use small letters, so this one catches people who already know JavaScript or PHP.

A close cousin: UnboundLocalError

This error is a kind of NameError, and it only happens inside functions:

try it · python
count = 0

def add_one():
    count = count + 1

add_one()
  File "<exec>", line 4, in add_one
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

Because the function assigns to count, Python treats count as the function’s own variable. Reading it on the right of the = then fails, since that local version has no value yet. The cleanest fix is to pass the value in and return the new one:

try it · python
count = 0

def add_one(number):
    return number + 1

count = add_one(count)
print(count)
1

A checklist for any NameError

  1. Read the last line and note the exact name, capitals included.
  2. Search your code for where that name is made.
  3. If it is never made, it is a typo, missing quotes or a missing import.
  4. If it is made below the error line, move it up.
  5. If it is made inside an if, a loop or a function, make sure that line actually runs before you use the name.

Common mistakes

Silencing the error instead of fixing it

Adding total = 0 near the top makes the NameError go away, but if the real problem was a typo elsewhere, your program now quietly uses the wrong value. Find out why the name was missing first.

Reaching for global

Writing global count inside a function does fix UnboundLocalError, but it makes functions depend on outside variables, which leads to harder bugs later. Passing values in and returning them, as above, is easier to follow.

Accepting every suggestion

Did you mean is a guess based on spelling. In cause 2 it suggested help when the real fix was quotes. Check the suggestion makes sense before you use it.

Fixing one error and stopping

Python stops at the first error it meets. After a fix, run the program again: there may be another NameError further down.

A short exercise

This program should print Total: 12, but it has four NameErrors. Run it, fix the name the error points at, and repeat until it works:

try it · python
rolls = [4, 2, 6]
total = 0
for roll in rols:
    total = total + rol
Print("Total:", totl)
  File "<exec>", line 3, in <module>
NameError: name 'rols' is not defined. Did you mean: 'rolls'?

To make your fixes, copy the code into the playground from the button at the bottom of the page and choose Python.

One possible answer

try it · python
rolls = [4, 2, 6]
total = 0
for roll in rolls:
    total = total + roll
print("Total:", total)
Total: 12

The four fixes: rols to rolls, rol to roll, Print to print and totl to total.

Your next step

Every programmer meets NameErrors, and reading them calmly is a skill that grows with practice. Gwecode’s Python Level 1 has a whole lesson on what to do when code goes wrong, and every lesson ends with a fix-the-bug challenge, so you get plenty of safe practice. Its level check is a tiny quiz game you build yourself. Every lesson is free and runs in your browser. Create a free account to keep your progress, and try the lesson below.

practise this · python · lessonWhen it goes wrongstart the lesson

questions

What does is not defined mean in Python?

Python looked for a variable, function or module with that name and found nothing. Either it was never made, it was made later in the program, or it was spelled differently.

Is Python case-sensitive?

Yes. print and Print are different names, and so are score and Score. Most NameErrors from a single wrong capital letter come with a Did you mean suggestion.

Why does Python suggest a different name?

Since Python 3.10, a NameError looks for similar names that do exist and suggests the closest one. It is usually right, but check before you accept it.

What is the difference between NameError and UnboundLocalError?

UnboundLocalError is a kind of NameError. It happens inside a function that assigns to a name and also reads it before the assignment. Python treats the name as local to that function, so the outside value is not used.

Can a NameError happen in code that worked before?

Yes. If a name is only made inside an if, the program works whenever that branch runs and fails when it does not. Give the variable a value before the if.

keep going.