Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Handling TypeError Exception in Python

  • Last Updated : 20 Aug, 2020

TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise TypeError.

Examples

The general causes for TypeError being raised are:

 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

1. Unsupported operation between two types:



In the following example, the variable ‘geek’ is a string and the variable ‘num’ is an integer. The + (addition) operator cannot be used between these two types and hence TypeError is raised.

Python3




geek = "Geeks"
num = 4
print(geek + num + geek)

Output :

TypeError: must be str, not int

2. Calling a non-callable identifier:

In the below example code, the variable ‘geek’ is a string and is non-callable in this context. Since it is called in the print statement, TypeError is raised.

Python3




geek = "GeeksforGeeks"
print(geek())

Output :

TypeError: 'str' object is not callable

3. Incorrect type of list index:

In Python, list indices must always be an integer value. Since the index value used in the following code is a string, it raises TypeError.

Python3




geeky_list = ["geek", "GeeksforGeeks", "geeky", "geekgod"]
index = "1"
print(geeky_list[index])

Output :

TypeError: list indices must be integers or slices, not str

4. Iterating through a non-iterative identifier:

In the following code, the value 1234.567890 is a floating-point number and hence it is non-iterative. Forcing Python to iterate on a non-iterative identifier will raise TypeError.

Python3




for geek in 1234.567890:
    print(geek)

Output :

TypeError: 'float' object is not iterable

Handling TypeError

TypeErrors are raised mostly in situations where the programmer fails to check the type of object before performing an operation on them. They can be handled specifically by mentioning them in the except block. In the following example, when one of the indices is found to be an incorrect type, an exception is raised and handled by the program.

Python3




geeky_list = ["Geeky", "GeeksforGeeks", "SuperGeek", "Geek"]
indices = [0, 1, "2", 3]
for i in range(len(indices)):
    try:
        print(geeky_list[indices[i]])
    except TypeError:
        print("TypeError: Check list of indices")

Output :

Geeky
GeeksforGeeks
TypeError: Check list of indices
Geek



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!