Scope of python variable in for loop

前端 未结 10 1852
一整个雨季
一整个雨季 2020-11-22 15:16

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:

相关标签:
10条回答
  • 2020-11-22 15:53

    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)
    
    0 讨论(0)
  • 2020-11-22 15:55

    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
    
    0 讨论(0)
  • 2020-11-22 15:56

    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.

    0 讨论(0)
  • 2020-11-22 15:57

    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
    
    0 讨论(0)
  • 2020-11-22 15:58

    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
    
    0 讨论(0)
  • 2020-11-22 15:58

    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.

    0 讨论(0)
提交回复
热议问题