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

前端 未结 4 1819
天涯浪人
天涯浪人 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 05:56

    The two constructs are both called for loops but they really aren't the same thing.

    Python's version is really a foreach loop. It runs once for each element in a collection. range(10) produces a list like [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] So the for loop runs once for each member of the collection. It doesn't use the value of i in deciding what the next element is, it always takes the next element in the list.

    The c for loop gets translated into the equivalent of

    int i = 0
    while i < 10:
       ...
       i++;
    

    Which is why you can manipulate the i.

提交回复
热议问题