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
22
u/[deleted] Jan 20 '19
relevant
19
u/sharted_ptr Jan 20 '19 edited Jan 20 '19
This is true for
ifas well:Thats pretty pythonic in my book, but
barwould be undefined or undeclared in most languages.13
u/kazagistar Jan 20 '19
The only scopes in python are module level and function level.
Assigning a value to a variable anywhere in scope creates an implicit declaration of it at the start of the scope, shadowing any variables of the same name in lower scopes for the entire duration of the scope unless a special keyword is used.
Its simple, but a fairly common confusion.
3
u/[deleted] Jan 20 '19
Javascript's evolution is interesting when it comes to variables and loops. It gives you the option of a variable only existing inside the loop or not by using the keywords
varorlet.Variable exists inside and outside for loop, example:
Variable exists only inside for loop, example:
0
u/[deleted] Jan 21 '19
[deleted] — view deleted comment
-3
u/[deleted] Jan 20 '19
[removed] — view removed comment