Skip to content

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

  • Accessing a variable before it’s given a value, which inside a function surfaces as an UnboundLocalError, a subclass of NameError
  • Misspelling a variable or function name
  • Forgetting to import a module or an object from a module

NameError Example

An example of when the exception appears:

Language: Python
>>> unknown_variable
Traceback (most recent call last):
    ...
NameError: name 'unknown_variable' is not defined

When the interpreter displays a NameError, it also tries to suggest a fix. Since Python 3.10, a misspelled name gets a Did you mean: ...? hint, and since Python 3.12, an undefined standard-library name gets a Did you forget to import ...? hint.

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.

Python's Built-In Exceptions: A Walkthrough With Examples

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Aug. 12, 2026 • Reviewed by Martin Breuss