Practice: Safe Division

Practice: Safe Division

This exercise combines try/except with a new exception type: dividing by zero raises ZeroDivisionError.

Exercise

  1. Define a function named safe_divide with two parameters: a and b.
  2. It returns 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.

Hints

  • Catch ZeroDivisionError specifically, not everything.
  • An if b == 0 check is also a correct solution — both shapes are used in real code.

Tests

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))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.