Safe Division with a User-Friendly Message

Medium ⏱ 12 min 49% acceptance ★★★★☆ 4.2
Write a function divide_or_report(a, b) that returns the string str(a / b) if b is not zero, or the exact message "Error: cannot divide by zero" if b is zero. This mirrors how CLI tools should print friendly errors instead of letting ZeroDivisionError crash the program.

Examples

Example 1
Input
divide_or_report(10, 2)
Output
'5.0'
Explanation

10 / 2 = 5.0, converted to string.

Example 2
Input
divide_or_report(5, 0)
Output
'Error: cannot divide by zero'
Explanation

Division by zero is caught and reported.

Constraints

  • a and b are numbers (int or float).

Topics

Input & Outputerror output

Companies

RazorpayPayPal

Hints

Hint 1

Check `b == 0` before dividing, or catch ZeroDivisionError.

Hint 2

Convert the successful result to a string with str().

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.