Handling TypeError Exception in Python
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.
The general causes for TypeError being raised are:
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.
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.
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.
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.
TypeError: 'float' object is not iterable
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.
Geeky GeeksforGeeks TypeError: Check list of indices Geek
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