Introducing Python © Chirag Wazir 2002 Prev   Index   Next

for

a = ['Mandrake', 'Linux', '8.2']
for x in a:
    print x, len(x)
Mandrake 8
Linux 5
8.2 3

The range or xrange function can be used for numeric iteration

range(10)       # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(3,7)      # [3, 4, 5, 6]
range(0,10,2)   # [0, 2, 4, 6, 8]

Using for & else:

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'
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