
This is one of the most straightforward errors in Python, often referred to as a ZeroDivisionError. It’s not a bug in the language; it’s a fundamental rule of mathematics. You cannot divide a number by zero.
The Cause
Your code tried to perform a division (/) or modulo (%) operation where the denominator (the number on the bottom) was 0.
Problem Code:
total_score = 100
num_students = 0
# CRASH!
average = total_score / num_studentsThe Fix 1: The “Look Before You Leap” (LBYL) Check
The safest way is to check the denominator before you try to divide.
total_score = 100
num_students = 0
if num_students > 0:
average = total_score / num_students
else:
average = 0 # Or 'None', or 'N/A'
print(average)
# Output: 0 (No crash)The Fix 2: The “Easier to Ask Forgiveness” (EAFP) try/except
This is the more “Pythonic” way. You just try the operation, and if it fails, you “catch” the ZeroDivisionError. This is perfect if you don’t expect it to happen often.
total_score = 100
num_students = 0
try:
average = total_score / num_students
except ZeroDivisionError:
average = 0
print(average)
# Output: 0 (No crash)This is a much cleaner way to handle potential errors from user input or external data.





