Loops

The simple loops shown earlier used the while statement. The other looping construct is the for statement, which iterates over the members of a sequence, such as a string, list, or tuple. Here’s an example:

for i in range(1,10): 
        print "2 to the %d power is %d" % (i, 2**i) 

The range(i ,j ) function constructs a list of integers with values from i to j-1 . If the starting value is omitted, it’s taken to be zero. An optional stride can also be given as a third argument. For example:

a = range(5)         # a = [0,1,2,3,4] 
b = range(1,8)       # b = [1,2,3,4,5,6,7] 
c = range(0,14,3)    # c = [0,3,6,9,12] 
d = range(8,1,-1)    # d = [8,7,6,5,4,3,2] 

The for statement can iterate over any sequence type and isn’t limited to sequences of integers:

 a = "Hello World" ...

Get Python Essential Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.