Challenge: Safe Divider
Completed
Read two lines and divide the first number by the second. Never crash:
- If either line isn't a whole number, print
Invalid number. - If the second number is 0, print
Cannot divide by zero. - Otherwise print the answer rounded to 2 decimal places.
Input
Two lines.
Output
One line: the answer or one of the messages above.
Example
Input
10 4
Output
2.5
Editor
Python
Hints
Read both lines first, then convert them inside try.
Use one except for ValueError and one for ZeroDivisionError.
Solution explanation
We read both lines first, so the input is always fully read. Both int() calls and the division sit in the try block, so any of them can fail and be caught by the matching except.
Show solution
first = input()
second = input()
try:
a = int(first)
b = int(second)
print(round(a / b, 2))
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("Cannot divide by zero")