Loop variable value after loop finish

Tony J Ibbs (Tibs) tony at lsl.co.uk
Thu Mar 16 10:42:03 EST 2000


Mikael Johansson wrote:
> Can I safely trust that the value printed by the following program will
> always be loops-1, except when loops<1? I wasn't fully convinced by the
> docs on this point.
>
> for i in range(loops):
>     pass
> print i

Well, my copy of the reference manual says (in part):

----------------------------------------------------------
"""
for_stmt: "for" target_list "in" expression_list ":" suite
          [ "else" ":" suite ]

The expression list is evaulated once; it should yield a sequence. The suite
is then executed once for each item in the sequence, in the order of
ascending indices. Each item in turn is assigned to the target list using
the standard rules for assignments and then the suite is executed. [etc]
"""
----------------------------------------------------------

which seems to define the behaviour sufficiently to me - in other words,
yes.

In more detail:

"""The expression list is evaulated once; it should yield a sequence."""
- yes - the sequence [0,...,loops-1] as defined for "range".

"""The suite is then executed once for each item in the sequence, in the
order of ascending indices."""
- ok - that's the obvious order. and we know we don't have the empty
sequence because you excluded that case.

"""Each item in turn is assigned to the target list using the standard rules
for assignments"""
- so "i" becomes 0, ... loops-1 in turn

"""and then the suite is executed."""
- which is "pass", so that doesn't change anything.

So the result is as you expect - heh presto.

Tibs (give me a manual and a pedant and I can - well, irritate the world, I
guess)
--
Tony J Ibbs (Tibs)      http://www.tibsnjoan.demon.co.uk/
Well we're safe now....thank God we're in a bowling alley.
- Big Bob (J.T. Walsh) in "Pleasantville"
My views! Mine! Mine! (Unless Laser-Scan ask nicely to borrow them.)





More information about the Python-list mailing list