Computer Science
Use assert statement in Question No. 3 to test the division expression in the program.
Answer
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
assert denominator != 0, "Error: Denominator cannot be zero."
quotient = numerator / denominator
print("Quotient:", quotient)
Output
Enter the numerator: 12
Enter the denominator: 3
Quotient: 4.0
Enter the numerator: 5
Enter the denominator: 0
Traceback (most recent call last):
File "c:\PythonPlayground\q3.py", line 3, in <module>
assert denominator != 0, "Error: Denominator cannot be zero."
AssertionError: Error: Denominator cannot be zero.
Related Questions
When are the following built-in exceptions raised? Give examples to support your answers.
- ImportError
- IOError
- NameError
- ZeroDivisionError
What is the use of a raise statement? Write a code to accept two numbers and display the quotient. Appropriate exception should be raised if the user enters the second number (denominator) as zero (0).
Define the following:
- Exception Handling
- Throwing an exception
- Catching an exception
Explain catching exceptions using try and except block.