views:

191

answers:

3

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?

+13  A: 

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.

In silico
Surely not what the op wanted?
Sanjay Manohar
why not? it has the same effect. If you want code to run when you encounter a `break` statement, then just ... run the code before the break statement
matt b
I haven't seen constructs like that per se, but you can always use \*shudders\* `goto`
NullUserException
@NullUserException, http://entrian.com/goto/
gnibbler
The point is that what the OP wanted isn't what he's really looking for, there is a better way to do it.
Mk12
+3  A: 

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;
smichak
+1  A: 

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)
gnibbler