[Tutor] Loop help (fwd)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 7 Apr 2002 15:14:45 -0700 (PDT)


Hi everyone,

Yikes, there was a bug in the code I had posted.  The first loop has x
going through the values [x, 11]:

> ###
> x = random_between(1,10)
> y = random_between(1,10)
> while x <= 10:
>     x = x + 1
[Some code cut]
> ###


But the for loop I wrote only goes through [1, 10]:

> ###
> for x in range(1, 11):
[Some code cut]
> ###


I wasn't paying as much attention to the boundary of the range as I should
have.  Here's a corrected loop:

###
for x in range(x+1, 12):
###

But there's something here that might be a little confusing, since 'x'
appears in two places in the for loop!  Even worse, this really has the
potential of tripping someone up who doesn't know that the range() is
computed only once, and not every time through the loop.


This is probably why we might prefer the while loop here, just to avoid
tricking people.  *grin* Hope this helps!