Why doesn't this loop break?

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

    Why would it exit? You're iterating over elements of range(0, 10), the only exit condition is that your run out of elements. Rebinding the name doesn't change anything inside the iterable. If you want to break prematurely, use break.

    for i in range(0, 10):
        if i == 5: break
    

提交回复
热议问题