Sometimes you may want Python to behave one way if there is an exception and another way if no error occurred. In this case, you will want to use a structure of try...except...else. To nuance the same previous example, we can add a third clause to affirm the user in not dividing by zero.
a = input("Please enter the dividend (the number to be divided):")When run, this program can produce the following output:
b = input("Please enter the divisor (the number by which to divide):")
try:
print a/b
except (NameError, ZeroDivisionError), error:
print "The divisor must not be zero. When the divisor is zero, Python hiccups like every good calculator should. The error passed was:"
print "<div><b>%s</b><div>" %(error)
else:
print "Not dividing by zero is a good thing."
Please enter the dividend (the number to be divided): 6
Please enter the divisor (the number by which to divide): 3
2
Not dividing by zero is a good thing.
