easy +8 pts

Safe divide function

Implement a division function that gracefully handles division by zero and type errors.

Write a function `safe_divide(a, b)` that returns the result of dividing `a` by `b` (using normal Python division `/`). If division by zero occurs (`ZeroDivisionError`) or if either operand is not a number (`TypeError`), return `None` instead of letting the exception propagate. You must catch these exceptions. For any other exception, let it propagate (do not catch it). Ensure the function handles all numeric types (int, float) and edge cases like negative numbers and very small values.

Constraints

Inputs are any Python objects. The function should not raise `ZeroDivisionError` or `TypeError` for valid numeric inputs. Time complexity: O(1). Space complexity: O(1).

Example

>>> safe_divide(10, 2)
5.0
>>> safe_divide(10, 0)
>>> safe_divide('a', 2)
>>> safe_divide(-6, 3)
-2.0
>>> safe_divide(1, 3)
0.3333333333333333
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a try-except block. The except clause can catch multiple exception types: `except (ZeroDivisionError, TypeError):`
Return None inside the except block.
Remember that division always returns a float in Python 3.
Test with values like 0 as divisor and strings as operands.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.