Unexpected result.
Andrew Dalke
adalke at mindspring.com
Thu Sep 23 16:36:46 EDT 2004
Grzegorz Dostatni wrote:
> My question is whether it would make more sense (be more
> intuitive) to have a for loop create its own local scope. (ie. an output
> string of
> 1 2 3 a 1 2 3 b 1 2 3 c
If for loops created a new local scope then the following
would not work
for i in range(10):
if data[i] == "stop":
break
else:
return None
print "Found at position", i
.. continue to work with that position ..
In Python only functions, modules, and classes
create a new scope (at least syntax-wise)
If you really, really want a scope there you
can do this
>>> for i in range(5):
... class Spam:
... for i in "ABC":
... print i,
... print "At end -->", i
... del i
... print "After del -->", i
... i = "qwerty" # show that 'i' gets removed
... print "After end of class scope", i
...
A B C At end --> C
After del --> 0
After end of class scope 0
A B C At end --> C
After del --> 1
After end of class scope 1
A B C At end --> C
After del --> 2
After end of class scope 2
A B C At end --> C
After del --> 3
After end of class scope 3
A B C At end --> C
After del --> 4
After end of class scope 4
>>>
Strange, but it works. I don't think I've seen
anyone use this in real code, and I don't really
advise you do either.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list