Handling ZeroDivisionError in Python: A Complete Guide


Python ZeroDivisionError: division by zero

Python "ZeroDivisionError: division by zero" exception occurs when the denominator in the division 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 divide x by y. And the value in y is zero. Meaning, we are dividing x by zero.

Python Program

x = 14
y = 0

quot = x % y
print(f"Quotient : {quot}")

Output

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

Handle "ZeroDivisionError: division 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 division operation code in Try block, as shown in the following program.

Python Program

x = 14
y = 0

try:
    quot = x / y
    print(f"Quotient : {quot}")
except ZeroDivisionError:
    print("Please check the denominator. It is zero.")

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):
    quot = x / y
    print(f"Quotient : {quot}")
else:
    print("Please check the denominator. It is zero.")

Output

Please check the denominator. It is zero.

Summary

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