variables with loop-local scope?

Terry Reedy tjreedy at udel.edu
Sat Oct 25 19:27:14 EDT 2003


"Brian Alexander" <brian094 at sympatico.ca> wrote in message
news:3F9AF2EE.5090702 at sympatico.ca...
> I remember using a language many years ago that permitted the
creation
> of temporary, local variables within the body of a loop (and perhaps
> other statement blocks.) Maybe it was Turing.
>
> Can Python do this?
> for i in listOfNames:
>    prefixMr = 'Mr'
>    prefixMs = 'Ms'
>    if i in mansName:
>      salutation = prefixMr + i
>    else:
>      salutation = prefixMs + i
>    print 'Hello,' + salutation
>
>The idea is that all variables created within the for statements will
be
> forgotten once the loop exits. No need to exit the procedure.

Having the induction variable remain set to its last value is
sometimes useful (and when searching for a match) and almost never a
bother.  If and when it is, just delete it.

Terry J. Reedy






More information about the Python-list mailing list