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

前端 未结 4 1816
天涯浪人
天涯浪人 2020-12-11 05:28

C:

# include 
main()
{
    int i;
    for (i=0; i<10; i++)
    {
           if (i>5) 
           {
             i=i-1;     
                     


        
4条回答
  •  再見小時候
    2020-12-11 06:03

    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
    

提交回复
热议问题