Skip to Content
Python: Essential Reference, Third Edition
book

Python: Essential Reference, Third Edition

by David Beazley
February 2006
Intermediate to advanced content levelIntermediate to advanced
648 pages
14h 53m
English
Sams
Content preview from Python: Essential Reference, Third Edition

Iteration and Looping

The simple loop shown earlier used the while statement. The other looping construct is the for statement, which is used to iterate over a collection of items. Iteration is one of Python’s most rich features. However, the most common form of iteration is to simply loop over all 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] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python: Essential Reference

Python: Essential Reference

David M. Beazley

Publisher Resources

ISBN: 0672328623Purchase book