开发者

Opposite of Python for ... else

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, I want the opposite of this. Is there a way to do a for ... else (or while ... else) loop, but only execute the else code if th开发者_高级运维e 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.


A bit more generic solution using exceptions in case you break in multiple points in the loop and don't want to duplicate code:

try:
    for n in range(15):
        if n == 10:
            n = 1200
            raise StopIteration()
        if n > 4:
            n = 1400
            raise StopIteration()
except StopIteration:
    print n


I didn't really like the answers posted so far, as they all require the body of the loop to be changed, which might be annoying/risky if the body is really complicated, so here is a way to do it using a flag. Replace _break with found or something else meaningful for your use case.

_break = True
for n in range(15):
    if n == 100:
        break
else:
    _break = False

if _break:
    print(n)

Another possibility, if it is a function that does nothing if the loop doesn't find a match, is to return in the else: block:

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


Use:

for n in range(15):
    if n == 100:
        break
else:
    print("loop successful")
if n != range(15)[-1]:
    print("loop failed")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜