ZeroDivisionError

ZeroDivisionError is a built-in exception that occurs when you attempt to divide a number by zero, which is mathematically undefined. Python raises this exception when the right operand (divisor) in a division or modulo operation is zero.

You’ll often encounter this exception when you perform arithmetic operations that involve division.

ZeroDivisionError Occurs When

The right operand in a division or modulo operation is zero

ZeroDivisionError Can Be Used When

  • Handling division operations where the divisor is dynamically determined and may be zero
  • Implementing error messages or fallback logic for calculations involving user input that could be zero
  • Validating input data to ensure that division operations do not use zero as a divisor

ZeroDivisionError Examples

An example of when the exception appears:

Python
>>> result = 10 / 0
Traceback (most recent call last):
    ...
ZeroDivisionError: division by zero

An example of how to handle the exception:

Python
>>> try:
...     result = 10 / 0
... except ZeroDivisionError:
...     result = float("inf")
...     print("Cannot divide by zero, result set to infinity.")
...
Cannot divide by zero, result set to infinity.

ZeroDivisionError How to Fix It

Here’s a piece of code that raises a ZeroDivisionError because the input list is empty:

Python
>>> grades = []
>>> average = sum(grades) / len(grades)
Traceback (most recent call last):
    ...
ZeroDivisionError: division by zero

To avoid this issue, you can check for an empty list before trying to perform the division:

Python
>>> grades = []
>>> if grades:
...     average = sum(grades) / len(grades)
... else:
...     average = 0
...
>>> average
0

Tutorial

Python's Built-in Exceptions: A Walkthrough With Examples

In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 11, 2025 • Reviewed by Martin Breuss