for x in range(10):
for y in range(10):
print(x * y)
if x * y > 50:
break
else:
continue # only executed if the inner loop did NOT break
break # only executed if the inner loop DID break
The same works for deeper loops:
for x in range(10):
for y in range(10):
for z in range(10):
print(x, y, z)
if (x * y * z) == 30:
break
else:
continue
break
else:
continue
break
Answer from Markus Jarderot on Stack Overflowfor x in range(10):
for y in range(10):
print(x * y)
if x * y > 50:
break
else:
continue # only executed if the inner loop did NOT break
break # only executed if the inner loop DID break
The same works for deeper loops:
for x in range(10):
for y in range(10):
for z in range(10):
print(x, y, z)
if (x * y * z) == 30:
break
else:
continue
break
else:
continue
break
It has at least been suggested, but also rejected. I don't think there is another way, short of repeating the test or re-organizing the code. It is sometimes a bit annoying.
In the rejection message, Mr van Rossum mentions using return, which is really sensible and something I need to remember personally. :)
My first instinct would be to refactor the nested loop into a function and use return to break out.
Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want.
for a in range(10):
for b in range(20):
if something(a, b):
break # Break the inner loop...
else:
continue # Continue if the inner loop wasn't broken.
break # Inner loop was broken, break the outer.
This uses the for / else construct explained at: Why does python use 'else' after for and while loops?
Key insight: It only seems as if the outer loop always breaks. But if the inner loop doesn't break, the outer loop won't either.
The continue statement is the magic here. It's in the for-else clause. By definition that happens if there's no inner break. In that situation continue neatly circumvents the outer break.
Breaking/continuing out of multiple loops - Ideas - Discussions on Python.org
Break from multiple loops at once - Ideas - Discussions on Python.org
How to break out of nested loops in python? - Stack Overflow
control flow - What are the different options for breaking out of an inner loop? - Programming Language Design and Implementation Stack Exchange
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
A break will only break out of the inner-most loop it's inside of. Your first example breaks from the outer loop, the second example only breaks out of the inner loop.
To break out of multiple loops you need use a variable to keep track of whether you're trying to exit and check it each time the parent loop occurs.
is_looping = True
for i in range(5): # outer loop
for x in range(4): # inner loop
if x == 2:
is_looping = False
break # break out of the inner loop
if not is_looping:
break # break out of outer loop
In Python you can write an else clause for a loop, which is executed when no break happens in the loop, or when the loop terminates naturally so to speak. Sometimes you can use it to break from multiple loops.
for i in some_range:
for j in some_other_range:
if need_break(i, j):
break
else:
continue
break # break happens in inner loop, break outer loop too.
Early returns
Python notably doesn't allow labelled break and continue statements. Instead, when it's necessary to break from a nested loop, the programmer can write the nested loop in a function and use return to terminate the loop early.
Cartesian products
Instead of having a way to break from nested loops, you can give the programmer a way to write their code with just one loop. Python's standard library contains the helpful itertools.product which can be used to refactor nested for loops into a single level. For example, these two loops iterate over the same values in the same order:
for x in xs:
for y in ys:
for z in zs:
...
from itertools import product
for x, y, z in product(xs, ys, zs):
...
Short-circuiting functions for iteration
If you want to terminate a loop early, it's likely because you're doing some kind of search and you want to stop when you find the thing being searched for. So your language's standard library can provide helper functions for doing such searches, and the helper functions can handle the termination condition so that the programmer doesn't need to break explicitly.
Using Python again as an example, any and all are two such functions in the standard library, which can accept "nested loops" in the form of generator expressions. These are equivalent:
any_found = False
for x in xs:
for y in ys:
if some_condition(x, y):
any_found = True
break
any_found = any(some_condition(x, y) for x in xs for y in ys)
Depth Number
One option is for break and continue to accept a number, being the number of extra loops to break out of. A break; would be equivalent to break 0;.
while (condition) {
while (condition) {
// break 1;
// continue 1;
}
}
Tagged Loops
Another way that does not involve goto is to label the loops themselves and break a loop corresponding to a certain label. Java and Swift do this.
outer: while (condition) {
while (condition) {
// break outer;
// continue outer;
}
}
Breaking Construct Type
A third way, while less capable than the others, could still be useful, is to use the keyword for the construct in the break or continue statement.
while (condition) {
for (init; condition; increment) {
switch (value) {
case 10:
print("Value is 10");
break switch; // Breaks the switch
case 100:
break while; // Exits the entire while loop
default:
break for; // Breaks the for loop
}
}
}