Datasheet

Chapter 1: A Python Primer
9
Iteration
Iteration in Python is handled through the “ usual suspects ” : the for loop and the while loop. However,
if you ve programmed in other languages, these seemingly familiar friends are a little different.
For Loops
Unlike in Java, the for loop in Python is more than a simple construct based on a counter. Instead, it is a
sequence iterator that will step through the items of any sequenced object (such as a list of names, for
instance). Here s a simple example of a
for loop:
> > > names = [“Jim”, “Joe”]
> > > for x in names:
print x
Jim
Joe
> > >
As you can see, the basic syntax is for < variable > in < object > : , followed by the code block to be
iterated.
While Loops
A while loop is similar to a for loop but it s more flexible. It enables you to test for a particular
condition and then terminate the loop when the condition is true. This is great for situations when you
want to terminate a loop when the program is in a state that you can t predict at runtime (such as when
you are processing a file, and you want the loop to be done when you reach the end of the file).
Here s an example of a
while loop:
> > > counter = 5
> > > x = 0
> > > while x < counter:
print “x=”,x
print “counter = “, counter
x += 1
x = 0
counter = 5
x = 1
counter = 5
x = 2
counter = 5
x = 3
counter = 5
x = 4
counter = 5
> > >
c01.indd 9c01.indd 9 6/2/08 12:03:10 PM6/2/08 12:03:10 PM