Solve - ZeroDivisionError: division by zero in Python

Borislav Hadzhiev

Last updated: Apr 22, 2022

Check out my new book

**The Python "ZeroDivisionError: division by zero" occurs when we try to divide
a number by 0. To solve the error, use an if statement to check if the
number you are dividing by is not zero, or handle the error in a try/except
block.**

Here is an example of how the error occurs.

main.py

`a = 5 b = 0 # ⛔️ ZeroDivisionError: division by zero result = a / b`

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.

One way to solve the error is to check if the value we are dividing by is not
`0`

.

main.py

`a = 5 b = 0 if b != 0: result = a / b else: result = 0 print(result) # 👉️ 0`

We check if the `b`

variable doesn't store a `0`

value and if it doesn't, we
divide `a`

by `b`

.

Otherwise, we set the

`result`

variable to `0`

. Note that this could be any other value that suits your use case.If setting the `result`

variable to `0`

, if `b`

is equal to `0`

suits your use
case, you can shorten this to a single line.

main.py

`a = 5 b = 0 result = b and a / b print(result) # 👉️ 0`

The expression `x and y`

first evaluates `x`

, and if `x`

is falsy, its value is
returned, otherwise, `y`

is returned.

Since

`0`

is a falsy value, it gets returned if the `b`

variable in the example stores a `0`

value, otherwise the result of dividing `a`

by `b`

is returned.Alternatively, you can use a `try/except`

statement.

main.py

`a = 5 b = 0 try: result = a / b except ZeroDivisionError: result = 0 print(result) # 👉️ 0`

We try to divide `a`

by `b`

and if we get a `ZeroDivisionError`

, the `except`

block sets the `result`

variable to `0`

.

The best way to solve the error is to figure out where the variable gets
assigned a `0`

and check whether that's the expected behavior.

Here are some common ways you might get a zero value unexpectedly.

main.py

`print(int()) # 👉️ 0 print(int(0.9)) # 👉️ 0`

Use the search field on my Home Page to filter through my more than 3,000 articles.