Basic question

Arnaud Delobelle arnodel at googlemail.com
Sat May 12 12:48:50 EDT 2007


On May 12, 5:18 pm, "Cesar G. Miguel" <cesar.go... at gmail.com> wrote:
> I've been studying python for 2 weeks now and got stucked in the
> following problem:
>
> for j in range(10):
>   print j
>   if(True):
>        j=j+2
>        print 'interno',j
>
> What happens is that "j=j+2" inside IF does not change the loop
> counter ("j") as it would in C or Java, for example.
>
> Am I missing something?

Yes you are :)

"for j in range(10):..." means:
   1. Build a list [0,1,2,3,4,5,6,7,8,9]
   2. For element in this list (0, then 1, then 2,...), set j to that
value then execute the code inside the loop body

To simulate "for(<initialisation>; <condition>; <increment>) <body>"
you have to use while in Python:

<initialisation>
while <condition>:
    <body>
    <increment>

Of course in most case it would not be the "pythonic" way of doing
it :)

--
Arnaud




More information about the Python-list mailing list