NameError Exception in Python

By Lenin Mishra

This is the part of the 9th day in the Python 30 series. Check out the series here.

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.

  1. Try, Except, Else and Finally in Python
  2. ZeroDivisionError Exception in Python
  3. OverflowError Exception in Python
  4. ArithmeticError Exception in Python
  5. KeyError Exception in Python
  6. IndexError Exception in Python
  7. LookupError Exception in Python
  8. TypeError Exception in Python
  9. StopIteration Exception in Python
  10. FileNotFoundError Exception in Python
  11. Catch Multiple Exceptions in Python