Safe Divide With a Fallback Value

Easy ⏱ 8 min 79% acceptance ★★★★★ 4.7
Write a function safe_divide(a, b, fallback=0) that returns a / b, unless b is 0, in which case it returns fallback instead of raising a ZeroDivisionError.

Examples

Example 1
Input
safe_divide(10, 2)
Output
5.0
Explanation

Normal division since b is not zero.

Example 2
Input
safe_divide(10, 0)
Output
0
Explanation

b is zero, so the default fallback 0 is returned.

Example 3
Input
safe_divide(10, 0, fallback=-1)
Output
-1
Explanation

Caller supplies a custom fallback value.

Constraints

  • fallback defaults to 0 when not supplied.

Topics

Functionsdefault arguments

Companies

CapgeminiWipro

Hints

Hint 1

Check `if b == 0` before dividing.

Hint 2

Otherwise return a / b as normal.

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