When youre reading a text file

REMEMBER A for statement has two parts:

• An iterable, which provides elements one at a time In this for statement, the iterable is range(io):

• A loop target (a name), which is given to each value that the iterator generates

In the above for statement, the loop target is i.

The for loop is so flexible because there are many ways to use the loop target name in the body of the loop. For example, you can give a new value to the name inside the loop (as long as you don't mind if that value goes away when the loop restarts). This code gives a new value to i:

>>> for i in range(5): ... if i < 3: ... i = "more spam!" ... else:

... i = "bleargh!" ... print i, more spam! more spam! more spam! bleargh! bleargh!

Warning The other side of the coin is that if you give a new value to the loop target, you can't expect the value to stick. This code doesn't print what you might expect, because i gets reassigned to a number when the loop restarts:

Was this article helpful?

0 0

Post a comment