Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 then continue iterating with 4. How do I do that?

like image 305
Bo Milanovich Avatar asked Sep 22 '11 03:09

Bo Milanovich


People also ask

How do you break the loop of iteration?

Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.

How do you stop a loop in Python if a condition is met?

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.

How do you break out of a for loop in a while loop?

To break out of a while loop, you can use the endloop, continue, resume, or return statement.


2 Answers

while i < 5:
   do stuff
   if i == 3:
      print "i is 3"
      continue
like image 159
Matthew Avatar answered Sep 22 '22 18:09

Matthew


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.

like image 36
Winston Ewert Avatar answered Sep 21 '22 18:09

Winston Ewert