Advanced · Exceptions · 191 of 264
Careful calculator
Work out expressions "a op b" where op is +, -, * or /. Print the result with two decimals, or error for a bad number, an unknown operator or a division by zero.
Input: n, then n expressions. Output: one line per expression.
Examples
Input
4 3 + 4 10 / 4 1 / 0 2 ^ 3
Output
7.00 2.50 error error
Input
1 -1.5 * 2
Output
-3.00
One more test checks other inputs when you press Check.
Stuck? The idea behind exceptions
A try block runs code that might fail; its except catches the error and lets the program carry on, instead of stopping.
Catch the error you expect, by name: ValueError for int("abc"), ZeroDivisionError for dividing by 0.
for line in ["4", "x", "7"]:
try:
print(int(line) * 2)
except ValueError:
print("not a number")Watch for: A bare except: hides every mistake, your own typing errors too. Name the error.