Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Types of NameError Exception
2.1.
Misspelled built-in functions
2.2.
Use of undefined variables
2.3.
Defining variable after usage
2.4.
Incorrect usage of scope
3.
Handling NameError
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Handling NameError Exception in Python

Author Nagendra
2 upvotes
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Python is one of the most widely used programming languages often used to build websites and software, automate tasks, and conduct data analysis. Learning Python reinforces essential computer science principles while also providing access to a wide range of professional options.

An exception is a condition that arises during the execution of a program that causes the normal flow of instructions to be disrupted. When a method encounters an error, it produces an object and passes it to the runtime system. In Python, there are various standard exceptions, and NameError is one of them. When the identifier being referenced isn't declared in the local or global scope, a NameError is thrown.

You can also read about the Multilevel Inheritance in Python and Convert String to List Python.

Types of NameError Exception

Misspelled built-in functions

The following code illustrates the occurrence of an exception due to misspelled built-in function :

x=5
Print(x) #python is case sensitive , it raises exception

Output

NameError: name 'Print' is not defined

Use of undefined variables

The following code illustrates the occurrence of exceptions due to the usage of undefined variables :

x=5
Print(y) #Here, the variable y is not defined

Output

NameError: name 'y' is not defined

Defining variable after usage

In the following code snippet, even the variable x is defined, but it is defined after it is used in the following example. This will cause a NameError since Python interprets the code from top to bottom.

print(x)
x=5

Output

NameError: name 'x' is not defined

Incorrect usage of scope

In the following code snippet, the variable x is defined within the local scope of the assigned function. As a result, it can't be accessed from anywhere in the world. This results in a NameError.

def val():
    x=5
val()
print(x)

Output

NameError: name 'x' is not defined
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Handling NameError

In Python, the NameError is handled by mentioning it in the except block. If only the NameError is triggered in the try block in the following sample code, an error message will occur.
The following code illustrates handling NameError in Python :

def val():
    try:
        x=5
        return y #here the variable y is not defined
    except NameError:
        return "NameError Occurred"
 
print(val())

Output

NameError Occurred

 

You can practice by yourself with the help of online python compiler.

Check out Escape Sequence in Python

FAQs

  1. What is an exception in Python? 
    An exception is a condition that arises during the execution of a program that causes the normal flow of instructions to be disrupted.
     
  2. What is the NameError exception?
    In a code snippet, when the identifier being referenced isn't declared in the local or global scope, a NameError is thrown.
     
  3. How can you handle NameError in Python?
    In Python, the NameError is handled by mentioning it in the except block. If only the NameError is triggered in the try block in the following sample code, an error message will occur.

Key Takeaways

In this article, we have extensively discussed Handling NameError Exceptions in Python. The article explains the details about the types of NameError exceptions with examples, and handling the NameError exception is also explained in detail.

Check out this article - String slicing in PythonFibonacci Series in Python
We hope that this blog has helped you enhance your knowledge regarding Handling NameError Exceptions in Python and if you would like to learn more, check out our articles on Python. Do upvote our blog to help other ninjas grow. 

Happy Coding!

Previous article
Handling a thread's exception in the caller thread in Python
Next article
Handling TypeError exception in python
Live masterclass