Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Python for loop doesn't work like C for loop?

Tags:

python

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)

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

like image 287
Surya Avatar asked Jan 21 '12 16:01

Surya


1 Answers

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.

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.

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) ...

Is equivalent to:

init
while(condition) {
    ...
    term
}

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
like image 86
drrlvn Avatar answered Nov 15 '22 08:11

drrlvn