for ii in range(200):
for jj in range(200, 400):
...block0...
if something:
break
else:
...block1...
Break will break the inner loop, and block1 won't be executed (it will run only if the inner loop is exited normally).
for ii in range(200):
for jj in range(200, 400):
...block0...
if something:
break
else:
...block1...
Break will break the inner loop, and block1 won't be executed (it will run only if the inner loop is exited normally).
for i in ...:
for j in ...:
for k in ...:
if something:
# continue loop i
In a general case, when you have multiple levels of looping and break does not work for you (because you want to continue one of the upper loops, not the one right above the current one), you can do one of the following
Refactor the loops you want to escape from into a function
def inner():
for j in ...:
for k in ...:
if something:
return
for i in ...:
inner()
The disadvantage is that you may need to pass to that new function some variables, which were previously in scope. You can either just pass them as parameters, make them instance variables on an object (create a new object just for this function, if it makes sense), or global variables, singletons, whatever (ehm, ehm).
Or you can define inner as a nested function and let it just capture what it needs (may be slower?)
for i in ...:
def inner():
for j in ...:
for k in ...:
if something:
return
inner()
Use exceptions
Philosophically, this is what exceptions are for, breaking the program flow through the structured programming building blocks (if, for, while) when necessary.
The advantage is that you don't have to break the single piece of code into multiple parts. This is good if it is some kind of computation that you are designing while writing it in Python. Introducing abstractions at this early point may slow you down.
Bad thing with this approach is that interpreter/compiler authors usually assume that exceptions are exceptional and optimize for them accordingly.
class ContinueI(Exception):
pass
continue_i = ContinueI()
for i in ...:
try:
for j in ...:
for k in ...:
if something:
raise continue_i
except ContinueI:
continue
Create a special exception class for this, so that you don't risk accidentally silencing some other exception.
Something else entirely
I am sure there are still other solutions.
Breaking out of nested loops
tideman, how to break out of a nested inner loop but continue the outer loop
python - How to continue the outer loop? - Stack Overflow
How to continue in nested loops in Python - Stack Overflow
Videos
for x in range(10):
for y in range(10):
if x + y == 10:
print('break')
break
else:
continue
breakI understand everything until the else statement. I dont know how its being called without an if statement or what its doing at all. Also why is break not indented after the else statement.Please help
This is my first time posting a coding question on any website, so apologies if i dont do a great job. Constructive feedback is very welcome.
I cant figure out a way to break out of the inner nested loop but continue the outer loop. As in, if is_cycle is true, the lines:
locked[pairs[i].winner][pairs[i].loser] = true; num_locked++;
need to be skipped for that current iteration of the outer loop.
Thank you so much.
// Lock pairs into the candidate graph in order, without creating cycles
void lock_pairs(void)
{
int num_locked = 0;
//loop through pairs
//has loser won before?
//if no, lock the pair
//if yes, call is_cycle on pair. if its not a cycle lock the pair
for (int i = 0; i < pair_count; i++)
{
//has the loser won before?
for (int j = 0; j < i; j++)
{
if (pairs[i].loser == pairs[j].winner)
{
//if the loser has won before and it creates a cycle, break the inner
//loop, continue outer
if (is_cycle(pairs[i], pairs[j], num_locked))
{
break;
}
}
}
//this is incorrect this will lock the pair each time
locked[pairs[i].winner][pairs[i].loser] = true;
num_locked++;
}
return;
}
I have tried searching through stack overflow. Some mentioned a goto
function but most people said that is bad programming. someone else mentioned creating a separate function and using return
statements but i need that outer loop to continue, not stop. And one other answer suggested using flags
, which after more searching i still dont get how that could help.
The behavior that you expect is not fully clear, but you could use a flag:
break_flag = False
for i in range(1, 5):
if break_flag:
break_flag = False
continue
for j in listD:
if smth:
break_flag = True
break
or a try/except block:
for i in range(1, 5):
try:
for j in listD:
if smth:
raise StopIteration # you might want to use a custom error
except StopIteration:
continue
Just indent the code correctly. Python uses spaces to know which statements are in scope. If you use 4 spaces to indent code, then another 4 spaces means an inner code block (8 spaces in total). This is like nesting in a programming language like C or Java but without the "{ }". To end code block and get to outer loop just write with 4 spaces less in the next line of code.
One important thing to note is number of spaces used should be consistent. You must use consistent units of spaces. If one indent block is 4 spaces, you must use multiples of 4 to intent code in the same file. Ideally use 4 spaces as a unit of indent for statements sin same code block.
for i in range(1, 5):
#outer loop statements here
for j in listD:
#inner loop statements here
pass
#outer loop statements again
if smth:
#this if block statements is part of outer loop statements
continue
Now continue statement gets executed after inner loop is executed. You need continue statement only if you have statements which you need to skip over.
- Break from the inner loop (if there's nothing else after it)
- Put the outer loop's body in a function and return from the function
- Raise an exception and catch it at the outer level
- Set a flag, break from the inner loop and test it at an outer level.
- Refactor the code so you no longer have to do this.
I would go with 5 every time.
Here's a bunch of hacky ways to do it:
Create a local function
for a in b: def doWork(): for c in d: for e in f: if somecondition: return # <continue the for a in b loop?> doWork()A better option would be to move doWork somewhere else and pass its state as arguments.
Use an exception
class StopLookingForThings(Exception): pass for a in b: try: for c in d: for e in f: if somecondition: raise StopLookingForThings() except StopLookingForThings: pass