Processing Arrays Using the break and else Clauses

0
100

When you process sequences and arrays using loops, you sometimes need to stop what you’re doing. For example, if you find the answer to the question of whether a number is prime or not, you really don’t need to continue the loop that was looking for the answer. At this point, you can simply print out the two numbers that result in the target number when multiplied. Then again, you might complete the loop without finding a divisor that can divide equally into the number you’re testing, so you need to tell the user that you have, indeed, found a prime number. Listing 4-9 shows one solution to this problem.

Listin g 4-9: Using break and else to process sequences

[code]# Create a loop for detecting prime numbers.
for Number in range(1, 10):
# This loop looks for divisors.
for Divisor in range(2, Number):
# If the number can be divided by the divisor evenly.
if Number % Divisor == 0:
# Print the values and then exit the loop.
print Number, ‘=’, Divisor, ‘*‘, Number/Divisor
break
else:
# If you can’t divide the number by any of the divisors,
# it’s prime.
print Number, ‘is a prime number’
# Pause after the debug session.
raw_input(‘nPress any key to continue…’)[/code]

The code begins by looking at the numbers 1 through 9. (Remember that range() won’t output 10 in this case.) What you have at the beginning of the second loop is a number that you want to examine. You know that you need to check all numbers smaller than the target number to determine whether they divide evenly into the target number. For example, if you were detecting whether 4 is a prime number, you wouldn’t try using 5 as a divisor.

The actual detection takes place with the code, Number % Divisor. If the output of this calculation is 0, then there isn’t any remainder, and you’ve found the divisor you wanted. At this point, the code outputs the two numbers that will result in the target number when multiplied, such as 4 = 2 * 2. After printing out the result, the inner loop can stop — it’s found the divisor you wanted and determined that the number isn’t prime.

However, some numbers won’t have a divisor because they are prime. In this case, the else clause takes over. The for loop literally falls through to the else clause and performs some other processing when the for loop fails. Figure 4-9 shows the output from this example.

Using break makes it possible to stop loop processing, while else gives an alternative output.