NameError: name ‘x’ is not defined

Python
Traceback (most recent call last):
  File "shelf.py", line 2, in <module>
    print(nmae)
          ^^^^
NameError: name 'nmae' is not defined

You look at your file. The variable is right there. So why doesn’t Python think so?

What Python is actually saying

I went looking for something with this name, and there is nothing by that name anywhere I can see.

Python doesn’t guess. It doesn’t autocorrect. If you ask for nmae and only name exists, nmae does not exist.

Cause 1: a typo

Python
name = "Maya"
print(nmae)          # ← two letters swapped

This is the most common one by far, and the reason Python underlines the exact name with ^^^^. Read the name in the error message character by character against the name in your code. They differ somewhere.

Cause 2: missing quotes around text

Python
name = Maya

Python
NameError: name 'Maya' is not defined

Without quotes, Python doesn’t read Maya as the word “Maya” — it reads it as the name of a variable called Maya, goes looking for it, and finds nothing.

Text always needs quotes:

Python
name = "Maya"

Cause 3: it exists, but not where you’re standing

Python
def set_name():
    name = "Maya"

set_name()
print(name)          # NameError

A variable created inside a function lives inside that function and disappears when the function ends. If you need the value outside, return it:

Python
def set_name():
    return "Maya"

name = set_name()
print(name)          # Maya

The one that catches everyone once

Running your file before the line that creates the variable. Python reads top to bottom. A variable created on line 10 does not exist on line 4.

What to check, in order

  1. Compare the name in the error to the name in your code, letter by letter
  2. If it should be text, does it have quotes?
  3. Was it created inside a function you’re now standing outside of?
  4. Is it created above the line that uses it?

Remember this

NameError is Python telling you it looked and found nothing. It is never Python being difficult — it is always a name that genuinely isn’t there.


Every error like this one, explained in full, in the Python Troubleshooting Handbook.

Next: TypeError: can only concatenate str