Scope of python variable in for loop

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

提交回复
热议问题