variables with loop-local scope?
Brian Alexander
brian094 at sympatico.ca
Sun Oct 26 21:49:46 EST 2003
Alex Martelli wrote:
> 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
>
>
Alex;
Many thanks. This is quite interesting.
Brian.
More information about the Python-list
mailing list