I\'m not asking about Python\'s scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were m
For starters, if variables were local to loops, those loops would be useless for most real-world programming.
In the current situation:
# Sum the values 0..9
total = 0
for foo in xrange(10):
total = total + foo
print total
yields 45
. Now, consider how assignment works in Python. If loop variables were strictly local:
# Sum the values 0..9?
total = 0
for foo in xrange(10):
# Create a new integer object with value "total + foo" and bind it to a new
# loop-local variable named "total".
total = total + foo
print total
yields 0
, because total
inside the loop after the assignment is not the same variable as total
outside the loop. This would not be optimal or expected behavior.