当循环变量递增时,为什么for循环中没有跳过迭代?

OK_*_*_sr 0 python loops for-loop

def loop():
    for i in range (0,9):
        pass
        if i == 3:
            i = i +3

        print(i)

loop()
Run Code Online (Sandbox Code Playgroud)

当前输出:

0
1
2
6
4
5
6
7
8
Run Code Online (Sandbox Code Playgroud)

期待输出:

0
1
2
6
7
8
9
Run Code Online (Sandbox Code Playgroud)

这是否必须对Python中创建堆栈帧的方式做些什么?为什么即使我们增加i,迭代次数也不会减少?

cs9*_*s95 7

i与循环执行没有任何关系.这是由... range(0, 9)(或,range(9))确定的.该for循环是为了遍历一个迭代器,并重复了迭代的定数.如果你想跳过循环迭代,你可以用一个条件控制来做continue.

不过,对于你的情况,我建议while循环,这种要求的惯用选择.

i = 0
while i < 9:
    ... # something happens here
    if i == 3:
        i += 3
    else:
        i += 1
Run Code Online (Sandbox Code Playgroud)

进一步阅读; 何时在Python中使用"while"或"for"