easy +8 pts

Else on try block

Learn how the else clause in try-except works by building a safe divisor analyzer.

Write a function `safe_divide(a, b)` that takes two numbers `a` and `b` and returns a string. The function must use a `try`/`except`/`else` construct. - If `b` is zero, catch the `ZeroDivisionError` and return the string `"division by zero"`. - If `b` is not zero, perform the division `a / b`. The `else` clause should be used to convert the result to a string and return it. You may round the result to 2 decimal places using `round(result, 2)` before converting to a string. - The function must never raise an exception; it always returns a string. The function should be implemented exactly as described. The body of your solution must include a `try` statement with an `except` and an `else` clause. Note: The `else` clause runs only if no exception was raised in the `try` block.

Constraints

- `a` and `b` are integers or floats. - The absolute value of `a` and `b` can be up to 10^9. - The result of division is rounded to 2 decimal places using Python's `round`. - Time complexity: O(1). Space complexity: O(1).

Example

>>> safe_divide(10, 2)
'5.0'
>>> safe_divide(7, 2)
'3.5'
>>> safe_divide(1, 3)
'0.33'
>>> safe_divide(10, 0)
'division by zero'
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

The `else` clause of a `try` block executes only when no exception was raised.
Use `round(result, 2)` to limit decimal places before converting to string.
The string conversion of an integer result like 5.0 will be '5.0' in Python.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.