I have the following script:
for i in range (10):
print i
i = 11
When i execute this script, I was expecting to print out only 0, but instead, it prints out 0 to 9. Why i=11 did not stop the for loop?
I have the following script:
for i in range (10):
print i
i = 11
When i execute this script, I was expecting to print out only 0, but instead, it prints out 0 to 9. Why i=11 did not stop the for loop?
changing i
inside the for-loop have no effect how many iterations are performed because that is controlled by how many elements are inside range or in whatever you are looping in, likewise it don't have any effect in which value i
will have in the next iteration.
Internally a for loop like this
for elem in iterable:
#stuff
#other stuff
is transformed to something like this (for any stuff and for any iterable)
iterator = iter(iterable)
while True:
try:
elem = next(iterator)
#stuff
except StopIteration:
break
#other stuff
the iterator constructed by iter will trow a StopIteration exception when there are no more elements inside it, and to get the next element you use next. break is used to end a for/while loop and the try-except is used to catch and handled exceptions.
As you can see, any change you do elem
(or i
in your case) is meaningless to how many iteration you will have or its next value.
To stop a for-loop prematurely you use break
, in your case that would be
for i in range(10):
print i
break