NameError Exception in Python

Learn to handle Name Error exception in python using the try-except block.

NameError Exception in Python
NameError in Python

The NameError exception in Python is raised when the object being accessed is not defined in the local or global scope of your python program.

A few examples of NameError Exception in Python:-

  1. Trying to access a variable that doesn’t exist
  2. Trying to access a variable in the global scope but it is defined in the local scope.

To learn more about local and global scope of variables, check out the video below.

You can handle such errors using the NameError Exception class.


Example 1 - Accessing a variable that doesn’t exist

Code

try:
    print(name)
except NameError as e:
    print(e)

Output

name 'name' is not defined

Example 2 - Accessing variables not present in global scope

Code

def random_func():
    name = "Pylenin"

try:
    print(name)
except NameError as e:
    print(e)

Output

name 'name' is not defined

Check out other Python Built-in Exception classes in Python.