You run your program. Python stops and prints this:
NameError: name 'score' is not defined
Python hit a name it has never heard of. Below I explain what that means in plain words. Then I go through six situations that cause it, each with the exact line that breaks and the fix. At the end you get a few habits that keep it from coming back. I ran every example, and the error text is copied from the real output of Python 3.14. Older versions print the same error but skip the Did you mean hint.
What the Error Means
A name is just a word that points to something. It can be a variable, a function or a module. A name only exists once a line of code has created it. You can assign to it (score = 10), define it (def, class) or import it (import math). If Python reads a name that doesn't exist yet, it raises a NameError.
The traceback gives you the line and the name. Look at the name inside the quotes and ask one thing: where was this name supposed to be created, and had that line already run? The six causes below cover almost every case.
The Six Causes
1. A Typo in the Name
# Cause 1: a typo in the variable name
score = 10
print(scor)
This one is the most common. Python cares about spelling and capitals, so scor, Score and score are three different names. Python 3.10 and newer even guess what you meant, like in the error above. Fix the spelling:
# Fix: use the exact name you created
score = 10
print(score)
2. Using a Name Before You Create It
# Cause 2: the variable is used before the line that creates it
print(total)
total = 5 + 7
Python reads a file from top to bottom. When it gets to line 2, total doesn't exist. The line that creates it comes later. Move the assignment up, above the line that uses it:
# Fix: create the variable first, then use it
total = 5 + 7
print(total)
Functions work the same way. Say you call greet() on line 3 but write def greet(): on line 10. The call fails. Define first, call after.
3. Text Without Quotes
# Cause 3: text without quotes is read as a variable name
city = Toronto
print(city)
No quotes means Python reads Toronto as a name. It looks for a variable called Toronto and finds nothing. Quotes are how you tell Python "this is text":
# Fix: put quotes around text
city = "Toronto"
print(city)
Does the name in the error look like a word or value you meant as text? Then this is almost always the cause. Mixing numbers and text is a close cousin of this mistake. I cover it in the post on TypeError: can only concatenate str.
4. The Variable Lives Inside a Function
# Cause 4: the variable only exists inside the function
def make_greeting():
greeting = "Hello"
make_greeting()
print(greeting)
A variable made inside a function lives only while that function runs. Once the function ends, greeting is gone. So line 6 can't find it. The clean fix is to return the value and store it where you need it:
# Fix: return the value and keep it
def make_greeting():
return "Hello"
greeting = make_greeting()
print(greeting)
Seeing the reverse, where Python complains that a variable is used before it's assigned? That's a different error, covered in UnboundLocalError: Variable Referenced Before Assignment.
5. A Module You Did Not Import
# Cause 5: a module is used without importing it
print(math.sqrt(16))
Built-in functions like print() and len() are always there. Everything else needs an import at the top of the file. That includes math, random, os and json. Recent Python versions even put Did you forget to import in the message:
# Fix: import the module first
import math
print(math.sqrt(16))
When the import itself breaks, the error changes. Head to ModuleNotFoundError After pip install.
6. Python 2 Code in Python 3
# Cause 6: raw_input() only exists in Python 2
name = raw_input("Name: ")
print("Hi", name)
Old tutorials and answers lean on raw_input(), unicode() and xrange(). Those only exist in Python 2. Python 3 renamed raw_input() to input() and xrange() to range():
# Fix: Python 3 calls it input()
name = input("Name: ")
print("Hi", name)
Copied code from an old page, and it fails on a name you never wrote? Check whether that page dates from the Python 2 days.
How to Find the Cause Fast
Try these three checks, one after another. You'll be done in under a minute.
1. Read the name. Check what's between the quotes in the error. Do you spell it that way every time?
2. Search upward. Begin at the line that failed and look up the file for where the name gets made. Can't find it? You're looking at cause 2, 3 or 5. Sitting inside a function? That's cause 4.
3. Print what exists. Drop in print(dir()) for a quick test. You'll see every name Python knows at that point. Your name missing from the list means Python is right.
How to Stop It From Happening Again
Pick an editor that underlines unknown names. VS Code with the Python extension paints an undefined name red before you even run the file.
Imports first, definitions before use. Stick to one order: imports, functions, then the code that calls them. Cause 2 and cause 5 go away.
Return values instead of reaching for them. If a function builds something you need later, hand it back with return. Cause 4 goes away.
Copy and paste names. With a long variable name, don't retype it. Paste it. Cause 1 goes away.
Quick Reference
| What you see | Cause | Fix |
|---|---|---|
| A name that is almost one you wrote | A typo | Fix the spelling and capitals |
| The name is created lower in the file | Used before it exists | Move the creating line above it |
| The name looks like your text | Missing quotes | Write "text"
|
| The name is created in a function | Scope |
return the value |
The name is a module such as math
|
No import | import math |
raw_input, xrange, unicode
|
Python 2 code |
input, range, str
|
The Rule, Stated Once
NameError: name 'x' is not defined means no line had created x by the time Python reached it. So find the line that should create it. Check the spelling. Make sure it runs before the failing line. Then make sure it isn't hidden inside a function or behind a missing import.
Other Python errors have just as clear a cause. Have a look at KeyError, TypeError: NoneType is not subscriptable and IndexError: list index out of range. New to Python? Start with Python for Beginners.
Download the code: the broken and fixed versions of all six examples are on GitHub in Python-projects/Troubleshooting/nameerror. To run one, open its folder and type python bug.py.
Top comments (0)