简体   繁体   中英

how can I use a function to exit for loop

I want to write a function to exit a for loop. Typically, we can

for i in range(10):
    if i==8:
       break

I hope to write a function like,

def interrupt(i):
   if i == val:
      ...


for i in range(10):
   interrupt(i)

Edit

I understand the mechanism and why I can't do this now. Just out of curiosity, does python offer something like 'macro expansion', so that I don't actually create a function, but a name to repalce the code block?

You can't. The for loop continues until an explicit break statement is encountered directly in the loop, or until the iterator raises StopIteration .

The best you can do is examine the return value of interrupt or catch an exception raised by interrupt , and use that information to use break or not.

I don't think it is possible to throw a break, you can fake it a bit like this for example:

def interrupt(i):
    if i > 2:
        return True
    return False

for i in range(10):
    if interrupt(i):
        break

    #.. do loop stuff

The following code will solve your problem:

def interrupt(i, pred=lambda x:x==8):
    if pred(i):
        raise StopIteration(i)

try:
    for i in range(10):
        interrupt(i)
except StopIteration as e:
    print('Exit for loop with i=%s' % e)

# output: Exit for loop with i=8

The scheme is simple, and works in general with any kind of exception:

  1. Write a function foo() that raises one or more exceptions when one or more events occur
  2. Insert the call to the function foo() in the try-except construct
  3. Manage exceptions in except blocks

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