variables with loop-local scope?
Alex Martelli
aleaxit at yahoo.com
Sun Oct 26 10:57:53 EST 2003
Brian Alexander wrote:
> 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.
Or C (not that exotic, but does have block-local variables, as do its
descendants).
> Can Python do this?
Python's variables _automatically_ go out of scope only when a function
terminates (you can of course explicitly delete them). So, if you need
"automatic going out of scope", you need a nested function. E.g.:
> for i in listOfNames:
> prefixMr = 'Mr'
> prefixMs = 'Ms'
>
> if i in mansName:
> salutation = prefixMr + i
>
> else:
> salutation = prefixMs + i
>
> print 'Hello,' + salutation
for i in listOfNames:
def block():
prefixMr = 'Mr'
prefixMs = 'Ms'
if i in mansName:
salutation = prefixMr + i
else:
salutation = prefixMs + i
print 'Hello,' + salutation
block()
Alex
More information about the Python-list
mailing list