简体   繁体   中英

Is there an inverse behavior to the “else” in a for-else loop?

I have a for loop which tests for a condition. I would like to execute some code if the condition was never met. The following code does the opposite:

a = [1, 2, 3]
for k in a:
    if k == 2:
        break
else:
    print("no match")

"no match" is printed if the break is not reached (for a condition like k == 10 for instance). Is there a construction which would do the opposite, ie run some code if the break is reached?

I know I can do something like

a = [1, 2, 3]
match = False
for k in a:
    if k == 2:
        match = True
if match:
    print("match")

but was looking for a more compact solution, without the flag variable..

Note : I now realize from the answers that I did not make it clear that I would like to move the "matched" code outside of the for loop. It will be rather large and I would like to avoid hiding it in the for loop (thus the idea of the flag variable)

If you put your condition inside of a function or a comprehension, you can use the any keyword to accomplish this in a very pythonic way.

if not any(k == 2 for k in a):
    print 'no match'

If you were to move the condition to a function that returns a boolean, you could generalize this:

def f(x):
    return x == 2

if not any(f(k) for k in a):
    print 'no match'

Sure. Just put it before the break .

a = [1, 2, 3]
for k in a:
    if k == 2:
        print("found")    # HERE
        break
else:
    print("no match")

Why not simply:

a = [1, 2, 3]
for k in a:
    if k == 2:
        print("match")
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM