Heres the python code im having problems with:
for i in range (0,10):
if i==5:
i+=3
print i
I expected the output to be:
0
1
2
3
4
8
9
however the interpreter spits out:
0
1
2
3
4
8
6
7
8
9
I know that a for
loop creates a new scope for a variable in C, but have no idea about python. Can anyone explain why the value of i
doesnt change in the for
loop in python and whats the remedy to it to get the expected output.
or
A for loop in Python is actually a for-each loop. At the start of each loop,
i
is set to the next element in the iterator (range(0, 10)
in your case). The value ofi
gets re-set at the beginning of each loop, so changing it in the loop body does not change its value for the next iteration.That is, the
for
loop you wrote is equivalent to the following while loop:I gets reset every iteration, so it doesn't really matter what you do to it inside the loop. The only time it does anything is when i is 5, and it then adds 3 to it. Once it loops back it then sets i back to the next number in the list. You probably want to use a
while
here.The for loop iterates over all the numbers in
range(10)
, that is,[0,1,2,3,4,5,6,7,8,9]
.That you change the current value of
i
has no effect on the next value in the range.You can get the desired behavior with a while loop.
In my view, the analogous code is not a while loop, but a for loop where you edit the list during runtime:
Python's
for
loop simply loops over the provided sequence of values — think of it as "foreach". For this reason, modifying the variable has no effect on loop execution.This is well described in the tutorial.