Home > Backend Development > Python Tutorial > 如何在Python中使用break跳出多层循环?

如何在Python中使用break跳出多层循环?

WBOY
Release: 2016-06-06 16:23:59
Original
4448 people have browsed it

<span class="k">for</span> <span class="n">a</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">b</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="mi">20</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">something</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
            <span class="c"># Break the inner loop...</span>
            <span class="k">break</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="c"># Continue if the inner loop wasn't broken.</span>
        <span class="k">continue</span>
    <span class="c"># Inner loop was broken, break the outer.</span>
    <span class="k">break</span>
Copy after login

回复内容:

我又有些忍不住要说了……你们学python是从来不看官方文档,只是跟着某某某中文教程一路撸下去的么?

Python的循环体自己就有else分支!
Python的循环体自己就有else分支!
Python的循环体自己就有else分支!

不只是if有,while和for都有else分支。循环体的else分支触发条件是循环正常结束。如果循环内被break跳出,就不执行else。所以这个逻辑是:如果循环内break了,不触发else,则执行下一句外层循环中的break;如果正常结束,执行else分支里的continue,直接跳转到外层循环的下一轮,跳过了第二个break。

不过这写法真尼玛丑啊……搞个布尔量会死么……

————————

其实感觉比较正确的姿势应该是拿个函数包起来然后用return…… 抛个异常外面接着不就完了 for和while的else子句用于循环后处理,仅在循环正常结束时执行。

问题中所举的例子,设置一个flag变量,代码看起来会更直观一些。

难说哪种写法好,我倒挺喜欢用else分支的。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template