NameError: name 'X' is not defined
1 · The lesson
readWhat this error means
Python tried to look up the name X and couldn't find it in any scope — not locally, not globally, not in built-ins. Either you spelled it wrong, you used it before defining it, you forgot to import it, or you defined it in a different scope (a different function or a different file).
When you see it
Traceback (most recent call last): File "main.py", line 4, in <module> print(usrname) NameError: name 'usrname' is not defined
Why it happens
Run through this checklist — one of these is almost always the cause:
1. Typo. usrname vs username. Python is case-sensitive: User and user are different.
2. Used before defined. You referenced the variable on a line that runs before the line that creates it.
3. Missing import. math.sqrt(2) fails with NameError: name 'math' is not defined if you forgot import math.
4. Wrong scope. A variable defined inside a function isn't visible outside it. A variable defined in another file isn't visible until imported.
5. String not quoted. print(hello) looks up a variable called hello; you meant print("hello").
def setup(): api_key = "abc123" # local to setup() setup() print(api_key) # NameError — api_key isn't visible here
How to fix it
Check the spelling and case of every name in the failing line:
username = "alice" print(username) # not Username, not usrname
Define before you use, or move the call lower:
def greet(): print(message) message = "hello" # must exist before greet() runs greet()
Add the missing import:
import math print(math.sqrt(2))
Return the value out of the function instead of relying on hidden scope:
def setup(): return "abc123" api_key = setup() print(api_key)
Quote string literals:
print("hello") # not print(hello)
When you'd actually see this in real code
- Refactoring split a function in two; one half still references a variable that now only lives in the other.
- You renamed a variable in five places and missed the sixth.
- A Jupyter notebook cell was re-run out of order, so the cell that defined the name hasn't executed in this session.
- You copied code from a tutorial that depended on
from x import *and you didn't run the import.
Related errors
- TypeError: 'X' object is not callable — the name exists but isn't a function.
- AttributeError: module 'X' has no attribute 'Y' — the module exists, the name inside doesn't.
- TypeError: 'NoneType' object is not iterable — sometimes a missing
returnlooks like this.
See Also
- All Python errors — the full index, by type and by when it happens.
- Variables (tutorial)
- Functions and scope
- Imports cheat sheet