In my Jupyter notebook (Python 3) I use the variable kk over and over:
kk = 7
for kk in range(2): # ranging from 0 to 1
for kk in range(90,92): # ranging from 90-91
for kk in range(10,12): # ranging from 10-11
print(kk)
kk
As I understand, the for kk in range(2) loop uses its own kk variable (scope) and does not care about the kk defined above, nor the kk from the other loops. The same is true for the for kk in range(90,92) loop and the for kk in range(10,12) loop. How come all of them overwrite the globally defined kk, so that the final kk is 11, but they never read the global kk?
I am trying to understand scopes and namespaces. But I expected that:
- none of the loops would overwrite the global
kk, as they usekkin their own scope (which I expected due to Namespace and scope in Python); or - the loop should end after the first iteration, as
kkis now set to10, which lies outside the required range of the outermost loop.
I think Scope and Namespace in Python is trying to explain it, but I do not understand.
kkis somehow checked against range. Whatever is afterinis used as iterable, taking elements from it one by one and assigning it tokk. This is done disregarding whatkkcurrently is, and will be repeated untill all elements of iterable are exhausted.kk, and its value gets constantly overwritten by each loop. That's it. You may be incorrectly assuming that the loop works likefor (kk = 0; kk < 42; kk++)in some other languages, but that's wrong, it doesn't.