1.

Explain try..except…else … with the help of user defined function def divide(x, y)which raises an error when the denominator is zero while dividing x by y and displays the quotient otherwise.

Answer»

def divide(x, y):

try:

result = x / y

except ZeroDivisionError:

print "division by zero!"

else:

print "result is", result

In the above example:

try block consists of code that can raise an error. When y(denominator) gets a 0 value, ZeroDivisionError is raised which is handled by except clause. In case of no exception else statement is executed.

In case there is no error the statement(s) in else clause are executed.



Discussion

No Comment Found

Related InterviewSolutions