Computer Science

Consider the code given below and fill in the blanks.

print("Learning Exceptions...")
try:
    num1 = int(input("Enter the first number"))  
    num2 = int(input("Enter the second number"))  
    quotient = (num1/num2)
    print("Both the numbers entered were correct")
except ...............: # to enter only integers
    print("Please enter only numbers")
except ...............: # Denominator should not be zero
    print("Number 2 should not be zero")
else:
    print("Great .. you are a good programmer")
...............: # to be executed at the end
    print("JOB OVER... GO GET SOME REST")  

Python Exception Handling

3 Likes

Answer

print("Learning Exceptions...")
try:
    num1 = int(input("Enter the first number"))  
    num2 = int(input("Enter the second number"))  
    quotient = (num1 / num2)
    print("Both numbers entered were correct")
except ValueError:  # 1 : to enter only integers
    print("Please enter only numbers")
except ZeroDivisionError:  # 2 : Denominator should not be zero
    print("Number 2 should not be zero")
else:
    print("Great.. you are a good programmer")
finally: #  3 : to be executed at the end
    print("JOB OVER... GO GET SOME REST")
Explanation
  1. When using int(input("Enter the first number")) or int(input("Enter the second number")), the user is expected to input an integer. If the user enters a non-integer value (like a string or a floating-point number), a ValueError will be raised during the conversion to an integer. The except ValueError: block is used to handle this situation by displaying a message asking the user to enter only numbers.
  2. In the line quotient = (num1 / num2), if num2 is entered as zero, it will lead to a ZeroDivisionError during the division operation (num1 / num2). The except ZeroDivisionError: block is used to handle this scenario by displaying a message informing the user that the second number should not be zero.
  3. The finally: block is used to define code that should be executed regardless of whether an exception occurs or not.

Answered By

1 Like


Related Questions