print(1 + "hello")

TypeError exceptions occur on an attempt to perform an operation on objects of an inappropriate/unsupported type. This typically occurs when attempting to perform a type-specific operation on objects of the wrong type.

#with operators
1 + "hello"
//TypeError: unsupported operand type(s) for +: 'int' and 'str'

#with builtin functions
int([1, 2, 3])
//TypeError: int() argument must be a string, a bytes-like object or a real number, not 'list'
float((1))
//TypeError: float() argument must be a string or a real number, not 'tuple'

Common causes of TypeError exceptions

Some of the most common causes for TypeError in Python are:

  • Performing an operation with unsupported types

"hello" * "world!"
  • Calling uncallable object

demo = "Pynerds"

demo()
  • Incorrect type during indexing

L = [1, 2, 3, 4, 5, 6]

print(L[1.0])
  • Iterating on an object that does not support iteration

demo = 3.142
for i in demo:
    print(i)

Avoiding and Handling TypeError Exceptions

Ensuring that the objects being used in an operation are of the appropriate types is the first step to avoid the TypeError exceptions. For example we can check in advance whether the values are of the correct type using the if block. 

def add(a, b):
   """This function only works with integers and floating point values"""

   if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):

       return "The values entered are invalid"

   return "%s + %s = %s"%(a, b, a + b)

print(add(10, 20))

print(add(50, 60))

print(add(10, "Pynerds"))

In the above case, the TypeError exception is not raised because we explicitly avoid it. However, we can also use the try-except block to catch the TypeError when it is raised and proceed accordingly.

def add(a, b):
   """This function only works with integers and floating point values"""

   try:

     return "%s + %s = %s"%(a, b, a + b)

   except:
       return "The values entered are invalid"

print(add(10, 20))

print(add(50, 60.5))

print(add(10, "Pynerds"))