Why doesn't this loop break?

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

    Because for i in whatever means that for each element in whatever, the loop body will be executed once setting i to that element. There is no rule that says that at the end of each iteration, i must still be an element of whatever.

    Reassigning i in the loop body has no effect whatsoever on how often the loop body executes or which value i will hold in the next iteration.

提交回复
热议问题