Opposite of Python for ... else

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)