how to exit from a nested loop in python

rurpy at yahoo.com rurpy at yahoo.com
Fri Feb 8 11:15:17 EST 2019


On Thursday, February 7, 2019 at 11:45:23 PM UTC-7, Kaka wrote:
> for i  in range(len(A.hp)):
> 
>         for j in range(len(run_parameters.bits_Mod)):
>          req_slots[j] = math.ceil((A.T[i])
> 
>          for g in Temp[i]["Available_ranges"][j]:
>           for s in range(g[0], g[-1]):
>               if (s+req_slots[j]-1) <= g[-1]:
>                  if (Temp[i]['cost'][j] <= (run_parameters.PSD):  ------ When this condition is true i want to break the nested loop and start from the begining
>                    served_count +=1
>                    A.T[i]["First_index"]= s
>                    A.T[i]["Last_index"]= s+req_slots[j]-1
>                    A.T[i]["Status"]= 1
>                    A.T[i]["Selected_MOD"] = j
>                    break
> 
> I have this code. When the last "if" condition is satisfied, i want to break all the loops and start the nested loop for next i. else, the loop should continue.  
> 
> can anyone help me?

In addition to the two methods Peter posted there is also
the obvious way of using a flag (but perhaps this is what 
you were trying to avoid?)

  for i in (1,2,3):
      nexti = False
      for g in (1,2,3):
          for s in (1,2,3):
              print (i,g,s)
              if (g,s) == (2,2):
                  nexti = True
                  break
          if nexti: break

You can also use exceptions to do a multi-level break:

  class Next_i (Exception): pass
  for i in (1,2,3):
      try:
          for g in (1,2,3):
              for s in (1,2,3):
                  print (i,g,s)
                  if (g,s) == (2,2):
                      raise Next_i
      except Next_i: continue



More information about the Python-list mailing list