Advertisements
Advertisements
Question
Use assert statement in Question No. 3 to test the division expression in the program.
Answer in Brief
Advertisements
Solution
An assert statement in Python is used to test an expression in the program code. If the result after testing comes false, then the exception is raised. This statement is generally used in the beginning of the function or after a function call to check for valid input.
The syntax for assert statement is assert Expression[,arguments].
On encountering an assert statement, Python evaluates the expression given immediately after the assert keyword. If this expression is false, an AssertionError exception is raised which can be handled like any other exception.
n = int(input("Enter Number 1 :"))
m = int(input("Enter Number 2 : "))
assert (m == 0), "Oops , Zero Division Error ...."
print("Quotient : ", n / m)
Output - 1
Enter Number 1 :10
Enter Number 2 : 2
Traceback (most recent call last):
File “D:/PythonProg/ExceptionHandling/DivideByZero.py”, line 4, in
assert (m == 0), “Opps, …. ZeroDivisionError”
AssertionError: Opps, …. ZeroDivisionError
Output - 2
Enter Number 1 :10
Enter Number 2 : 0
Traceback (most recent call last):
File “D:/PythonProg/ExceptionHandling/DivideByZero.py”, line 5, in
print(“Quotient : “, n / m)
ZeroDivisionError: division by zeroshaalaa.com
Raising Exceptions in Python
Is there an error in this question or solution?
