else clause on loops

by kiawin

An interesting control flow for Python,

for n in range(2, 10):
     for x in range(2, n):
         if n % x == 0:
             print n, 'equals', x, '*', n/x
             break
     else:
         # loop fell through without finding a factor
         print n, 'is a prime number'

If you look carefully on the highlighted line, you will notice an else was attached to the for-loop. It doesn’t belong to if per se, as the indentation shows the else belongs to for-loop.

The output will be as follow,

2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

The else clause on for-loop will be executed when the for-loop completed its repetition without any break occurred. Interesting indeed. It provides a refreshing approach to the common prime number program demonstrated in Programming Fundamentals, usually in C/C++.

A simple display of the else clause on loops feature,

for i in range(0,4):
        print i
else:
        print "no break"

Its output,

0
1
2
3
4
no break

Happy coding :)

[Source: Python 2.7.3 Documentation]