NameError: What It Means and How to Fix It
Error reference
NameError
Language
Severity
MediumWhen it happens
A NameError is raised in Python when you try to use a variable or function name that has not been defined in the current scope.
Potential fixes
Define the variable before using it. Double-check the spelling of every name. If a variable is defined inside a function, pass it as an argument or return it rather than accessing it from the outer scope. Use an IDE or linter to catch undefined names early.
Related errors
Deep dive
A NameError is raised in Python when you try to use a variable or function name that has not been defined in the current scope. Python looks up the name in local, enclosing, global, and built-in scopes and cannot find it.
Why it happens
- •Using a variable before assigning a value to it.
- •Typo in the variable or function name.
- •Trying to use a name that is only defined inside a function from outside it.
- •Forgetting to import a module before using its contents.
Potential fixes
Define the variable before using it. Double-check the spelling of every name. If a variable is defined inside a function, pass it as an argument or return it rather than accessing it from the outer scope. Use an IDE or linter to catch undefined names early.
Examples
Code that triggers the error
def greet():
print(message)
greet()Error output
Traceback (most recent call last):
File "app.py", line 4, in <module>
greet()
File "app.py", line 2, in greet
print(message)
NameError: name 'message' is not definedFixed code
message = "Hello, world!"
def greet():
print(message)
greet() # Hello, world!Practice in English
How would you explain a NameError to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free