7

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 the loop did break?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John Howard
  • 61,037
  • 23
  • 50
  • 66
  • Too tired to write a solution atm (maybe later!) but using contextmanagers could be a solution! Source of inspiration could be here: http://stackoverflow.com/a/3171971/1524913 – jeromej Mar 21 '15 at 15:45

4 Answers4

15

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
  • 51,091
  • 10
  • 150
  • 143
7

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
  • 4,716
  • 3
  • 35
  • 47
4

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

Use:

for n in range(15):
    if n == 100:
        break
else:
    print("loop successful")
if n != range(15)[-1]:
    print("loop failed")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Leon
  • 9
  • 1
  • This gives the wrong result if the `break` happens in the last loop iteration. It will print _both_ "loop successful" and "loop failed" in that case. – Sven Marnach Jun 01 '17 at 10:44
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Dima Kozhevin Jul 27 '20 at 20:01
  • 1
    Hello! While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Brian61354270 Jul 27 '20 at 20:06