Q:

IndexError Exception in Python with Example

belongs to collection: Python Exception Handling Programs

0

Python programming language provides programmers a huge number of exception handler libraries that help them to handle different types of exceptions.

One such exception is the IndexError exception, let's understand it in detail.

IndexError Exception in Python is thrown when the passed value is not in the range of the given sequence [inputted value is out of range exception]. If it is not integer simply TypeError is thrown.

Here is an example that will help you to learn more about it, suppose you have a list of names of 10 students in a class. And the user entered the input for the 12th student. This throws an IndexError.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to illustrate index error in Python

# Program to illustrate IndexError Exception in Python...

# Try Block Starts
try:
    # List to store employee name 
   employees = ["pankaj","amit","dilip","pooja","nitisha"]

   id = int(input("Enter Id (1-5):"))
   print("Your name is ",employees[id-1]," and your id is ",id)

# Value error if the values is not in range 
except ValueError as ex:
    print(ex)

# IndexError if the value is out of the list index...
except IndexError as ex:
    print(ex)

Output:

Run 1: 
Enter Id (1-5):3
Your name is  dilip  and your id is  3

Run 2: 
Enter Id (1-5):59
list index out of range

Explanation:

In the above code, we have created a list consisting of the names of 5 employees of a company. And then prompted the user to enter the id of the employee to be searched. If the ID is out of the range of list, IndexError exception is thrown otherwise the ID is printed.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

ValueError Exception in Python with Example... >>
<< Create a library with functions to input the value...