Scoping in Python 'for' loops
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping
--
Chapters
00:00 Scoping In Python 'For' Loops
00:50 Answer 1 Score 54
01:21 Answer 2 Score 81
01:36 Accepted Answer Score 161
02:21 Answer 4 Score 4
02:44 Thank you
--
Full question
https://stackoverflow.com/questions/3611...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #scope
#avk47
ACCEPTED ANSWER
Score 161
The likeliest answer is that it just keeps the grammar simple, hasn't been a stumbling block for adoption, and many have been happy with not having to disambiguate the scope to which a name belongs when assigning to it within a loop construct.  Variables are not declared within a scope, it is implied by the location of assignment statements.  The global keyword exists just for this reason (to signify that assignment is done at a global scope).
Update
Here's a good discussion on the topic: http://mail.python.org/pipermail/python-ideas/2008-October/002109.html
Previous proposals to make for-loop variables local to the loop have stumbled on the problem of existing code that relies on the loop variable keeping its value after exiting the loop, and it seems that this is regarded as a desirable feature.
In short, you can probably blame it on the Python community :P
ANSWER 2
Score 81
Python does not have blocks, as do some other languages (such as C/C++ or Java). Therefore, scoping unit in Python is a function.
ANSWER 3
Score 54
A really useful case for this is when using enumerate and you want the total count in the end:
for count, x in enumerate(someiterator, start=1):
    dosomething(count, x)
print "I did something {0} times".format(count)
Is this necessary? No. But, it sure is convenient.
Another thing to be aware of: in Python 2, variables in list comprehensions are leaked as well:
>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> x
9
But, the same does not apply to Python 3.
ANSWER 4
Score 4
One of the primary influences for Python is ABC, a language developed in the Netherlands for teaching programming concepts to beginners. Python's creator, Guido van Rossum, worked on ABC for several years in the 1980s. I know almost nothing about ABC, but as it is intended for beginners, I suppose it must have a limited number of scopes, much like early BASICs.