r/ProgrammerTIL • u/some_q • Jan 20 '19
Other [Python] Loop variables continue to exist outside of the loop
This code will print "9" rather than giving an error.
for i in range(10):
pass
print(i)That surprised me: in many languages, "i" becomes undefined as soon as the loop terminates. I saw some strange behavior that basically followed from this kind of typo:
for i in range(10):
print("i is %d" % i)
for j in range(10):
print("j is %d" % i) # Note the typo: still using iRather than the second loop erroring out, it just used the last value of i on every iteration.
81
Upvotes
View all comments
Show parent comment
14
u/[deleted] Jan 20 '19
Python doesn't have "blocks" like some other languages, so it's not actually a different scope.
Later in the thread I linked, someone mentions that changing the way scoping works had been discussed by the developers, but that it would break backward compatibility.