22. Safe division
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
a = 10, b = 42.5Example 2
a = 1, b = 0NoneExample 3
a = 6, b = 32.0Constraints
aandbare 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).
- Dividing by zero raises a
ZeroDivisionError, which stops the program unless you catch it.0 / 5is fine: it is0.0. - Put the division in a
try:block and returna / bthere. - Add
except ZeroDivisionError:andreturn Nonein it. Catch that error only, not every error, so other mistakes still show.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.