Skip to content
Happy Programming Guide
Start learning
Python

Fixing “NameError: name is not defined” in Python

Python cannot find a name at the moment you used it. A typo, a variable used before it was assigned, a function called before it was defined, or a scope problem. Each has a tell.

A laptop computer on a table

NameError: name 'x' is not defined means that when Python reached that line, no variable, function, class or module called x existed in any scope it could see. The name in the message is exact, which makes this one of the more helpful errors: it is spelt wrong, it has not been created yet, it was created somewhere Python cannot see from here, or it was never imported.

Cause 1: it is spelt differently#

Python
user_name = "ada"
print(username)          # NameError: name 'username' is not defined. Did you mean: 'user_name'?

Python is case-sensitive and does not fuzzy-match. Recent versions add a “Did you mean” suggestion when a similar name exists, which resolves this case immediately. If you see the suggestion, take it.

Cause 2: used before it exists#

Python
print(total)             # NameError
total = 0
Python
greet("Ada")             # NameError: name 'greet' is not defined

def greet(name):
    print("Hello", name)

A script runs top to bottom, and a name exists only from the line that creates it. Functions are no different: def is a statement that runs and creates the name; a call above it finds nothing. Move the definition above the first use, or put the calls at the bottom of the file under a main guard:

Python
def greet(name):
    print("Hello", name)

if __name__ == "__main__":
    greet("Ada")

Inside a function it is different: a function’s body only runs when called, so a function can refer to another defined later in the file, as long as both exist by the time the call happens.

Cause 3: defined in a scope you cannot see#

Python
def load():
    data = [1, 2, 3]

load()
print(data)              # NameError: name 'data' is not defined

Variables created inside a function exist only inside it. To get the value out, return it:

Python
def load():
    return [1, 2, 3]

data = load()

The same applies to class bodies and to comprehensions, which have their own scope. Loop and if blocks do not create a scope in Python, so a variable assigned inside a for loop is visible after it — but only if the loop ran at least once:

Python
for item in []:
    last = item
print(last)              # NameError: the loop body never ran, so last was never assigned

Cause 4: only assigned on one branch#

Python
if score > 50:
    grade = "pass"
print(grade)             # NameError when score <= 50

The name exists on one path and not the other. Give it a value before the if, or add an else. This error is intermittent, appearing only for some inputs, which is what makes it worth fixing properly.

Cause 5: not imported#

Python
now = datetime.now()     # NameError: name 'datetime' is not defined
Python
from datetime import datetime
now = datetime.now()

Standard-library names such as datetime, math, os, json and random must be imported. The message is the same as for any other missing name. Watch also for importing the module and using the function directly: import math then sqrt(2) fails; it is math.sqrt(2).

Cause 6: a Python 2 name#

Python
name = raw_input("Name: ")     # NameError: name 'raw_input' is not defined
print "hello"                   # SyntaxError, and a hint about print()
xrange(10)                      # NameError
unicode("x")                    # NameError

Old tutorials and old code. The replacements are input, print(...), range and str.

Cause 7: strings without quotes#

Python
colour = red             # NameError: name 'red' is not defined
colour = "red"

Without quotes, Python looks for a variable called red. Beginners hit this constantly, and the fix is two characters.

Inside a function: UnboundLocalError#

Python
count = 0

def increment():
    count += 1           # UnboundLocalError: cannot access local variable 'count'

increment()

Assigning to a name anywhere in a function makes it local to that function for the whole body, so the += reads a local that has no value yet. If you really mean the module-level variable, declare it: global count. Usually the better fix is to pass the value in and return the new one.

Finding it#

The traceback names the line and the name. Then:

  1. Search the file for the exact name, including case. If it appears only once, it is a typo or a missing import.
  2. If it appears elsewhere, check whether that occurrence is before the failing line and in the same scope.
  3. If it is inside a function or a branch, that is the cause.

Questions people ask#

Why does it say “name” rather than “variable”?

Because functions, classes and modules are also names. The error does not know which kind you meant; it only knows nothing by that name exists.

The name is defined in another file.

Then it must be imported into this one. Each module has its own namespace.

It works in the notebook but not as a script.

Notebook cells share one namespace and may have run out of order, so a name defined in a later cell can exist. A script runs strictly top to bottom. Restart the notebook kernel and run all cells in order to reproduce script behaviour.

What is the difference from AttributeError?

NameError is a bare name Python cannot find. AttributeError is a name found, followed by a dot and something that does not exist on it: math.sqroot.

Where to go next#

Functions in Python: scope, arguments and returnRead next

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *