50 XP

22. Safe division

Intermediate exceptions

Write a function safe_divide(a, b) that takes two numbers and returns a / b. Dividing by zero is an error in Python (ZeroDivisionError), so when b is 0, return None instead of crashing.

Use try and except rather than checking b first.

The answer is a decimal number (a float), even when the division comes out exact: 6 / 3 is 2.0. When a is 0 and b isn't, the answer is 0.0. When both are 0, return None.

Example 1

Inputa = 10, b = 4
Output2.5
Explanation10 / 4 = 2.5.

Example 2

Inputa = 1, b = 0
OutputNone
Explanationb is 0, so the answer is None.

Example 3

Inputa = 6, b = 3
Output2.0
Explanation/ always gives a float, even for 6 / 3.

Constraints

  • a and b are whole numbers or decimals from -1000 to 1000. Either can be 0 or negative.

Submit also runs 4 more tests you can't see.

Practises Errors and Exceptions (lesson 21).

Code
def safe_divide(a, b):
    """Divide a by b, or return None when b is 0.

    a, b: int or float
    Returns: float, a / b; or None if b is 0
    """
    # Write your code here
    pass