September 19, 2026
NameError: name 'x' is not defined — The Most Common Causes
NameError: name 'x' is not defined is one of the first errors most people hit, and it almost always comes down to one of three specific mistakes — not a mysterious Python quirk.
Cause #1: a typo in the variable name
mesage = "Hello" print(message)
Traceback (most recent call last):
File "script.py", line 2, in <module>
print(message)
NameError: name 'message' is not definedmesage and message are two different names as far as Python is concerned — a single missing letter is enough. This is the most common cause by far, and the fix is just careful reading (or an editor with autocomplete, which would have caught this immediately).
Cause #2: using a variable before it's defined
print(count) count = 5
Traceback (most recent call last):
File "script.py", line 1, in <module>
print(count)
NameError: name 'count' is not definedPython runs your file top to bottom, one line at a time. count doesn't exist yet when print(count) runs, even though it gets created one line later — order matters.
Cause #3: a variable defined inside a function, used outside it
def set_name():
name = "Ava"
set_name()
print(name)Traceback (most recent call last):
File "script.py", line 5, in <module>
print(name)
NameError: name 'name' is not definedVariables created inside a function only exist inside that function — this is called local scope. Calling set_name() runs the function and then throws its local name variable away; nothing outside the function ever sees it, even though the function clearly ran.
For more on how variables and scope work in Python, see the Variables and Data Types lesson in our free Python course.