Blog |

How to Fix ZeroDivisionError in Python

How to Fix ZeroDivisionError in Python
Table of Contents

In Python, a ZeroDivisionError is raised when a division or modulo operation is attempted with a denominator or divisor of 0.

What Causes ZeroDivisionError

A ZeroDivisionError occurs in Python when a number is attempted to be divided by zero. Since division by zero is not allowed in mathematics, attempting this in Python code raises a ZeroDivisionError.

Python ZeroDivisionError Example

Here’s an example of a Python ZeroDivisionError thrown due to division by zero:

a = 10
b = 0
print(a/b)

In this example, a number a is attempted to be divided by another number b, whose value is zero, leading to a ZeroDivisionError:

File "test.py", line 3, in <module>
    print(a/b)
ZeroDivisionError: division by zero

How to Fix ZeroDivisionError in Python

The ZeroDivisionError can be avoided using a conditional statement to check for a denominator or divisor of 0 before performing the operation.

The code in the earlier example can be updated to use an if statement to check if the denominator is 0:

a = 10
b = 0
if b == 0:
    print("Cannot divide by zero")
else:
    print(a/b)

Running the above code produces the correct output as expected:

Cannot divide by zero

A try-except block can also be used to catch and handle this error if the value of the denominator is not known beforehand:

try:
    a = 10
    b = 0
    print(a/b)
except ZeroDivisionError as e:
    print("Error: Cannot divide by zero")

Surrounding the code in try-except blocks like the above allows the program to continue execution after the exception is encountered:

Error: Cannot divide by zero

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape