Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of Python for ... else

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?

like image 620
John Howard Avatar asked Jul 21 '10 03:07

John Howard


2 Answers

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.

like image 160
In silico Avatar answered Oct 29 '22 12:10

In silico


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
like image 6
smichak Avatar answered Oct 29 '22 14:10

smichak