Skip to the content

Project: crash-proof calculator

Python · Unit 9: Errors and exceptions

The calculator gets what the person typed: text. When dividing, two things can go wrong: it isn't a number (ValueError), or it's 0 (ZeroDivisionError).

A try can have one except for each error. Python uses the first one whose type matches.

try:
    print(8 / float("0"))
except ValueError:
    print("Not a number")
except ZeroDivisionError:
    print("Division by 0")

Prints

Division by 0

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Complete it so the calculator handles both zero and text.

  2. 2. Write the code

    Write divide(a, b). a and b are the texts the person typed, and they may have decimals. Return the result of the division, "Not a number" if either one isn't a number, or "Division by 0" if b is 0.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →