Scope of python variable in for loop

2019-01-02 16:17发布

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.

8条回答
旧时光的记忆
2楼-- · 2019-01-02 16:21
it = iter(xrange (0,10))
for i in it:
    if i==4: all(it.next() for a in xrange(3))
    print i

or

it = iter(xrange (0,10))
itn = it.next
for i in it:
    if i==4: all(itn() for a in xrange(3))
    print i
查看更多
若你有天会懂
3楼-- · 2019-01-02 16:27

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
查看更多
余生无你
4楼-- · 2019-01-02 16:30

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.

查看更多
皆成旧梦
5楼-- · 2019-01-02 16:34

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
查看更多
无与为乐者.
6楼-- · 2019-01-02 16:35

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
查看更多
孤独寂梦人
7楼-- · 2019-01-02 16:39

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.

查看更多
登录 后发表回答