Fix: NameError: name 'X' is not defined
Exact message
NameError: name 'x' is not defined
Quick answer
NameError means Python cannot find a variable or function name in the current scope. The most common causes are a typo, using a variable before it is defined, or referencing an outer-scope name that is not accessible inside a function.
Why this error happens
Python resolves names at runtime, not at compile time. When it evaluates an expression that refers to x, it looks in the local scope, then enclosing scopes, then module globals, then built-ins. If none contain x, it raises NameError. This differs from C++ or Java where undeclared variables fail at compile time.
Example: Wrong vs Right
Wrong
print(usename) # NameError: name 'usename' is not defined
Right
username = "samrat"
print(username)
# In a function, declare global explicitly if you must modify it
def update():
global username
username = "new"How to fix it (step by step)
- Check the exact variable name — typos like 'usename' instead of 'username' are the top cause
- Verify the variable is assigned BEFORE the line that uses it
- If inside a function, confirm the name is accessible (local, enclosing, global, or passed as argument)
- If modifying a global inside a function, use the global keyword, or better, return the new value
Frequently asked questions
What is the difference between NameError and UnboundLocalError?
UnboundLocalError occurs when a variable is assigned somewhere inside a function but used before that assignment. NameError occurs when the name does not exist in any scope.
Why does it work in REPL but not in a script?
REPL preserves state between lines. In a script, code runs top to bottom — a variable must be defined before use.
How do I access a global variable inside a function?
Just read it — reading is automatic. To assign, use global x. Better still, pass the value as a function argument and return the new value.
Related Python errors
Need a fix for a different error?
Use the free to paste any traceback and get an AI-suggested fix in seconds.
Want an AI with memory for your project?
MonsterX AI remembers your codebase across chats.