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?

1
  • Too tired to write a solution atm (maybe later!) but using contextmanagers could be a solution! Source of inspiration could be here: stackoverflow.com/a/3171971/1524913 Commented Mar 21, 2015 at 15:45

4 Answers 4

17

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Surely not what the op wanted?
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
I haven't seen constructs like that per se, but you can always use *shudders* goto
The point is that what the OP wanted isn't what he's really looking for, there is a better way to do it.
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

Comments

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)

Comments

0

Use:

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

3 Comments

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.
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.
Hello! While this code may solve the question, including an explanation 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.