do loop

Peter Hansen peter at
Fri Jan 16 14:59:18 CET 2004

beliavsky at wrote:
> In a Python 'for' loop, one can change the value of looping variable,
> so that
> for i in range(3):
>     i = i*5
>     print i
> is legal code
> In Fortran 90 and 95, the analogous code
> do i=0,2
>    i = i*5
>    print*,i
> end do
> is illegal, because variable 'i' cannot be changed inside the loop.
> The constraint of not allowing the loop variable to change within the
> body of the loop can prevent errors in logic when the body of the loop
> is large.
> Is there a way to write a loop in Python that enforces this
> constraint? Should such functionality be added to the language?

No, absolutely not.  I don't believe this is a common error,
and in fact sometimes even in e.g. FORTRAN or BASIC you *wanted*
to change the loop variable to affect the sequence.  In any case 
Python's typical approach to such things is to treat the programmer 
as an adult.

Note that in Python you can trust that such a change will not affect 
the sequence as it would with some other languages, but if you do
*want* to change the loop variable, and have it affect the sequence, 
you can use a while loop instead.


More information about the Python-list mailing list