Handling Division by Zero

Write a Python function that takes two integers as input and returns the result of the division of the first number by the second number. If a division by zero error occurs, return the string “Error: Division by zero is undefined”.

Example 1:

Input: 10, 2

Output: 5.0

Example 2:

Input: 10, 0

Output: "Error: Division by zero is undefined"

Use try-except block to handle ZeroDivisionError.

def divide(x, y):
    try:
        return x / y
    except ZeroDivisionError:
        return "Error: Division by zero is undefined"

print(divide(10, 2))  # Output: 5.0
print(divide(10, 0))  # Output: "Error: Division by zero is undefined"

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!