In Python, a NameError exception is raised when a name is not found in the local or global namespace.

For example  a NameError is raised when a variable or function is referenced before it has been defined, or when the value of a variable is accessed outside of its scope.


The general causes of NameError are:

  1. Using undefined variables

#The variable b is not defined resulting to a NameError
  1. Misspelled identifiers

#The print function is misspelled below leading to a NameError

prnt("Hello, World!")
  1. Using variables before they are defined

#variable a is used befor it is defined


a = 1000
  1. Incorrect usage of scope

#A name error is raised because we try to access variable a outside its scope.

def func():
   a = 100



Avoiding and Handling NameError Exceptions

The most obvious way to fix  the NameError exception is to ensure that your code is using the correct names for variables and objects. Make sure to double-check all variable names and object names. 

Python keeps a dictionary of all the variables defined in the global and  another for variables defined in the local namespaces.  You can access these dictionaries using the built-in functions globals() and locals() respectively.   This allows us to check whether a variable is already assigned using the "in" operator before using it . For example:

x = 100

if "x" in locals():
   x = x * 2

Just like other exceptions, you can also use try-except blocks for catching and handling the NameError.

except NameError as e:
   print("no variable named x.")