Lesson 1 of 0
In Progress

Handling Multiple Exceptions in a Single Block

Kedeisha June 16, 2023

Write a Python function that accepts a string and tries to convert it to an integer and then divide 100 by this integer. The function should handle exceptions ValueError and ZeroDivisionError. For ValueError, return the string “Invalid integer”, and for ZeroDivisionError, return “Cannot divide by zero”.

Input Data: Your function should accept a single string as input.

Explanation of Solution: The function safe_division tries to convert the string to an integer and then divide 100 by this integer. If the string cannot be converted to an integer, a ValueError is raised and the function returns ‘Invalid integer’. If the integer is zero, a ZeroDivisionError is raised and the function returns ‘Cannot divide by zero’. If no exceptions are raised, the function returns the result of the division.