TryBugHunt

NameError: name 'x' is not defined

NameError: name 'x' is not defined in Python means 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.

PythonPattern: Scope and closure bugs

How do I fix NameError: name 'x' is not defined?

NameError: name 'x' is not defined means Python cannot find that name in any scope. Common causes are a typo or wrong capitalisation, a missing import like import math, a variable that only exists inside another function, or text without quotes. Check the spelling, add the import, or return the value from the function and assign it.

  1. 1. Compare the spellingPython is case-sensitive. Compare the name in the message with where you defined it. Read any Did you mean hint.
  2. 2. Check your importsModules like math, json and os need an import line at the top of the file before use.
  3. 3. Check where it was definedA variable made inside a function disappears when it returns. Return it and assign the result instead.

What does NameError: name 'x' is not defined mean?

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.

Why does NameError: name 'x' is not defined happen?

1. A typo or different capitalisation

Python names are case-sensitive. total and Total are unrelated.

Breaks

Total = 0
for n in nums:
    total += n

Works

total = 0
for n in nums:
    total += n

2. 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 = hello

Works

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.

Try it: fix this bug

easy

total_with_tip(100, 10) crashes: NameError: name 'bil' is not defined. Did you mean: 'bill'?

def total_with_tip(bill, tip_percent):
    tip = bill * tip_percent / 100
    return bil + tip
Open with hintsRuns in your browser. No account needed.

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.