r/ProgrammerTIL • • 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 i

Rather than the second loop erroring out, it just used the last value of i on every iteration.

81 Upvotes

26 comments sorted by

View all comments

Show parent comment

2

u/ThreePinkApples Jan 22 '19

Oh, I should try to create some good before and after examples. That could work

2

u/pickausernamehesaid Jan 22 '19

Definitely, show off f-strings, ordered dictionaries by default, async/await, dataclasses, matrix multiplication with '@', and anything else you can think of.