This exercise combines try/except with a new exception type: dividing by zero raises ZeroDivisionError.
safe_divide with two parameters: a and b.a / b. When b is zero, it returns None instead of raising.safe_divide(10, 4) returns 2.5. safe_divide(10, 0) returns None.
Run your code to see the output, then press Submit.
ZeroDivisionError specifically, not everything.if b == 0 check is also a correct solution — both shapes are used in real code.import unittest
class TestSafeDivide(unittest.TestCase):
def test_normal_division(self):
self.assertEqual(safe_divide(10, 4), 2.5)
def test_division_by_zero_gives_none(self):
self.assertIsNone(safe_divide(10, 0))
def test_zero_dividend_is_fine(self):
self.assertEqual(safe_divide(0, 5), 0.0)
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
print(safe_divide(10, 4))
print(safe_divide(10, 0))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.