pairs = [(10, 4), (7, 0), ("9", 3), (12, 3)]
for a, b in pairs:
try:
result = a / b
except ZeroDivisionError:
print(f"{a} / {b}: cannot divide by zero")
except TypeError:
print(f"{a!r} / {b!r}: both values must be numbers")
else:
print(f"{a} / {b} = {result}")
Output Verified by running it on Python 3
10 / 4 = 2.5
7 / 0: cannot divide by zero
'9' / 3: both values must be numbers
12 / 3 = 4.0
Each failure has its own handler; else prints only successful results.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!