Why doesn't this loop break?

前端 未结 6 1459
太阳男子
太阳男子 2021-01-16 00:01

Python noob; please explain why this loop doesn\'t exit.

for i in range(0,10):
  print \"Hello, World!\"
  if i == 5: i = 15
  print i
next

6条回答
  •  难免孤独
    2021-01-16 00:21

    In python the for loop is not a while loop like in C or Java; it's instead an iteration over an iterable.

    In you case (assuming Python 2.x) range(0, 10) (that by the way is the same as range(10)) is a function that returns a list. A python list is an iterable and can therefore be used in a for loop... what the language will do is assigning the variable to first, second, third element and so on and each time it will execute the body part of for.

    It doesn't matter if you alter that variable in the body... Python will just pick next element of the list until all elements have been processed. Consider that your loop is not really different from

     for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
         print "Hello, world."
         if i == 5: i = 15
         print i
    

    that in turn is also quite similar to

     for i in [1, 29, 5, 3, 77, 91]:
         print "Hello, world."
         if i == 5: i = 15
         print i
    

    why should an assignment to i break the loop?

提交回复
热议问题