How to Fix ZeroDivisionError in Python



Your Python program just crashed with a ZeroDivisionError: division by zero. It sounds scary, but it’s actually one of the simplest errors to understand and fix.

This error means your code tried to divide a number by zero — which is mathematically impossible. Python stops your program to let you know something went wrong.

Let’s look at why this happens and how to handle it properly.

What Causes a ZeroDivisionError in Python

  • Dividing by a variable that happens to be zero — The variable might come from user input, a calculation, or a database, and you didn’t expect it to be zero.
  • Using the modulo operator (%) with zero — The % operator (which gives you the remainder of a division) also fails when the divisor is zero.
  • Calculating averages with an empty list — Dividing a sum by the count of items when there are no items means dividing by zero.

Fix 1: Check for Zero Before Dividing

The simplest fix is to check if the divisor (the number you’re dividing by) is zero before doing the division.

Example of the error:

# This raises ZeroDivisionError
total = 100
count = 0
average = total / count

Step 1: Add an if statement to check for zero.

total = 100
count = 0

if count != 0:
    average = total / count
    print(f"Average: {average}")
else:
    print("Cannot calculate average: no items to divide by.")

If the program prints the warning message instead of crashing, you’ve fixed it.

Step 2: For user input, validate before calculating.

numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))

if denominator == 0:
    print("You can't divide by zero. Please enter a non-zero number.")
else:
    result = numerator / denominator
    print(f"Result: {result}")

If the program rejects zero and accepts other numbers, everything is working correctly.

Fix 2: Use try-except to Handle the Error

When you can’t predict whether the divisor will be zero (for example, when it comes from complex calculations or external data), use error handling.

Step 1: Wrap the division in a try-except block.

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("Warning: Division by zero. Returning 0 as default.")
        return 0

# Using the function
result = safe_divide(100, 0)
print(f"Result: {result}")
# Output:
# Warning: Division by zero. Returning 0 as default.
# Result: 0

If the program prints the warning and continues without crashing, it’s working.

Step 2: Use this pattern for calculating averages safely.

scores = []  # An empty list

try:
    average = sum(scores) / len(scores)
    print(f"Average score: {average}")
except ZeroDivisionError:
    print("No scores available to calculate an average.")

Fix 3: Use Default Values or Conditional Expressions

For quick, inline handling, you can use a conditional expression (a short way to write an if-else on one line).

Step 1: Use a conditional expression to provide a default value.

total = 100
count = 0

# If count is 0, use "N/A" instead of dividing
average = total / count if count != 0 else "N/A"
print(f"Average: {average}")  # Output: Average: N/A

If the program shows “N/A” instead of crashing, it’s working correctly.

Step 2: For numerical results, you might want to default to zero.

total = 100
count = 0

# Returns 0 when count is zero
average = total / count if count else 0
print(f"Average: {average}")  # Output: Average: 0

What to Do If It Still Doesn’t Work

  • Trace the variable — Add print(f"divisor = {variable}") before the division to see exactly what value is causing the issue.
  • Check your data source — If the zero comes from a file, database, or API (a service your code connects to), validate the data when you first load it.
  • Review your math logic — Sometimes the zero is a symptom of a bug earlier in your code. Make sure the calculations leading up to the division are correct.
  • Use a debugger — In VS Code, set a breakpoint (a pause point) on the line with the division and inspect the variables.

Summary

  • A ZeroDivisionError means your code tried to divide by zero, which Python doesn’t allow.
  • The simplest fix is to check if divisor != 0 before dividing.
  • For unpredictable data, wrap the division in a try-except ZeroDivisionError block.

Related articles:

  • valueerror-python.html
  • type-error-python.html
  • syntax-error-invalid-syntax.html