The else Clause

Another feature of the first form of the try statement is the else clause. else's suite is executed only if no exceptions occurred.

suite except expression-target: s uite except :

suite else:

suite

The percentage is 1.0 The percentage is 1.0 Traceback (innermost last): File "<stdin>", line 1, in ? File "C:\\.\divby0_2.py", line 19, in ? File "C:\\.\divby0_2.py", line 4, in figurePercentage AttributeError: _getitem_

Using our denominator example (divby0_4.py), if we want to determine if any exceptions occurred, we can add anelse clause to the end of our try st atemeni as follows:

def figurePercentage(figures): for tuple in figures: try :

numerator = tuple[0] denominator = tuple[1] percent = numerator/denominator percent = percent * 100

print ("The percentage is " + "percent" + "%") except ZeroDivisionError:

print ("divide by 0 percentage error")

except :

print ("percentage error")

else:

print ("No exceptions occurred")

If br exceptions occurred, the figurePercentage () function prints out "No exceptions occurred " during each iteration in which that statement remains true.

Was this article helpful?

0 0

Post a comment