Opposite Python for ... else

The following python code will print n (14) since the for loop has completed.

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

However, what I want is the opposite of this. Is there a way to make a for ... else loop (or while ... else), but only execute the else code if the loop breaks?

+6
python for-loop if-statement
source share
4 answers

In Python (or in any language I know) there is no explicit for...elseifbreak -like construct, because you can just do this:

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

If you have multiple break s, put print(n) in the function so that you Do not Repeat Yourself .

+16
source share

A slightly more general solution using exceptions if you break multiple points in a 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 
+6
source share

I did not like the answers posted so far, since they all require the body of the cycle to be changed, which can be annoying / risky if the body is really complex, so here is a way to do this using the 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 does not find a match, is in return in the else: block else:

 for n in range(15): if n == 100: break else: return print(n) 
+4
source share

What about:

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

All Articles