How to Fix ZeroDivisionError: division by zero in Python
In this tutorial, you'll learn about How to Fix ZeroDivisionError: division by zero in Python. We cover key concepts, practical examples, and best practices.
Python raises ZeroDivisionError: division by zero when any arithmetic operation divides a number by zero.
The Wrong Way
result = 10 / 0
print(result)
This produces:
Traceback (most recent call last):
File "script.py", line 1, in <module>
result = 10 / 0
ZeroDivisionError: division by zero
The Right Way
Check the divisor before dividing:
dividend = 10
divisor = 0
if divisor != 0:
result = dividend / divisor
else:
result = float('inf')
print("Division by zero avoided")
print(result)
Output:
Division by zero avoided
inf
Step-by-Step Fix
1. Validate user input divisors
divisor = float(input("Enter divisor: "))
if divisor == 0:
print("Cannot divide by zero")
else:
print(f"10 / {divisor} = {10 / divisor}")
2. Use try-except for unknown values
try:
result = 10 / unknown_value
except ZeroDivisionError:
result = float('inf')
3. Handle integer division
# Integer division also raises the error
try:
result = 10 // 0
except ZeroDivisionError:
result = 0
# Modulo operation too
try:
result = 10 % 0
except ZeroDivisionError:
result = 0
4. Filter zeros in bulk operations
numbers = [1, 0, 3, 0, 5]
results = [100 / n for n in numbers if n != 0]
print(results)
Output:
[100.0, 33.333333333333336, 20.0]
Prevention Tips
- Always validate divisors before arithmetic operations.
- Use try-except blocks when dividing by unknown or user-supplied values.
- Filter out zeros early in data processing pipelines.
- Set
numpy.seterr(divide='raise')to catch division issues in array operations. - Use
math.isclose()to check for near-zero floating-point values.
Common Mistakes with zerodivision
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro