NameError
NameError
is a built-in exception that occurs when you try to use a variable or function name that isn’t defined yet. This usually happens if there’s a misspelling or if the name isn’t in the current scope.
You can avoid raising a NameError
by making sure everything you reference is defined or imported and accessible in the current scope before you use it. Double-checking that you spelled each name correctly also helps.
NameError
Occurs When
NameError
Example
An example of when the exception appears:
>>> unknown_variable
Traceback (most recent call last):
...
NameError: name 'unknown_variable' is not defined
You typically won’t raise a NameError
on purpose. Instead, it’s a signal that you tried to use something that isn’t defined or available yet.
Related Resources
Tutorial
Python's Built-in Exceptions: A Walkthrough With Examples
In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.
For additional information on related topics, take a look at the following resources: