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
1
u/pickausernamehesaid Jan 21 '19
This part really screwed me up for a while on one project I was working a while ago. The implicit shadow at the beginning can lead to it being undefined early in the function if you need to reassign it. Ex:
The solution is to add
nonlocal some_varto the beginning of g() (which was new keyword for me:P).