Skip to main content
Practice

Handling TypeError for Function Parameters

When using functions, a TypeError can occur if you provide arguments of incorrect types or if required arguments are missing.

This occurs when you pass arguments of the wrong type to a function or when you don't provide the required number of arguments.

TypeError Example
def add(x, y):
return x + y

# Passing wrong type of argument
add('3', 5)
# Cannot add a string and a number

# Missing argument
add(10)
# The 2nd argument is not provided

Handling TypeError

TypeError can be managed using a try-except block as shown below.

Handling TypeError Example
def add(x, y):
return x + y

try:
add('3', 5)
except TypeError:
print('It is not possible to add a string and a number.')

In the code above, when add('3', 5) is executed, a TypeError is raised, and it is handled by the except TypeError block which outputs It is not possible to add a string and a number.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.