为什么Python for loop不能像C for loop一样工作?

为什么Python for loop不能像C for loop一样工作?

问题描述:

C:

# include <stdio.h>
main()
{
    int i;
    for (i=0; i<10; i++)
    {
           if (i>5) 
           {
             i=i-1;     
             printf("%d",i);
           } 
    }
}

Python:

for i in range(10):
   if i>5: i=i-1
   print(i)

当我们编译C代码时,它会进入无限循环,直到永远打印5,而在Python中却没有,为什么不呢?

When we compile C code, it goes into a infinite loop printing 5 forever, whereas in Python it doesn't, why not?

Python输出为:

The Python output is:

0 1 2 3 4 5 5 6 7 8

0 1 2 3 4 5 5 6 7 8

在Python中,循环不会递增i,而是从可迭代对象(在这种情况下为list)分配值.因此,在for循环中更改i不会混淆"该循环,因为在下一次迭代中,i将仅被分配下一个值.

In Python, the loop does not increment i, instead it assigns it values from the iterable object (in this case, list). Therefore, changing i inside the for loop does not "confuse" the loop, since in the next iteration i will simply be assigned the next value.

在您提供的代码中,当i为6时,它将在循环中递减,以便将其更改为5,然后进行打印.在下一次迭代中,Python只需将其设置为列表[0,1,2,3,4,5,6,7,8,9]中的下一个值,即7,依此类推.没有更多值可使用时,循环终止.

In the code you provided, when i is 6, it is then decremented in the loop so that it is changed to 5 and then printed. In the next iteration, Python simply sets it to the next value in the list [0,1,2,3,4,5,6,7,8,9], which is 7, and so on. The loop terminates when there are no more values to take.

当然,您在C循环中获得的效果仍然可以在Python中实现.由于每个for循环都是美化的while循环,因此可以这样转换:

Of course, the effect you get in the C loop you provided could still be achieved in Python. Since every for loop is a glorified while loop, in the sense that it could be converted like this:

for (init; condition; term) ...

等效于:

init
while(condition) {
    ...
    term
}

那么您的for无限循环可以用Python编写为:

Then your for infinite loop could be written in Python as:

i = 0
while i < 10:
    if i > 5:
        i -= 1
    print i
    i += 1