pythonfunctionloopsbreakcontinue

break and continue in function


def funcA(i):
   if i%3==0:
      print "Oh! No!",
      print i
      break

for i in range(100):
   funcA(i)
   print "Pass",
   print i

I know script above won't work. So, how can I write if I need put a function with break or continue into a loop?


Solution

  • A function cannot cause a break or continue in the code from which it is called. The break/continue has to appear literally inside the loop. Your options are:

    1. return a value from funcA and use it to decide whether to break
    2. raise an exception in funcA and catch it in the calling code (or somewhere higher up the call chain)
    3. write a generator that encapsulates the break logic and iterate over that instead over the range

    By #3 I mean something like this:

    def gen(base):
        for item in base:
            if item%3 == 0:
               break
            yield i
    
    for i in gen(range(1, 100)):
        print "Pass," i
    

    This allows you to put the break with the condition by grouping them into a generator based on the "base" iterator (in this case a range). You then iterate over this generator instead of over the range itself and you get the breaking behavior.