为什么 Python for 循环不像 C for 循环那样工作? [英] Why Python for loop doesn't work like 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);
}
}
}
蟒蛇:
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
,而是从可迭代对象(在本例中为列表)中为其分配值.因此,在 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
这篇关于为什么 Python for 循环不像 C for 循环那样工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!