NameError: name 'x' is not defined
Python reached a name it has never seen in this scope. A typo, a missing import, or a variable that only exists inside another function.
What it means
Names are looked up when the line runs: local scope, then enclosing functions, then the module, then built-ins. If none has it, NameError. Since Python 3.10 the message often adds "Did you mean ...?" — read it, it is usually right.
Common causes
1. A typo or different capitalisation
Python names are case-sensitive. total and Total are unrelated.
Breaks
Total = 0
for n in nums:
total += nWorks
total = 0
for n in nums:
total += n2. A variable that lives inside another function
Locals vanish when their function returns. Return the value instead of reaching for it.
Breaks
def load():
data = [1, 2, 3]
load()
print(data)Works
def load():
return [1, 2, 3]
data = load()
print(data)3. A missing import
math, json, os and friends exist only after you import them.
Breaks
print(math.sqrt(16))Works
import math
print(math.sqrt(16))4. Text without quotes
Without quotes, Python reads hello as a variable name.
Breaks
greeting = helloWorks
greeting = "hello"How to find it in your own code
Check the spelling of the name in the message against where you think you defined it. If it is spelled right, ask where it was defined — if that is inside a function, a loop that may not run, or a file you have not imported, that is the bug.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.