[Solved] Python ZeroDivisionError: integer modulo by zero

Python ZeroDivisionError: integer modulo by zero

Python “ZeroDivisionError: integer modulo by zero” exception occurs when the denominator in the modulo division operation is zero.

Mathematically when the denominator is zero, the result of the division is infinity, but in programming language like Python, it cannot handle such value, and therefore throws ZeroDivisionError.

Now, let us recreate this error.

In the following program, we find the x modulo y. And the value in y is zero. Meaning, we are trying to find the remainder of in the division of x by zero.

Python Program

x = 14
y = 0

rem = x % y
print(f"Remainder : {rem}")
Run Code Copy

Output

Traceback (most recent call last):
  File "/Users/pythonexamplesorg/main.py", line 4, in <module>
    rem = x % y
          ~~^~~
ZeroDivisionError: integer modulo by zero

Handle “ZeroDivisionError: integer modulo by zero” in Python

There are two ways in which we can handle this expiation.

The first way to handle this exception is to use Python Try Except. Enclose the modulo operation code in Try block, as shown in the following program.

Python Program

x = 14
y = 0

try:
    rem = x % y
    print(f"Remainder : {rem}")
except ZeroDivisionError:
    print("Please check the denominator. It is zero.")
Run Code Copy

Output

Please check the denominator. It is zero.

The second way to handle this exception is to check if the denominator is zero, even before doing the division operation, using a Python if else statement.

Python Program

x = 14
y = 0

if (y != 0):
    rem = x % y
    print(f"Remainder : {rem}")
else:
    print("Please check the denominator. It is zero.")
Run Code Copy

Output

Please check the denominator. It is zero.

Summary

In this tutorial, we learned how to handle ZeroDivisionError: integer modulo by zero expiation in Python, with examples.

Related Tutorials

Code copied to clipboard successfully 👍