Scope of python variable in for loop

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

提交回复
热议问题