|
|
||
Iterative Processing: The for StatementThe simplest for statement looks like this:
The
The
There are a number of ways of creating the necessary
The
A sequence display looks like this:
[
This first example creates a sequence of 6 values from 0 to just
before 6. The
for
statement iterates through the
sequence, assigning each value to the local variable for i in range(6): print i+1 The second example creates a sequence of 6 values from 1 to just
before 7. The
for
statement iterates through the
sequence, assigning each value to the local variable for j in range(1,7): print j This example creates a sequence of 36/2=18 values from 1 to just
before 36 stepping by 2. This will be a list of odd values from 1 to 35.
The
for
statement iterates through the sequence,
assigning each value to the local variable for o in range(1,36,2): print o This example uses an explicit sequence of values. These are all of
the red numbers on a standard roulette wheel. It then iterates through the
sequence, assigning each value to the local variable for r in [1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36]: print r, "red" Here's a more complex example, showing nested
for
statements. This enumerates all the 36 outcomes of rolling two dice. The
outer
for
statement creates a sequence of 6 values, and
iterates through the sequence, assigning each value to the local variable
for d1 in range(6): for d2 in range(6): print d1+1,d2+1,'=',d1+d2+2 Here's the example alluded to earlier, which does 100 simulations of
rolling two dice. The
for
statement creates the
sequence of 100 values, assigns each value to the local variable
import random for i in range(100): d1= random.randrange(6)+1 d2= random.randrange(6)+1 print d1+d2 There are a number of more advanced forms of the for statement, which we'll cover in the section on sequences in Chapter 11, Sequences: Strings, Tuples and Lists . |
||