Learn
Python NameError: name is not defined
Last updated: August 22, 2026
Fix NameError in Python when a variable or function is not defined. Run a tiny example online and read the traceback without a local install.
Declare the name, then Run againThe name is missing in this scope
NameError is Python’s version of “I do not know that word.” The traceback’s last line names the identifier. Start there, not at the first frame.
In Code Arena, Output shows the same traceback you would see in a terminal. Copy the name, then search the file for a declaration.
If there is no declaration, you either forgot to assign the variable, misspelled it, or meant a string and forgot the quotes.
Fix it in order
Check spelling and capitalization — total and Total are different. Then check whether you assigned the variable before the first use. Then check scope: a value created inside a function does not leak out.
print(hello) looks up a name. print("hello") prints text. That single pair of quotes is a common first-week bug.
If the name is a function you have not defined yet, either define it above the call or move the call below the def. Python reads the file top to bottom for this kind of snippet.
- Spelling first
- Assignment before use
- Scope: is the name inside another def?
- Quotes: did you mean a string literal?
Scope surprises
A variable assigned inside a function is local unless you declare otherwise. The caller cannot see it. A later function cannot see it either.
Loops do not create a new scope the way functions do. A name assigned in a for loop is still visible after the loop in ordinary module-level code. That difference confuses people who just learned functions.
When in doubt, print the name on the line before the crash. If the print itself is a NameError, you have your answer.
A playground drill
Run the starter snippet. You should see NameError: name 'message' is not defined. Add message = "hello" above greet(), Run again, then move the assignment inside greet() and try printing message after the call — that second NameError teaches scope.
FAQ
- What does NameError: name X is not defined mean?
- Python evaluated a name that has no binding in that scope — a typo, a missing assignment, or a variable used outside the function that created it.
- Why does it work in one function and fail in another?
- Names assigned inside a function are local unless you declare otherwise. The caller cannot see them, and a later function cannot see them either.
- Is NameError the same as TypeError?
- No. NameError is a missing name. TypeError means the name exists but you used the value in an invalid way, such as adding a string to an int.