In C (as well as in most other languages), you will not find an else statement outside the realm of conditional statements, yet Python bucks the trend again by offering these in while or for loops. How do they work? When used with loops, an else clause will be executed only if a loop finishes to completion, meaning they were not abandoned by break.
One popular example of else usage in a while statement is in finding the largest factor of a number. We have implemented a function which performs this task, using the else statement with our while loop. The showMaxFactor() function in Example 8.1 (maxFact.py) utilizes the else statement as part of a while loop.
This program displays the largest factors for numbers between 10 and 20. If the number is prime, the script will indicate that as well. 1 #!/usr/bin/env python 2 3 def showMaxFactor(num): 4 count = num / 2 5 while count > 1: 6 if (num % count == 0): 7 print 'largest factor of %d is %d' % 8 (num, count) 9 break 10 count = count - 1 11 else: 12 print num, "is prime" 13 14 for eachNum in range(10, 21): 15 showMaxFactor(eachNum) |
The loop beginning on line 3 in showMaxFactor() counts down from half the amount (starts checking if two divides the number, which would give the largest factor). The loop decrements each time (line 10) through until a divisor is found (lines 6–9). If a divisor has not been found by the time the loop decrements to 1, then the original number must be prime. The else clause on lines 11–12 takes care of this case. The main part of the program on lines 14–15 fires off the requests to showMaxFactor() with the numeric argument.
Running our program results in the following output:
largest factor of 10 is 5 11 is prime largest factor of 12 is 6 13 is prime largest factor of 14 is 7 largest factor of 15 is 5 largest factor of 16 is 8 17 is prime largest factor of 18 is 9 19 is prime largest factor of 20 is 10
Likewise, a for loop can have a post-processing else. It operates exactly the same way as for a while loop. As long as the for loop exits normally (not via break), the else clause will be executed. We saw such an example in Section 8.5.3.
Table 8.1 summarizes which conditional or looping statements auxiliary statements can be used.
Loops and Conditionals | |||
---|---|---|---|
Auxiliary Statements | if | while | for |
elif | • | ||
else | • | • | • |
break | • | • | |
continue | • | • | |
pass[a] | • | • | • |
[a] pass is valid anywhere a suite is required (also includes elif, else, class, def, try, except, finally)