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:
You can make the following modification to your for
loop:
for i in range (0,10):
if i in [5, 6, 7]:
continue
print(i)
In my view, the analogous code is not a while loop, but a for loop where you edit the list during runtime:
originalLoopRange = 5
loopList = list(range(originalLoopRange))
timesThroughLoop = 0
for loopIndex in loopList:
print(timesThroughLoop, "count")
if loopIndex == 2:
loopList.pop(3)
print(loopList)
print(loopIndex)
timesThroughLoop += 1
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.
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 of i
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:
_numbers = range(0, 10) #the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_iter = iter(_numbers)
while True:
try:
i = _iter.next()
except StopIteration:
break
#--YOUR CODE HERE:--
if i==5:
i+=3
print i
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.
i = 0
while i < 10:
# do stuff and manipulate `i` as much as you like
if i==5:
i+=3
print i
# don't forget to increment `i` manually
i += 1
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.