我问的不是Python的作用域规则;我大致了解Python for循环中的作用域是如何工作的。我的问题是为什么设计决策是以这种方式做出的。例如(不是双关语):
for foo in xrange(10):
bar = 2
print(foo, bar)
上面将输出(9,2)。
This strikes me as weird: 'foo' is really just controlling the loop, and 'bar' was defined inside the loop. I can understand why it might be necessary for 'bar' to be accessible outside the loop (otherwise, for loops would have very limited functionality). What I don't understand is why it is necessary for the control variable to remain in scope after the loop exits. In my experience, it simply clutters the global namespace and makes it harder to track down errors that would be caught by interpreters in other languages.