Scope of python variable in for loop

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

    In python 2.7 range function create a list while in python 3.x versions it creates a 'range' class object which is only iterable not a list, similar to xrange in python 2.7.

    Not when you are iterating over range(1, 10), eventually you are reading from the list type object and i takes new value each time it reaches for loop.

    this is something like:

    for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
        if i==5:
            i+=3
        print(i)
    

    Changing the value wont change the iteration order from the list.

提交回复
热议问题