Computer Science

Consider the code given below and fill in the blanks with appropriate error types:

loop = 1
while loop == 1:
      try:
         a = int(input('Enter the first number: ')
         b = int(input('Enter the second number: ')
         quotient = a/b
      except ...............:
         print("Error: Please enter only numbers")
      except ...............:
         print("\n Error: Second number should not be zero")
      except ...............:
         print("\n Unsupported operation: Check the date type")
      else:
         print("Great")
      finally:
         print("Program execution completed")
loop = int(input('Press 1 to try again !')
continue

Python Exception Handling

1 Like

Answer

loop = 1
while loop == 1:
    try:
        a = int(input('Enter the first number: '))
        b = int(input('Enter the second number: '))
        quotient = a / b
    except ValueError:
        print("Error: Please enter only numbers")
    except ZeroDivisionError:
        print("\n Error: Second number should not be zero")
    except TypeError:
        print("\n Unsupported operation: Check the data type")
    else:
        print("Great")
    finally:
        print("Program execution completed")
loop = int(input('Press 1 to try again: '))
continue

In the code:

  1. The ValueError exception is used to catch errors that occur when the input cannot be converted to an integer (e.g., if the user enters a non-numeric value).
  2. The ZeroDivisionError exception is used to catch errors that occur when attempting to divide by zero (i.e., when the second number is zero).
  3. The TypeError exception is used to catch errors related to unsupported operations, such as performing arithmetic operations on incompatible data types.

Answered By

2 Likes


Related Questions