Python的对面是... [英] Opposite of Python for ... else

查看:147
本文介绍了Python的对面是...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的python代码会导致n(14)被打印,因为for循环已经完成了。

  for n (15):
if n == 100:
break
else:
print(n)

然而,我想要的是与此相反的。有没有办法做一个for ... else(或while ... else)循环,但只执行else代码,如果循环中断?


<在Python中没有明确的 for ... elseifbreak 类似的构造(或者任何语言知道),因为你可以简单地做到这一点:$ b​​
$ b pre $ 在范围(15)中的n:
if n ==如果您有多个<$
code> break
s,把 print(n)放入一个函数中,这样你就可以不要重复自己


The following python code will result in n (14) being printed, as the for loop is completed.

for n in range(15):
    if n == 100:
        break
else:
    print(n)

However, what I want is the opposite of this. Is there any way to do a for ... else (or while ... else) loop, but only execute the else code if the loop did break?

解决方案

There is no explicit for...elseifbreak-like construct in Python (or in any language that I know of) because you can simply do this:

for n in range(15): 
    if n == 100:
        print(n)  
        break

If you have multiple breaks, put print(n) in a function so you Don't Repeat Yourself.

这篇关于Python的对面是...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆