How to break out of two nested for loops?

Tom Jenkins tjenkins at devis.com
Mon Jan 21 16:55:23 EST 2002


On Mon, 2002-01-21 at 16:40, Francois Petitjean wrote:
> 
> In Interpreter.py :
> import Command   # another module
> ...
> class Interpreter:
> ...
>     def interpret(self,lines):
>         """decode statement lines (list of strings) and run associated
> action"""
>         if lines[-1] == '':  del lines[-1]
>         line = '\n'.join(lines)
>         ret = None
>         for module in self.lModules:
>             for cde in module.lcdes:
>                 ret = cde.match(line)
>                 if ret:
>                     break   # break 2 ??
>             if ret:                #  or  else: continue   and a break
>                 break
>         else:
>             print "No command found to match '%s'\n" % (line,)
>             return
>         cde,m = ret   # line matches cde with parameters m
<snip>

well an easy way to break out of n loops is using an exception.

class BreakLoop(Exception) : pass

def interpret(self, lines):
   ...
   try:
     for module in self.lModules:
        for cde in module.lcdes:
           ret = cde.match(line):
           if ret:
              raise BreakLoop
     else:
        print "No command found to match ...
        return
  except BreakLoop:
     pass
  cde, m = ret
  ...

-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com






More information about the Python-list mailing list