Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Python

Python NameError: name '...' is not defined (fix)

· 11 min read

Your program asks for a name, you type it, and Python stops on the very next line:

Terminal
What's your name? Sam
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print("Hello, " + nmae)
                      ^^^^
NameError: name 'nmae' is not defined

NameError: name '...' is not defined means Python met a name, here nmae, and has no idea what it refers to. Nothing with that name was created before this line ran. The name in the quotes is your best clue, and in most cases the fix is a single word. This article goes through every common cause, from typos to functions, with the real output for each.

Try it yourself

Save this as main.py and run python main.py:

main.py
name = input("What's your name? ")
print("Hello, " + nmae)

Type any name, and you'll get the error above. Here the typo is plain to see. In a 50-line program it's not, so let's learn to read the message.

What NameError means

In Python, a name is the word you use to refer to something: a variable like price, a function like print, a module like math. A name exists only after something creates it: an assignment (price = 4), a def, an import, or a for loop. NameError: name 'x' is not defined means Python reached a line that uses x, looked for it, and found nothing.

Read the traceback from the bottom up:

  • NameError: the type of problem. A name is missing.
  • name 'nmae' is not defined: the exact name Python looked for. Copy it, letter by letter.
  • File "main.py", line 2: where it happened. The line itself is printed below, and the ^^^^ marks under it point at the name.

Then ask the question that solves most of these: where did I mean to create this name, and why didn't Python see it?

Cause 1: a typo in the name

The example above. You created name and used nmae. Python doesn't guess: to it, these are two unrelated words.

Newer versions of Python (3.10 and later) often add a suggestion when a similar name exists. In this run on Python 3.13, a change in capital letters got one:

main.py
Age = 30
print(age)
Terminal
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(age)
          ^^^
NameError: name 'age' is not defined. Did you mean: 'Age'?

Names in Python are case-sensitive: Age, age and AGE are three different names. A good habit: use lowercase with underscores for variables (birth_year), and you'll rarely mix them up.

Treat Did you mean as a hint, not an answer. It only compares spelling. You'll see below that it sometimes suggests something that has nothing to do with your program.

Cause 2: text without quotes

You wanted the word yes, and you forgot the quotes:

main.py
answer = input("Continue? ")
if answer == yes:
    print("OK")
Terminal
Continue? yes
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    if answer == yes:
                 ^^^
NameError: name 'yes' is not defined

Without quotes, yes is a name, so Python looks for a variable called yes. With quotes, "yes" is text. Write if answer == "yes":.

The same happens with print(Hello) instead of print("Hello"): you'll get NameError: name 'Hello' is not defined.

Cause 3: true, false and none in lowercase

Python's special values start with a capital letter: True, False and None.

main.py
is_ready = true
Terminal
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    is_ready = true
               ^^^^
NameError: name 'true' is not defined. Did you mean: 'True'?

If you've written JavaScript or Java before, this one will catch you a few times. The suggestion gets it right here.

Cause 4: using a variable before it's created

Python runs your file from top to bottom. A line can only use names that earlier lines created:

main.py
total = price * 3
price = 4
Terminal
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    total = price * 3
            ^^^^^
NameError: name 'price' is not defined. Did you mean: 'print'?

price is created on line 2, but line 1 needs it. Swap the two lines. And note the suggestion: print looks a bit like price, so Python offered it. It's a real built-in name, but it's the wrong answer. That's why you read the hint and then think.

A function called before its def

The same rule applies to functions. def creates the function name when Python reaches that line:

main.py
greet("Sam")

def greet(person):
    print("Hi", person)
Terminal
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    greet("Sam")
    ^^^^^
NameError: name 'greet' is not defined

Put your def blocks at the top of the file, and the code that uses them below.

A variable created only inside an if

A variable created in one branch of an if exists only if that branch ran:

main.py
if False:
    message = "hi"
print(message)
Terminal
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(message)
          ^^^^^^^
NameError: name 'message' is not defined

In a real program the condition is something like if score > 50:, so the error appears only for some inputs. That's the confusing part: it worked yesterday. Give the variable a value before the if (message = ""), or make sure every branch sets it, including an else.

Cause 5: a missing import

Modules have to be imported before you use them:

main.py
numbers = [3, 7, 1]
print(math.sqrt(numbers[0]))
Terminal
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(math.sqrt(numbers[0]))
          ^^^^
NameError: name 'math' is not defined. Did you forget to import 'math'?

Add import math at the top of the file. Recent Python versions recognise standard modules and say so directly, as you can see above.

There's a sneakier version. from math import sqrt imports only the name sqrt, not math:

python
from math import sqrt
print(math.pi)

That also gives NameError: name 'math' is not defined. Either use import math and write math.sqrt and math.pi, or import every name you need: from math import sqrt, pi.

And a typo in a module name gets no help at all. In our test, print(jsno.dumps({})) after import json gave only NameError: name 'jsno' is not defined, with no suggestion.

Cause 6: a variable that lives inside a function

Variables created inside a function are local: they exist only while the function runs. Outside, they're gone:

main.py
def add_tip(bill):
    tip = bill * 0.15
    return bill + tip

add_tip(40)
print(tip)
Terminal
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(tip)
          ^^^
NameError: name 'tip' is not defined. Did you mean: 'zip'?

(zip is another built-in that happens to look like tip. Ignore it.)

The fix is to return what you need and store the result:

main.py
def add_tip(bill):
    tip = bill * 0.15
    return bill + tip

total = add_tip(40)
print(total)
Terminal
46.0

If you need both the tip and the total outside, return both: return tip, bill + tip, then tip, total = add_tip(40).

Inside a class: forgetting self

In a class, values saved with self.name = ... belong to the object. Inside another method, you have to reach them through self again:

main.py
class Dog:
    def __init__(self, name):
        self.name = name
    def speak(self):
        print(name, "says woof")

Dog("Rex").speak()
Terminal
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    Dog("Rex").speak()
    ~~~~~~~~~~~~~~~~^^
  File "main.py", line 5, in speak
    print(name, "says woof")
          ^^^^
NameError: name 'name' is not defined. Did you mean: 'self.name'?

This traceback has two parts. The last File line is where the error happened: line 5, inside speak. The first one only shows where speak was called from. Write print(self.name, "says woof").

This one looks different, but it's a close cousin:

main.py
def show():
    print(count)
    count = count + 1

count = 0
show()
Terminal
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    show()
    ~~~~^^
  File "main.py", line 2, in show
    print(count)
          ^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

count exists outside the function, so why does this fail? Because the function also assigns to count on line 3. That makes count a local variable for the whole function, and on line 2 the local one has no value yet. In fact, UnboundLocalError is a special kind of NameError. The cleanest fix is to pass the value in and return the new one: def show(count): ... return count + 1.

Errors that look alike

  • AttributeError: 'str' object has no attribute ...: the name exists, but the thing after the dot doesn't. The problem is on the right of the dot, not the left.
  • ModuleNotFoundError: No module named 'x': you did write the import, but Python can't find that module. Usually a typo in the import line, or a package that isn't installed.
  • TypeError: unsupported operand type(s): the names exist but their values are the wrong type. See Python TypeError: 'int' and 'str'.
  • IndentationError: sometimes the real cause of a NameError is that a line ended up inside or outside a block by mistake. See IndentationError: expected an indented block.

Wrong fixes that don't help

  • Making everything global. Writing global tip inside the function makes the error go away, but now any part of the program can change tip. Returning values is the habit that scales.
  • Wrapping it in try/except NameError. A NameError is almost always a bug in the code, not a problem with the input. Hiding it means the program carries on without the value it needed.
  • Accepting the Did you mean suggestion without reading it. You saw print for price and zip for tip. Check that the suggestion makes sense in your program.

A debugging walkthrough

A small budget program fails with NameError: name 'monthly_total' is not defined. Here's the order to check:

  1. Copy the name from the message and search your file for it (Ctrl+F or Cmd+F). Zero results that create it? It's a typo or it was never created.
  2. Look for near-matches. Search for part of the name, like total. Maybe you created month_total.
  3. Check the order. Is the line that creates it above the line that uses it?
  4. Check the indentation. Is it created inside a function or an if that didn't run?
  5. Check imports if the name is a module or something you expected to import.

Most NameErrors are solved by step 2 or 3.

Practice

Predict the error before you run each snippet.

  1. print(len(names)) when the file never creates names.
  2. for i in range(3): pass, then print(i) after the loop.
  3. items = [], then for item in items: pass, then print(item).

Answers. (1) NameError: name 'names' is not defined. (2) No error: it prints 2. The loop variable still exists after the loop, holding its last value. (3) NameError: name 'item' is not defined. The list is empty, so the loop never ran and never created item. (In our run, Python suggested 'iter', another built-in that's no use here.)

Frequently asked questions

What does "name is not defined" mean in Python?

Python reached a line that uses a name (a variable, function or module) that hasn't been created yet at that point in the run. Check spelling, quotes, order and imports.

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

Add import math at the top of the file. If you wrote from math import sqrt, use sqrt(...) without math., or switch to import math.

Why does my variable work in one function but not another?

Variables created inside a function are local to it. Return the value and pass it to the other function as an argument.

Why did it work before and fail now?

The name was probably created inside an if, a loop or a function that didn't run this time. Different input, different path.

Is NameError the same in Jupyter notebooks?

The error is the same. Notebooks add one more cause: if you restart the kernel or run cells out of order, a cell that created the name may not have run yet. Run the cells from the top.

A quick checklist

  1. Copy the name from the quotes in the message.
  2. Check the spelling and the capital letters.
  3. Is it meant to be text? Add quotes.
  4. Is it created above the line that uses it?
  5. Is it created inside a function, class or if that didn't run or doesn't share it?
  6. Is it a module? Add the import.

For a method that works on every error, read how to read an error message. The official Python documentation describes NameError and how names and scopes work.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Python

Why does 0.1 + 0.2 not equal 0.3 in Python?

Why Python prints 0.30000000000000004 for 0.1 + 0.2, why 0.1 + 0.2 == 0.3 is False, and the three fixes: round for display, math.isclose() instead of ==, and Decimal for money. With code you can run.

Error explained · · 4 min read

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right