for循环从C转换为Python

Sub*_*noy 0 python for-loop

for在C中编写循环时如何编写循环:

for(i=0;i<10;)
{
    if(i%2==0)
       i=i+3;
    else
       i++;
    printf("%d\n",i);
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我这件事?我搜索了很多但找不到它.我在Python中用这样写的:

for i in range(0,10):
    if (i%2==0):
        i+=3
    else:
        i+=1
    print i
Run Code Online (Sandbox Code Playgroud)

输出:

3
2
5
4
7
6
9
8
11
10
Run Code Online (Sandbox Code Playgroud)

预期产量:

3
4
7
8
11
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释这个输出的原因吗?

jon*_*rpe 5

在Python中编写相同的循环:

i = 0
while i < 10:
    if i % 2 == 0:
       i += 3
    else:
       i += 1
    print i
Run Code Online (Sandbox Code Playgroud)

这使:

3
4
7
8
11
Run Code Online (Sandbox Code Playgroud)

请注意,根据教程:

forPython中的语句与您在C或Pascal中使用的语句略有不同.而不是总是迭代数字的算术级数(如在Pascal中),或者让用户能够定义迭代步骤和停止条件(作为C),Python的for语句迭代任何序列的项目(列表或string),按照它们出现在序列中的顺序.

在Python for循环中,i循环重复时循环变量(在本例中)发生的任何更改都将被忽略,并且将使用迭代的对象中的下一个值.在这种情况下,对象是一个数字列表:

>>> range(10)  # note that a 0 start is the default
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)

有些语言称之为for each循环.有关更多详细信息,另请参阅语言参考.