Project: crash-proof calculator
Python · Unit 9: Errors and exceptions
- Full plan
- Python
- Project
- 2 exercises
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. Complete the code
Complete it so the calculator handles both zero and text.
2. Write the code
Write
divide(a, b).aandbare 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"ifbis 0.
Do this lesson
See all lessons →It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.