1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Exceptions, Errors, and Warnings

By Al Lukaszewski, About.com

6 of 8

If All Else Fails...

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):")
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."
When run, this program can produce the following output:
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.

6 of 8

Explore Python

More from About.com

  1. Home
  2. Computing & Technology
  3. Python

©2008 About.com, a part of The New York Times Company.

All rights reserved.