[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

how to exit from a nested loop in python

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

Thou shalt indent four spaces. One shalt thou not indent excepting that thou 
then proceed to four.
> 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?

Option 1: Collaps your inner loops into a generator:

    for b in ...:
        for c in ...:
            yield a, b, c

for a in ...:
    for b, c in gen(a):
        if f(a, b, c):

Option 2: If your code is too messy for option 1, use a helper function:

def process(a):
    for b in ...:
        for c in ...:
            if f(a, b, c):

for a in ...: