ZeroDivisionError: integer division or modulo by zero

avatar

Borislav Hadzhiev

Last updated: Apr 22, 2022

banner

Photo from Unsplash

ZeroDivisionError: integer division or modulo by zero #

The Python "ZeroDivisionError: integer division or modulo by zero" occurs when we use the modulo % operator with an integer and a zero. To solve the error, figure out where the 0 comes from and correct the assignment.

zerodivisionerror integer division or modulo by zero

Here is an example of how the error occurs.

main.py
a = 6 b = 0 # ⛔️ ZeroDivisionError: integer division or modulo by zero result = a % b

We tried using the modulo % operator with a zero.

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 best way to solve the error is to figure out where the 0 value comes from and correct the assignment.

Here are some unexpected sources of 0.

main.py
import random print(int()) # 👉️ 0 print(int(0.9)) # 👉️ 0 print(random.randint(0, 10)) # 👉️ 0 print(list(range(0, 5))) # 👉️ [0, 1, 2, 3, 4]

If you use the random.randint() method or the range() class, make sure to start from 1, and not from 0.

You can also conditionally check if the variable doesn't store a 0 value before using the modulo operator.

main.py
a = 6 b = 0 if b != 0: result = a % b else: # 👇️ this runs print('b is equal to 0')

Alternatively, you can use a try/except statement.

main.py
a = 6 b = 0 try: result = a % b print(result) except ZeroDivisionError: pass

We use the modulo operator and if we get a ZeroDivisionError, the except block is run.

You can set the result variable to a value that suits your use case in the except block or simply pass.

The modulo (%) operator returns the remainder from the division of the first value by the second.

main.py
print(10 % 2) # 👉️ 0 print(10 % 4) # 👉️ 2

If the value on the right-hand side is zero, the operator raises a ZeroDivisionError exception.

The left and right-hand side values may also be floating point numbers.

If the left-hand side value is a float and the right-hand side value is 0, you would get a "ZeroDivisionError: float modulo" error.

main.py
# ⛔️ ZeroDivisionError: float modulo print(10.5 % 0) # 👉️ 0

Conclusion #

The Python "ZeroDivisionError: integer division or modulo by zero" occurs when we use the modulo % operator with an integer and a zero. To solve the error, figure out where the 0 comes from and correct the assignment.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.