ZeroDivisionError · Exercises
Core Python

ZeroDivisionError Exercises

4 exercises that build on the Python ZeroDivisionError: Division by Zero lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A ZeroDivisionError means a division, floor division, modulo or power operation had zero as the divisor, which has no valid result. By the end you can recognise every form of ZeroDivisionError, trace it to the value that was zero, and fix it with a guard, try/except or input validation. You will practise: Predict which lines fail; Fix the empty class average; Split the restaurant bill; Safe percentage report.

0 / 4 completed

ZeroDivisionError practice exercises

1. Predict which lines fail

Predict the output Easy

Read the code and type exactly what it prints. Then press Check to compare.

Read this code
for divisor in [4, 0, 2.5]:
    try:
        print(20 / divisor)
    except ZeroDivisionError:
        print("cannot divide by", divisor)
print("done")

2. Fix the empty class average

Fix the bug Easy

average(scores) should return the mean of a list of scores, but it crashes for an empty list. Change it so an empty list returns 0 and other lists still return the mean.

Your code
def average(scores):
    return sum(scores) / len(scores)

print(average([80, 90]))
print(average([]))

3. Split the restaurant bill

Write code Medium

Write split_bill(total, people) that returns the amount each person pays, rounded to 2 decimal places. If people is 0 (or less), return None instead of raising an error. Use try/except ZeroDivisionError for the zero case.

Your code
def split_bill(total, people):
    return round(total / people, 2)

print(split_bill(100, 3))

4. Safe percentage report

Write code Hard

Write pass_rate(results) for a list of booleans such as [True, False, True]. Return the percentage that are True, rounded to 1 decimal place (e.g. 66.7). For an empty list return the string "no results". Then write summarize(batches) that takes a dictionary of batch name to results and returns a dictionary of batch name to pass_rate(...).

Your code
def pass_rate(results):
    return round(sum(results) / len(results) * 100, 1)

def summarize(batches):
    pass

print(pass_rate([True, False, True]))

Next lessonPython FileNotFoundError: No such file or directory

More Python ZeroDivisionError: Division by Zero examples · All Python exercises