Division That Never Crashes

Easy ⏱ 8 min 88% acceptance ★★★★☆ 4.4
Write safe_divide(a, b) returning a / b, but returning None when b is zero — by catching <code>ZeroDivisionError</code>, not by pre-checking b == 0 (the point is practicing EAFP style).

Examples

Example 1
Input
safe_divide(10, 4)
Output
2.5
Explanation

Normal division.

Example 2
Input
safe_divide(5, 0)
Output
None
Explanation

The exception is caught and None returned.

Constraints

  • Must use try/except.
  • Catch only ZeroDivisionError.

Topics

Exception Handlingtry/except

Companies

TCSCognizantAccenture

Hints

Hint 1

Wrap just the division in try.

Hint 2

The except block returns None.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.