2

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?

8
  • 2
    You can have interrupt throw an exception of some kind and catch it in your for loop, breaking, or doing whatever you please after excepting it. Commented Sep 9, 2019 at 20:59
  • 1
    @CeliusStingher, break and continue do different things. Commented Sep 9, 2019 at 20:59
  • 2
    @CeliusStingher And neither one can cross function-call boundaries; they only apply to the innermost loop they appear in lexically. Commented Sep 9, 2019 at 21:00
  • 2
    break exits the loop; continue skips the rest of the body and gets the next value from the iterator. Commented Sep 9, 2019 at 21:01
  • 2
    No, Python does not offer any kind of macro expansion. Such constructs usually cause more problems than they solve. Commented Sep 9, 2019 at 21:09

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.