Start free

Advanced · Exceptions · 188 of 264

Safe division

Divide pairs of values. Use try/except: print error: not a number when a value is not a number, and error: division by zero when dividing by 0. Otherwise print the result with two decimals.

Input: n, then n lines "a b". Output: one line per pair.

Examples

Input
3
10 4
1 0
x 2
Output
2.50
error: division by zero
error: not a number
Input
1
-9 3
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.

All the exceptions exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More exceptions exercises