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:
>>> result = 10 / 0
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
An example of how to handle the exception:
>>> 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:
>>> 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:
>>> grades = []
>>> if grades:
... average = sum(grades) / len(grades)
... else:
... average = 0
...
>>> average
0
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python Exceptions: An Introduction (Tutorial)
- Operators and Expressions in Python (Tutorial)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Python Operators and Expressions (Quiz)