Why doesn't this loop break?

前端 未结 6 1399
太阳男子
太阳男子 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:17

    Because Python's for loop doesn't count, it iterates. range produces an iterable (a list in Python 2.x), and that iterable is iterated over. Each time before the loop body is executed, the next item is pulled from it, and no changes you make in the loop body to the iteration variable affect the memory of what the next value is supposed to be. That's saved elsewhere and you generally can't affect it. Simply use break.

提交回复
热议问题