ΣνΜDr. Sharon's Math PlatformSyvara Learning
Question Bank › 📘 Undergraduate › Programming for Engineers › Q14

Q14 · Python: try/except for TypeError and ValueError in comparisons

Error Handling and Debugging 🟡 Intermediate Coding
Question

The code below raises a TypeError because it compares a string to an integer:

  x = "6"
  if x > 3:
      print("x is larger than 3")

(a) Wrap it in a try/except block that catches the TypeError and prints a helpful message.
(b) Fix the comparison by converting x to an integer before comparing.
(c) Write a function safe_compare(x, threshold) with try/except that also handles ValueError for the case x = "abc" (cannot be converted to int).

🔒

Log in to see the worked solution

Enter your email to get started. Your first free solutions in every course unlock as soon as you verify.

Log in or sign up with email
← Previous Next →
Working…