Read two lines and print the first number divided by the second, with two decimal places. Print Cannot divide by zero if the second number is 0, and Invalid input if either line is not a whole number.
What to build
A program that handles two different failures differently.
Requirements
- Print the quotient with two decimals.
- Print
Cannot divide by zerofor a zero divisor. - Print
Invalid inputif either line is not a whole number.
Input
Two lines of text.
Output
The result with two decimal places, or one of the two messages.
Constraints
Each line is at most 20 characters of text.
Example
Input:
10
4
Output:
2.50
Why it works
Separate except blocks let each failure have an accurate message, because a bad number and a zero divisor are different problems.
Examples
Example 1 · Input
10 4
Expected output
2.50
Example 2 · Input
7 0
Expected output
Cannot divide by zero
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
int('abc') raises ValueError; dividing by 0 raises ZeroDivisionError.
Hint 2
One try can have two except blocks.
Solution
Show one correct solution (try it yourself first)
a = input()
b = input()
try:
result = int(a) / int(b)
print(f"{result:.2f}")
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")