Scope of python variable in for loop

前端 未结 10 1867
一整个雨季
一整个雨季 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: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
    

提交回复
热议问题