easy +8 pts

Divide with zero check

Implement safe division that catches ZeroDivisionError and returns a custom error code.

Write a function `safe_divide(a, b)` that attempts to divide `a` by `b`. - If the division succeeds, return the float result of `a / b`. - If `b` is zero, catch the `ZeroDivisionError` and return the string `"Cannot divide by zero"`. - Maintain the exact function signature: `def safe_divide(a: float, b: float) -> float | str:` Note: You must use a `try`/`except` block to handle the error. Do not check `b == 0` with an if statement. Your implementation should be deterministic and work for all numeric inputs.

Constraints

- Inputs can be integers or floats. - The function must work for very large numbers, negative numbers, and non-integer floats. - Do not use any external libraries. - Time complexity: O(1).

Example

```python
>>> safe_divide(10, 2)
5.0
>>> safe_divide(7, 2)
3.5
>>> safe_divide(5, 0)
'Cannot divide by zero'
```
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use try: ... except ZeroDivisionError: ...
The division operator `/` raises ZeroDivisionError when dividing by zero.
Remember to return the result of the division in the `try` block.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.