Q: break multiple loop

Steve Purcell stephen_purcell at yahoo.com
Sat Feb 17 11:42:54 EST 2001


hwan-jo yu wrote:
> It seems that there is now "goto" statement in the python.

True!

> How can we terminate multiple for or while loop ?

If you need to jump right out of nested loops, this is usually a sign that
there is an easier way to arrange your loop: maybe the inner loop should be
a separate function or method? But if you insist use a flag variable:

   keepgoing = 1
   while loop_condition1 and keepgoing:
      while loop_condition2:
         if we_should_stop_now():
             keepgoing = 0
             break

or

   keepgoing = 1
   while loop_condition1:
      while loop_condition2:
         if we_should_stop_now():
             keepgoing = 0
             break
      if not keepgoing: break

Another trick is with an exception:

   try:
       while loop_condition1:
           while loop_condition_2:
               if we_should_stop_now():
                    raise "stopped"
   except "stopped":
       pass

But forget I said that -- it's nasty.

-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Get servlets at http://pyserv.sourceforge.net/
"Even snakes are afraid of snakes." -- Steven Wright




More information about the Python-list mailing list