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
-10
u/CommonMisspellingBot Jan 20 '19
Hey, nukestar101, just a quick heads-up:
seperate is actually spelled separate. You can remember it by -par- in the middle.
Have a nice day!
The parent commenter can reply with 'delete' to delete this comment.