LearnFrenzy
Sign in Take a free test

Exception Handling · Exception Handling Coding Problems · Question 2

Safe division of value pairs with error reporting in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Divide each pair of values, reporting division by zero and wrong types without stopping the program.

Solution
main.py Run
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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links