15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

8.10. else Statement ... Take Two<br />

In C (as well as in most other languages), you will not find an else statement outside the realm of<br />

conditional statements, yet <strong>Python</strong> bucks the trend again by offering these in while and for loops. How<br />

do they work? When used with loops, an else clause will be executed only if a loop finishes to<br />

completion, meaning they were not abandoned by break.<br />

One popular example of else usage in a while statement is in finding the largest factor of a number. We<br />

have implemented a function that performs this task, using the else statement with our while loop. The<br />

showMaxFactor() function in Example 8.1 (maxFact.py) utilizes the else statement as part of a while loop.<br />

Example 8.1. while-else Loop Example (maxFact.py)<br />

This program displays the largest factors for numbers between 10 and 20. If the number is<br />

prime, the script will indicate that as well.<br />

1 #!/usr/bin/env python<br />

2<br />

3 def showMaxFactor(num):<br />

4 count = num / 2<br />

5 while count > 1:<br />

6 if num % count == 0:<br />

7 print 'largest factor of %d is %d' % \<br />

8 (num, count)<br />

9 break<br />

10 count -= 1<br />

11 else:<br />

12 print num, "is prime"<br />

13<br />

14 for eachNum in range(10, 21):<br />

15 showMaxFactor(eachNum)<br />

The loop beginning on line 3 in showMaxFactor() counts down from half the amount (starts checking if<br />

two divides the number, which would give the largest factor). The loop decrements each time (line 10)<br />

through until a divisor is found (lines 6-9). If a divisor has not been found by the time the loop<br />

decrements to 1, then the original number must be prime. The else clause on lines 11-12 takes care of<br />

this case. The main part of the program on lines 14-15 fires off the requests to showMaxFactor() with the<br />

numeric argument.<br />

Running our program results in the following output:<br />

largest factor of 10 is 5<br />

11 is prime<br />

largest factor of 12 is 6<br />

13 is prime

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!