ProjectStack
python

ZeroDivisionError: division by zero

Your code tried to divide a number by zero, which is mathematically undefined. Python raises this error immediately rather than returning infinity or NaN.

Common causes

  • A divisor variable is zero — possibly from user input, a calculation, or an empty dataset
  • Calculating an average or percentage when the total/denominator is zero
  • An edge case where a loop counter or accumulator reaches zero
  • Integer division (// or %) with a zero divisor

How to fix it

  1. Add a guard check before dividing: if denominator != 0: result = numerator / denominator
  2. Use a conditional expression: result = (numerator / denominator) if denominator else 0
  3. Wrap in try/except: try: result = a / b except ZeroDivisionError: result = 0
  4. Trace back how the divisor became zero — fix the root cause rather than just catching the error

Example

Traceback (most recent call last): File "app.py", line 4, in <module> average = total / count ZeroDivisionError: division by zero

Calculating the average of an empty list where count is 0

Have a different error?

Paste any error message into the Error Translator to get an instant explanation.