FULL PYTHON FIX · 6 MIN READ

How to Fix ZeroDivisionError in Python

Dividing by zero stops a calculation. Trace where the divisor came from, decide what zero means for your program, and test that rule instead of hiding the error.

Video guide: How to Fix ZeroDivisionError in Python

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    Imagine a report that calculates average sales per order. The sales total is one hundred and twenty, and the order count comes from a list of orders. Today that list is empty. The code divides total sales by order count and prints the result. What should it show? Is the average zero, is it one hundred and twenty, or is there no average at all? Before deciding what the application should say, let us predict what Python itself will do. We will run the failing line, inspect the divisor, and make a small correction that matches the meaning of an empty list. We will then test normal data and an invalid negative count.

  2. 00:40

    The central lesson goes beyond one exception: handling a boundary value requires both a technical guard and a decision about the data. Silencing an error is not enough if the new answer is misleading. In a real report, zero orders can be completely normal at the start of a day, and an average cannot yet be calculated. A useful program should say so clearly. Watch the exact point at which Python raises the exception, because the traceback tells us where to begin the diagnosis. Run the short program with total sales one hundred and twenty and order count zero. Python raises ZeroDivisionError and the final line says division by zero.

  3. 01:22

    The traceback points at the expression with the slash. The earlier assignments were valid; the exception appears when Python evaluates the arithmetic expression. The value after the slash is the divisor. That is the first variable to inspect. In a larger program, it may have come from a count of records, a filtered subset, user input, or the return value of another function. Do not fix the problem by changing the numerator or by wrapping the whole report in a broad exception handler. That would make it harder to find the condition that produced zero. Notice also that this is not a syntax error.

  4. 02:02

    The program is valid Python and runs until it reaches data that make the calculation undefined. The same boundary can appear with floor division or modulo. A unit test with only nonempty input would miss it. Reproducing the empty case makes the cause visible and gives us a test to keep after the repair. We now know the exact operation that failed, but still need to decide what zero means in this report. Start again with an empty orders list and compute its length. Print the count and print whether it equals zero. Both outputs confirm that the divisor is zero before the failing expression. This check is simple, but it is more reliable than assuming where the bug is from the exception name alone.

  5. 02:47

    If the count should never be zero, trace back to the code that produced or filtered the list. If an empty list is normal, handle it as an expected state. Replacing zero with zero point zero does not help: Python's normal numeric division still rejects a zero divisor. Adding an arbitrary tiny amount to the denominator is also a poor repair. It changes the answer dramatically and hides the absence of data. In this example, an average sales value of zero would imply that orders existed and their average sale was zero. That is different from having no orders at all. We need to preserve the distinction.

  6. 03:29

    Ask what your real application should display to a user or return to another function when no records exist. Once that contract is clear, writing the guard becomes straightforward. The diagnosis is therefore both a Python value check and a small product decision about how to represent missing information. Put an if statement just before the division. If order count is zero, print a clear message that no average exists yet. Otherwise, divide total sales by the count and print the result. Rerun with zero. The program now reports the empty state without a traceback. Change the count to three and rerun.

  7. 04:10

    The average is forty. We have checked that the normal calculation still works, which matters whenever we add a special-case branch. In a reusable function, we might return None for the zero case and a number for the nonzero case. That is a deliberate contract: None means there is no result to compute yet. The caller must test for None before trying to format or add to the returned value. Another application might require the user to enter a positive count and ask again when the count is zero. The exact response depends on what the value represents, but the guard has the same structure. A try and except ZeroDivisionError can catch the runtime failure, yet it does not decide the desired meaning for us.

  8. 04:56

    Since we already have the divisor in a variable, checking it before division is readable and precise. Finish by testing more than one path. Call the average function with one hundred and twenty and three, then with one hundred and twenty and zero. The outputs are forty point zero and None. Those are two distinct results, and they should remain distinct in code that consumes the function. We can also reject a negative count. It may not trigger ZeroDivisionError, but a negative number of orders makes no sense in this report. A guard for zero protects arithmetic, while a separate validation rule protects the meaning of the data.

  9. 05:36

    For practice, write average score of a list of numbers. Return None for an empty list and the arithmetic mean otherwise. Try an empty list, a one-item list, and a two-item list. Predict each output before running it. If you are tempted to write length of scores or one, ask whether dividing by one for an empty list communicates the truth. It usually does not. The matching PythonLessonLab guide shows the broken run, the divisor check, the smallest useful correction, and the verification cases. The related Basic Operators and Exceptions lessons let you experiment in the browser. When you meet ZeroDivisionError in your own code, find the divisor, trace where its zero came from, define the zero case, and keep a test for that boundary.

Run the calculation that fails

A program wants the average sales per order. The total is 120, but no orders have been recorded yet. Run the short program and inspect the final line of the traceback. Python raises ZeroDivisionError at the division expression because the divisor is zero. The assignment to total_sales is fine; the problem is not with the numerator.

This often happens when the divisor comes from a count, a user input, or a filtered list. A calculation may work in development with several records and fail only when the data set is empty. Reproduce the empty case on purpose before changing the code. The same issue occurs with floor division and modulo: both require a nonzero divisor.

No orders yet
PYTHON
total_sales = 120
order_count = 0
print(total_sales / order_count)
ERROR (LAST LINE)
ZeroDivisionError: division by zero

Inspect the value on the right of division

The divisor is the value after the slash. Print it immediately before the failing expression and ask where it was calculated. In the example, order_count is zero because the list of orders is empty. That is a valid state for the data, even though an average cannot yet be computed. The code must represent that state explicitly.

Do not assume that writing 0.0 instead of 0 solves the issue. Both integer and floating-point zero are invalid divisors for Python's normal numeric division. Adding a tiny arbitrary number to the denominator merely changes the answer and can produce a misleading result. The correct response depends on what the number means in this application.

Print the divisor and its source
PYTHON
orders = []
order_count = len(orders)
print('count:', order_count)
print('is zero:', order_count == 0)
OUTPUT
count: 0
is zero: True

Choose a rule for the zero case

For an average, zero orders means there is no average yet. Test the count before dividing and display that fact. The guard belongs beside the calculation so a future reader can see the condition that makes division safe. If the application instead needs a numeric value, decide whether zero is a meaningful placeholder and document that decision. Do not silently substitute zero when it could be mistaken for a real average.

If zero indicates bad user input rather than a valid empty state, reject the input or ask again. A try/except ZeroDivisionError can be useful when a large expression is difficult to guard, but catching the exception does not decide the business rule for you. A simple if statement is clearer when the divisor is already available.

A meaningful empty-state response
PYTHON
total_sales = 120
order_count = 0
if order_count == 0:
    print('No average yet: there are no orders.')
else:
    print(total_sales / order_count)
OUTPUT
No average yet: there are no orders.
The same function with data
PYTHON
def average(total, count):
    if count == 0:
        return None
    return total / count
print(average(120, 3))
OUTPUT
40.0

Test zero, normal values, and invalid counts

Verify both branches. A count of three should produce 40.0; zero should produce None, meaning the result is absent. If negative counts are impossible in your domain, reject those too. The zero guard only protects the division; it does not validate the entire input. A good test includes at least one ordinary value, the boundary value zero, and a value the application should reject.

When a count comes from a list, use len(items) and consider the empty list explicitly. Do not use count or 1 as a shortcut unless you intentionally want to divide by one when count is zero; that changes the mathematical meaning. If the caller receives None, it must check for None before formatting or doing more arithmetic.

Verify the return contract
PYTHON
def average(total, count):
    if count < 0:
        raise ValueError('count cannot be negative')
    if count == 0:
        return None
    return total / count
print(average(120, 3))
print(average(120, 0))
OUTPUT
40.0
None
  • A positive count produces a numeric average.
  • A zero count produces a clearly identified no-data state.
  • A negative count is rejected as invalid input rather than used in the average.

Practice the fix

Write a function average_score(scores) that returns None for an empty list and the arithmetic mean otherwise. Test [], [10], and [10, 20]. Print each result and explain why the empty-list result is not the number zero.

Need a hint?

Check if not scores before dividing. For a nonempty list, return sum(scores) / len(scores). Call the function with each test list.

Python console

Ready to run

Edit the code and run it in your browser. Examples above can be loaded with Try this example.

Does your code use input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.

Write your solution, then select Check practice.

    Key takeaways

    • ZeroDivisionError means the divisor evaluated to zero at the failing expression.
    • Inspect the source of the divisor, especially an empty collection or missing input.
    • Guard the calculation and define what zero means in your application.
    • Test the zero boundary and an ordinary nonzero case.

    Related lessons

    Sources and further reading