top of page
learn_data_science.jpg

Data Scientist Program

 

Free Online Data Science Training for Complete Beginners.
 


No prior coding knowledge required!

Writer's pictureMusonda Katongo

Error Handling in Python Functions

Table of Contents

 

1. Introduction

When calling functions, we need to ensure that valid arguments are passed to the function for it to execute correctly. When we write our own functions, we will want to catch specific problems and print specific error messages that will enable the user to know exactly why the function is not executing.

 

2. Handling Exceptions

An exception is an error that is caught during the execution of a function. The following is an example of a function that returns the square root of a number.

def sq_root(num):
    """Returns square root of a number"""
    return num**0.5

sq_root(25)
5.0
sq_root('25')
-------------------------------------------------------------TypeError                                 Traceback (most recent call last) Input In [33], in <cell line: 1>()
----> 1 sq_root('25')
  
Input In [31], in sq_root(num)      
      1 def sq_root(num): 
----> 2     return num**0.5

TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float'  

When we pass a positive float or integer the function returns the square root of the number correctly. However, if we pass a string to it, an error is thrown, in this case a TypeError.


When we write our own functions we want to be able to provide error messages that are useful to the user. This is were we employ the try-except clause in which case we will specify within the code what the function should 'try' except in a case were it fails then we return an error message. The following is the code that will pri