Quick Answer
Handle invalid division operations.
Understanding the Issue
ZeroDivisionError occurs when attempting to divide by zero, which is mathematically undefined. This can happen in regular division (/) or floor division (//). The error often surfaces in dynamic calculations where denominators aren't properly validated.
The Problem
This code demonstrates the issue:
Python
Error
def calculate_ratio(a, b):
return a / b # Fails if b=0
average = total / count # Fails if count=0
The Solution
Here's the corrected code:
Python
Fixed
# Solution 1: Explicit check
def safe_division(a, b):
if b == 0:
return float('nan') # or raise custom error
return a / b
# Solution 2: Try/except
try:
result = numerator / denominator
except ZeroDivisionError:
result = 0
Key Takeaways
Always validate denominators in division operations.