I recently read this question which had a solution about labeling loops in Java.
I am wondering if such a loop-naming system exists in Python. I have been in a situation multiple times where I do need to break out of an outer for
loop from an inner for
loop. Usually, I solve this problem by putting the inner loop in a function that returns (among others) a boolean which is used as a breaking condition. But labeling loops for breaking seems a lot simpler and I would like to try that, if such functionality exists in python
Does anyone know if it does?
Many popular programming languages support a labelled break statement. It's mostly used to break out of the outer loop in case of nested loops. However, Python doesn't support labeled break statement. PEP 3136 was raised to add label support to break statement.
In Java, there are three kinds of loops which are – the for loop, the while loop, and the do-while loop. All these three loop constructs of Java executes a set of repeated statements as long as a specified condition remains true. This particular condition is generally known as loop control.
Here's a way to break out of multiple, nested blocks using a context manager:
import contextlib @contextlib.contextmanager def escapable(): class Escape(RuntimeError): pass class Unblock(object): def escape(self): raise Escape() try: yield Unblock() except Escape: pass
You can use it to break out of multiple loops:
with escapable() as a: for i in xrange(30): for j in xrange(30): if i * j > 6: a.escape()
And you can even nest them:
with escapable() as a: for i in xrange(30): with escapable() as b: for j in xrange(30): if i * j == 12: b.escape() # Break partway out if i * j == 40: a.escape() # Break all the way out
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With