与 while 循环一样,如何跳过 for 循环中的步骤?

송준석*_*송준석 4 python for-loop

我尝试像 while 循环一样跳过 for 循环中的几个步骤。

在 while 循环中,步骤根据特定条件进行调整,如下面的代码所示。

i = 0 
while i <10:
    if i == 3:
        i = 5
    else:
        print(i)
    i = i + 1
#result 0 1 2 6 7 8 9
Run Code Online (Sandbox Code Playgroud)

然而,我尝试以同样的方式调整for循环的步骤,但失败了。

for i in range(10):
    if i == 3:
        i = 5
    else:
        print(i)
#result 0 1 2 4 5 6 7 8 9
Run Code Online (Sandbox Code Playgroud)

我不能直接在 for 循环中控制步骤“i”吗?

如果有办法,请告诉我,我将不胜感激。

sou*_*rge 7

循环体中的更改i没有任何影响,因为它会在每次迭代时自动分配“range() 结果中的下一个值”。您可以改为使用continue要跳过的值:

for i in range(10):
    if 3 <= i <= 5:
        continue
    else:
        print(i)
Run Code Online (Sandbox Code Playgroud)