Skip to content
Related Articles

Related Articles

Improve Article

Handling NameError Exception in Python

  • Last Updated : 20 Aug, 2020
Geek Week

Prerequisites: Python Exception Handling

There are several standard exceptions in Python and NameError is one among them. NameError is raised when the identifier being accessed is not defined in the local or global scope. General causes for NameError being raised are :

1. Misspelled built-in functions:

In the below example code, the print statement is misspelled hence NameError will be raised.

Python3




geek = input()
prit(geek)

Output :



NameError: name 'prit' is not defined

2. Using undefined variables:

When the below program is executed, NameError will be raised as the variable geek is never defined.

Python3




geeky = input()
print(geek)


Output :
NameError: name 'geek' is not defined

3. Defining variable after usage:

In the following example, even though the variable geek is defined in the program, it is defined after its usage. Since Python interprets the code from top to bottom, this will raise NameError

Python3




print(geek)
geek = "GeeksforGeeks"


Output :
NameError: name 'geek' is not defined

4. Incorrect usage of scope:

In the below example program, the variable geek is defined within the local scope of the assign function. Hence, it cannot be accessed globally. This raises NameError.

Python3




def assign():
    geek = "GeeksforGeeks"
  
assign()
print(geek)


Output :
NameError: name 'geek' is not defined

Handling NameError

To specifically handle NameError in Python, you need to mention it in the except statement. In the following example code, if only the NameError is raised in the try block then an error message will be printed on the console.

Python3




def geek_message():
    try:
        geek = "GeeksforGeeks"
        return geeksforgeeks
    except NameError:
        return "NameError occured. Some variable isn't defined."
  
print(geek_message())

Output :

NameError occured. Some variable isn't defined.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :