[Tutor] skipping ahead within a loop

Dave Kuhlman dkuhlman at rexx.com
Thu Mar 15 17:32:14 CET 2007


On Thu, Mar 15, 2007 at 03:35:27PM +0100, 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.

The while-statement looks like a good solution to me.

Two additional points:

1. You can alter the for-variable, *but* each time you go to the
   top of the for-loop, that variable is set to the next item from
   the iterator, wiping out any alteration.  Because of this, you
   can modify and use that variable within the loop body without
   having to worry about messing up the loop sequence.  What Clay
   wants to do is mess with the sequencing of items in the loop.

2. The reason that modifying the for-variable does not change the
   sequence of objects processed by the loop is that the
   for-statement is generating a sequence of objects from an
   iterator.  In this case the range function creates a list, which
   the for-statement turns into an iterator.

You don't even *want* to give Clay what he is asking for.  He asked
about being able to jump forward in the loop or sequence.  If you
were able to give him that one, he would come back and ask whether
he could jump *backward* in the loop.

For more on iterators, see "Iterator types" at
http://docs.python.org/lib/typeiter.html.  Also see the "iter"
function in "Built-in functions":
http://docs.python.org/lib/built-in-funcs.html.

You can think of the following:

    def test2():
        for item in range(4):
            print item

as syntactic sugar for this:

    def test1():
        myrange = range(4)
        myiter = iter(myrange)
        try:
            while True:
                item = myiter.next()
                print item
        except StopIteration, e:
            pass

Hoping this is not TMI (too much information), but sometimes it
helps to understand what is going on underneath, because the for
statement and iterators are very general, powerful,
and elegant features of Python.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman


More information about the Tutor mailing list