[Tutor] skipping ahead within a loop
Kent Johnson
kent37 at tds.net
Thu Mar 15 17:00:25 CET 2007
Rikard Bosnjakovic wrote:
> On 3/15/07, Clay Wiedemann <clay.wiedemann at gmail.com> wrote:
>> If doing a loop, how can one skip forward a specific amount randomly
>> determined within the loop?
>
> y = 0
> while y < HEIGHT:
> linewidth = random(3, 9)
> # drawlines etc
> y += linewidth
>
> The reason why you cannot alter the for-variable beats me, though.
Because each time through the loop the variable is assigned to the next
value from the range.
A Python for loop is not like a C for loop. Python for loops work with
sequences. The loop variable is assigned to each element of the sequence
in turn.
range() returns a list which is the sequence the for loop iterates over.
You can manipulate the loop by making the iterator explicit. For example:
>>> for i in it:
... print i
... it.next() # explicitly skip the next item
...
0
2
4
6
Kent
More information about the Tutor
mailing list