TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Python multi-level break and continue

42 pointsby angrygoatover 2 years ago

15 comments

norhi999over 2 years ago
I don&#x27;t get why they discarded<p><i>for&#x2F;while... as label1:<p>__for&#x2F;while... as label2:<p>___break label1</i><p>suggestion. It actually seems a good enough idea to implement that. And it&#x27;s rather concise. I often need to break deep inner loops to outermost and doing it with flags is... strange.
评论 #32713422 未加载
评论 #32698793 未加载
评论 #32711079 未加载
评论 #32710908 未加载
dataflowover 2 years ago
&gt; But the arguments given in support of the feature were generally fairly weak; they often used arbitrary, &quot;made up&quot; examples that demonstrated a place where multi-level break could be used, but were not particularly compelling.<p>&gt; To make this proposal convincing, we need a <i>realistic</i> example of an algorithm that uses it, and that example needs to be <i>significantly</i> more readable and maintainable than the refactorings into functions, or the use of try…except (also a localised goto).<p>How about this:<p><pre><code> found = None for r, row in enumerate(table.rows): for c, cell in enumerate(row): if search_query.matches(cell.value): found = (r, c) break 2 logger.log(&quot;Found cell: {}&quot;.format(found)) return found</code></pre>
评论 #32710887 未加载
评论 #32710389 未加载
评论 #32712952 未加载
评论 #32710505 未加载
评论 #32710822 未加载
评论 #32711255 未加载
评论 #32710578 未加载
评论 #32710439 未加载
artificialidiotover 2 years ago
I think it boils down to &quot;early exit&quot; v.s. &quot;single return&quot; style. More than likely, the average programmer will pick the style they&#x27;ve been taught at school or whichever was preached more.<p>I think early exit constructs improve readability and python already offers a lot of syntax open to abuse at this point. (things you can write with nested list&#x2F;dict comprehensions with if conditions&#x2F;expressions scattered..)
benstopicsover 2 years ago
The first thing that came to mind was either for&#x2F;else, try&#x2F;except, or refactoring out to a function which were all mentioned in the article. This solves the problem in all cases except a multi-level continue as it was called, and the solution by Python Millionaire was essentially goto labels. The reason high level programming languages moved away from goto labels is because they create spaghetti code. Goto labels were before for and while loops and are not necessary now, but this is a shallow answer because goto labels do work.<p>To dig deeper into why goto labels are bad and the alternative, what goto labels allow you to do is to create a state machine in procedural code. The more explicit way to do this is to create a dictionary object that tracks the state and a while loop with state-based logic that includes a halting condition. But according to Python Millionaire this would not be “Pythonic” which is basically just a blanket term for saying it is built into the language and therefore designed to be simple and easy to read. However, I would argue that goto statements are inherently un-Pythonic because they encourage spaghetti code. I don’t see how for&#x2F;else or try&#x2F;except is not Pythonic, but also I don’t see the aversion to refactoring to separate function which is the accepted cross-language way to refactor and simplify code. It even lets you write a built-in comment for what the function does, the function name. That being said, an easy way to determine if the function failed is to either throw and exception or simply return a result like True&#x2F;False which would determine whether to break out of the parent loop.
greatgibover 2 years ago
Personally I like very much the solution proposed at the end of comments:<p><a href="https:&#x2F;&#x2F;lwn.net&#x2F;Articles&#x2F;907510&#x2F;" rel="nofollow">https:&#x2F;&#x2F;lwn.net&#x2F;Articles&#x2F;907510&#x2F;</a><p>With something like: For loop... As my_loop: my_loop.continue()
henrydarkover 2 years ago
Python has coroutines (in the original sense), so one can implement almost Break-break. For example, it&#x27;s easy to implement an object so that this will work as expected:<p><pre><code> from easytowritelibrary import LoopManager lm = LoopManager() for x in lm(a1): for y in lm(a2): if cond: lm.break_(2); break block() </code></pre> It can support stuff like:<p><pre><code> for x in lm(a1, &quot;a1&quot;): for y in lm(a2, &quot;a2&quot;): if cond1: lm.break_(&quot;a1&quot;); break if cond2: lm.continue_(&quot;a1&quot;); break block() </code></pre> It can&#x27;t handle &quot;for-else&quot; correctly, but maybe that&#x27;s OK.
mangecoeurover 2 years ago
You might as well implement goto while you’re at it.
评论 #32713194 未加载
chkasover 2 years ago
I argue for a &quot;break&quot; with a number that indicates how many loops you want to break out of. I have this in my programming language <a href="https:&#x2F;&#x2F;easylang.online" rel="nofollow">https:&#x2F;&#x2F;easylang.online</a>. Each &quot;break&quot; needs the number, so also a &quot;break 1&quot;.<p><pre><code> for i = 1 to 50 for j = 1 to 50 if i * i + j * j * j = 80036 break 2 end end end print i &amp; &quot; &quot; &amp; j</code></pre>
评论 #32711077 未加载
评论 #32713829 未加载
shusakuover 2 years ago
FYI Fortran has this feature so if you feel like python is really missing this feature try using a more advanced language
rich_sashaover 2 years ago
Walrus operator? In. F string interpolation? In. Pattern matching? Hacked in.<p>Genuinely useful feature that is awkward to emulate? Nah.<p>Let&#x27;s face it, everyone writes a double or triple nested for loop every now and then.
评论 #32710827 未加载
评论 #32710768 未加载
评论 #32710896 未加载
评论 #32710869 未加载
hk1337over 2 years ago
Two nested loops is ugly but tolerable, 3+ is disgusting. Refactor it so you don’t have to go 3 deep.
评论 #32713391 未加载
barrkelover 2 years ago
It&#x27;s more tedious in C derivatives, where loops and switches share the break keyword. Where that isn&#x27;t the case, it&#x27;s much harder to justify multi-level break. Refactor to a function and return instead.
awinter-pyover 2 years ago
have always wanted `break break` syntax for this kind of thing<p><pre><code> for x in a1: for y in a2: if test(y): break break # break both outer loops </code></pre> in general, I wonder if there&#x27;s a class of &#x27;tree-like&#x27; control structures which can break multiple levels under certain circumstances<p>an application might be scope management parsing -- I tried to build something like this a while ago, not clear that it&#x27;s better than parser-generators but it&#x27;s certainly different
评论 #32710984 未加载
评论 #32710403 未加载
nemoniacover 2 years ago
Common Lisp has a system of Conditions and Restarts which can do this and more.<p>The link below describes an example of handling errors which arise when reading a collection of files line by line.<p><a href="https:&#x2F;&#x2F;gigamonkeys.com&#x2F;book&#x2F;beyond-exception-handling-conditions-and-restarts.html" rel="nofollow">https:&#x2F;&#x2F;gigamonkeys.com&#x2F;book&#x2F;beyond-exception-handling-condi...</a>
评论 #32710747 未加载
jeffybefffy519over 2 years ago
Could just raise StopIteration?
评论 #32710898 未加载