yujuezhao
yujuezhao

Reputation: 1105

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?

Upvotes: 2

Views: 74

Answers (3)

Massifox
Massifox

Reputation: 4487

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

Upvotes: 2

Christian Sloper
Christian Sloper

Reputation: 7510

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

Upvotes: 3

chepner
chepner

Reputation: 532238

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.

Upvotes: 3

Related Questions