Make division by Zero return Zero in Python

Borislav Hadzhiev

Last updated: Jul 11, 2022

Photo from Unsplash

**Use an if/else statement to make division by zero return zero in Python,
e.g. return a / b if b else 0. When the number is divided by 0, the result
tends towards infinity, but we can check if the divisor is equal to 0 and
return 0 if it is.**

main.py

`# ✅ make division of zero return zero using if/else def handle_zero_division(a, b): return a / b if b else 0 print(handle_zero_division(15, 5)) # 👉️ 3.0 print(handle_zero_division(15, 0)) # 👉️ 0 # ------------------------------------- # ✅ make division of zero return zero using try/except def handle_zero_division_2(a, b): try: result = a / b except ZeroDivisionError: result = 0 return result print(handle_zero_division_2(15, 5)) # 👉️ 3.0 print(handle_zero_division_2(15, 0)) # 👉️ 0`

It's unclear what value is expected when we divide by `0`

, so Python throws an
error.

When we divide a number by `0`

, the result tends towards infinity.

The first example uses an inline `if/else`

statement to check if the divisor is
falsy.

Since

`0`

is the only numeric falsy value, if the divisor is falsy, we return `0`

, otherwise we return the result of dividing `a`

by ` b`

.You can also explicitly check if the divisor is equal to `0`

in your `if/else`

statement.

main.py

`def handle_zero_division(a, b): return 0 if b == 0 else a / b print(handle_zero_division(15, 5)) # 👉️ 3.0 print(handle_zero_division(15, 0)) # 👉️ 0`

Alternatively, you can use a `try/except`

statement.

**To make division by zero return zero:**

- Wrap the division in a
`try/except`

statement. - The
`except`

block should handle the`ZeroDivisionError`

. - Set the result to
`0`

in the`except`

block.

main.py

`def handle_zero_division_2(a, b): try: result = a / b except ZeroDivisionError: result = 0 return result print(handle_zero_division_2(15, 5)) # 👉️ 3.0 print(handle_zero_division_2(15, 0)) # 👉️ 0`

The `try/except`

block is known as "asking for forgiveness, rather than
permission".

We try to divide number

`a`

by number `b`

, and if we get a `ZeroDivisionError`

, the `except`

block is ran.In the `except`

block, we set the `result`

variable to `0`

.

If the divisor doesn't store a `0`

value, the `except`

block is never ran.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

You can use the search field on my Home Page to filter through all of my articles.