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)
When we compile C code, it goes into a infinite loop printing 5 forever, whereas in Python it doesn’t, why not?
The Python output is:
0 1 2 3 4 5 5 6 7 8
In Python, the loop does not increment
i, instead it assigns it values from the iterable object (in this case, list). Therefore, changingiinside the for loop does not “confuse” the loop, since in the next iterationiwill simply be assigned the next value.In the code you provided, when
iis 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.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:
Is equivalent to:
Then your for infinite loop could be written in Python as: