开发者

How to break out of the loop only if a certain case is met, but then continue the iteration?

开发者 https://www.devze.com 2023-04-06 19:23 出处:网络
I realize that the title may be somewhat confusing, so I apologize. Basically, this is my code: while i < 5:

I realize that the title may be somewhat confusing, so I apologize.

Basically, this is my code:

while i < 5:
   do stuff
   if i == 3:
      print "i is 3"
      break

Now all that sounds pretty simple, right? Except I don't really want to BREAK from the loop as much as I'd want it to start over again. So in this case the desired result would be to iterate through 1, 2, then when 3 break out, but the开发者_运维百科n continue iterating with 4. How do I do that?


while i < 5:
   do stuff
   if i == 3:
      print "i is 3"
      continue


Instead of break use continue

Now, I pretty much never use continue as I find it is usually clearer to rework the code to avoid it. Of course that's really easy in this example, if you have trouble with a more complex example ask about that one.

0

精彩评论

暂无评论...
验证码 换一张
取 消