Online Book Reader

Home Category

Learning Python - Mark Lutz [194]

By Root 1840 0
in loop tests. You can move the assignment into the loop body with a break:

while True:

x = next()

if not x: break

...process x...

or move the assignment into the loop with tests:

x = True

while x:

x = next()

if x:

...process x...

or move the first assignment outside the loop:

x = next()

while x:

...process x...

x = next()

Of these three coding patterns, the first may be considered by some to be the least structured, but it also seems to be the simplest and is the most commonly used. A simple Python for loop may replace some C loops as well.

* * *

for Loops

The for loop is a generic sequence iterator in Python: it can step through the items in any ordered sequence object. The for statement works on strings, lists, tuples, other built-in iterables, and new objects that we’ll see how to create later with classes. We met it in brief when studying sequence object types; let’s expand on its usage more formally here.

General Format

The Python for loop begins with a header line that specifies an assignment target (or targets), along with the object you want to step through. The header is followed by a block of (normally indented) statements that you want to repeat:

for in : # Assign object items to target

# Repeated loop body: use target

else:

# If we didn't hit a 'break'

When Python runs a for loop, it assigns the items in the sequence object to the target one by one and executes the loop body for each. The loop body typically uses the assignment target to refer to the current item in the sequence as though it were a cursor stepping through the sequence.

The name used as the assignment target in a for header line is usually a (possibly new) variable in the scope where the for statement is coded. There’s not much special about it; it can even be changed inside the loop’s body, but it will automatically be set to the next item in the sequence when control returns to the top of the loop again. After the loop this variable normally still refers to the last item visited, which is the last item in the sequence unless the loop exits with a break statement.

The for statement also supports an optional else block, which works exactly as it does in a while loop—it’s executed if the loop exits without running into a break statement (i.e., if all items in the sequence have been visited). The break and continue statements introduced earlier also work the same in a for loop as they do in a while. The for loop’s complete format can be described this way:

for in : # Assign object items to target

if : break # Exit loop now, skip else

if : continue # Go to top of loop now

else:

# If we didn't hit a 'break'

Examples

Let’s type a few for loops interactively now, so you can see how they are used in practice.

Basic usage

As mentioned earlier, a for loop can step across any kind of sequence object. In our first example, for instance, we’ll assign the name x to each of the three items in a list in turn, from left to right, and the print statement will be executed for each. Inside the print statement (the loop body), the name x refers to the current item in the list:

>>> for x in ["spam", "eggs", "ham"]:

... print(x, end=' ')

...

spam eggs ham

The next two examples compute the sum and product of all the items in a list. Later in this chapter and later in the book we’ll meet tools that apply operations such as + and * to items in a list automatically, but it’s usually just as easy to use a for:

>>> sum = 0

>>> for x in [1, 2, 3, 4]:

... sum = sum + x

...

>>> sum

10

>>> prod = 1

>>> for item in [1, 2, 3, 4]: prod *= item

...

>>> prod

24

Other data types

Any sequence works in a for, as it’s a generic tool. For example, for loops work on strings and tuples:

>>> S = "lumberjack"

>>> T = ("and", "I'm", "okay")

>>> for x in S: print(x, end=' ') # Iterate over a string

...

l u m b e r j a c k

>>> for x in T: print(x, end=' ') # Iterate over a tuple

®Online Book Reader