Open In App

Handling NameError Exception in Python

Last Updated : 29 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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()
print(geek)


Output : 

NameError: name 'print' 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 occurred. Some variable isn't defined."
 
print(geek_message())


Output : 

NameError occurred. Some variable isn't defined.


Similar Reads

Nameerror: name self is not defined in Python
Python, a dynamically typed and object-oriented programming language, is lauded for its simplicity and readability. However, even the most seasoned developers can encounter stumbling blocks, and one such common hurdle is the "NameError: name 'self' is not defined." In this article, we will see how to fix Nameerror: Name 'self' is not defined in Pyt
4 min read
Nameerror: Name '__File__' Is Not Defined" in Python
One common issue that developers encounter is the "NameError: name 'file' is not defined." This error typically occurs when trying to access the __file__ attribute in a context where it is not recognized. In this article, we'll explore what this error means and discuss three scenarios where it might occur What is Nameerror?The __file__ attribute is
4 min read
Undefined Variable Nameerror In Python
Encountering the "NameError: name 'var' is not defined" is a common experience for Python users. In Python, variable declaration is a straightforward process of assigning a value. This error arises when attempting to access a non-existent variable or one not defined in the program. Surprisingly, it can occur even when the variable is present, owing
5 min read
Nameerror: Name Plot_Cases_Simple Is Not Defined in Python
Python, being a dynamically typed language, often encounters the "NameError: name 'plot_cases_simple' is not defined." This error arises when you attempt to use a variable or function that Python cannot recognize in the current scope. In this article, we will explore the meaning of this error, understand why it occurs, and provide solutions to rect
3 min read
Python Nameerror: Name 'Imagedraw' is Not Defined
Python, being a versatile and dynamic programming language, is widely used for various applications, including image processing. However, as with any programming language, errors can occur. One common issue that developers encounter is the "NameError: name 'ImageDraw' is not defined." This error can be particularly frustrating but fear not. What is
3 min read
Python | Raising an Exception to Another Exception
Let's consider a situation where we want to raise an exception in response to catching a different exception but want to include information about both exceptions in the traceback. To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors. Code #1 : def example(): try: in
2 min read
How to Fix: NameError name ‘pd’ is not defined
In this article we will discuss how to fix NameError pd is not defined in Python. When we imported pandas module without alias and used pd in the code, the error comes up. Example: Code to depict error C/C++ Code # import pandas module import pandas # create dataframe data = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) # display data Output: ----------
2 min read
How to Fix: NameError name ‘np’ is not defined
In this article, we will discuss how to fix NameError np that is not defined in Python. When we imported the NumPy module without alias and used np in the code, the error comes up. Example: Code to depict error C/C++ Code # import numpymodule import numpy # create numpy array a = np.array([1, 2, 3, 45]) # display a Output: name 'np' is not defined
2 min read
How To Fix Nameerror: Name 'Listnode' Is Not Defined
NameError is a common issue in Python programming, and one specific instance is the "Name 'Listnode' is not defined" error. This error occurs when the interpreter encounters a reference to a variable or object named 'Listnode' that has not been defined in the current scope. In this article, we will explore what causes this error and provide some co
4 min read
Multiple Exception Handling in Python
Given a piece of code that can throw any of several different exceptions, and one needs to account for all of the potential exceptions that could be raised without creating duplicate code or long, meandering code passages. If you can handle different exceptions all using a single block of code, they can be grouped together in a tuple as shown in th
3 min read
Article Tags :
Practice Tags :