NameError: name ‘x’ is not defined
Traceback (most recent call last):
File "shelf.py", line 2, in <module>
print(nmae)
^^^^
NameError: name 'nmae' is not definedYou 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
name = "Maya"
print(nmae) # ← two letters swappedThis 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
name = MayaNameError: name 'Maya' is not definedWithout 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:
name = "Maya"Cause 3: it exists, but not where you’re standing
def set_name():
name = "Maya"
set_name()
print(name) # NameErrorA variable created inside a function lives inside that function and disappears when the function ends. If you need the value outside, return it:
def set_name():
return "Maya"
name = set_name()
print(name) # MayaThe 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
- Compare the name in the error to the name in your code, letter by letter
- If it should be text, does it have quotes?
- Was it created inside a function you’re now standing outside of?
- 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.