0

I have a below python code:

def get_sess(sheet, i):
    first_time = True
    old_eid = " "
    old_sess = " "
    k = dict()
    p = []
    for i in range(i, 2712):  # (pt1)
        eid = str(sheet.cell_value(i, 2)).zfill(3)
        if first_time:
            old_eid = eid
            first_time = False
        if old_eid == eid:
            old_sess = str(sheet.cell_value(i, 21)).zfill(3)
            if d:
                for z in range(len(d)):  # (pt2)
                    if d[z]['sess_name'] == old_sess:
                        # This means this sess data is already saved in list, so ignore
                        continue
            new_sess = old_sess
            weight = sheet.cell_value(i, 14)
            product = str(sheet.cell_value(i, 5)).zfill(3)

            k['sess_name'] = old_sess
            k['weight'] = weight

            t = 0
            while new_sess == old_sess:
                product = str(sheet.cell_value(i + t, 5)).zfill(3)
                p.append(product)
                t = t + 1
                new_sess = str(sheet.cell_value(i + t, 21)).zfill(3)
            k['product'] = p
            d.append(k)

In the above function, I have two for loop at pt1 and pt2. In second for loop, I have a if condition where I am checking if the old_sess is same as sess stored in list, if yes I need to skip all the code after it and want to reach my code back again at first for loop. But if I use continue or break in the if condition, it will only break the second for loop and will execute the rest of the code which is what I dont want.

Is there any way we can directly jump to first for loop if if condition becomes true.

Thanks

S Andrew
  • 5,592
  • 27
  • 115
  • 237
  • 2
    [This question](https://stackoverflow.com/questions/438844/is-there-a-label-goto-in-python) seems like a duplicate. In addition, extracting the double loop in a function and using `return` as a multiple `break` works, and is Pythonic. EDIT: Jason Baker's answer mentions is explicitly, I seem to have skipped it when I skimmed the question first. – Amadan Dec 18 '19 at 11:09
  • What are you even iterating the second loop? `z` is not referenced at all inside of the second for-block. – James Dec 18 '19 at 11:13
  • 1
    I would argue the duplicate target given isn't the best one, this would be much better https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops – WhatsThePoint Dec 18 '19 at 11:13
  • +1 for the `return` solution. It is always possible to structure your code so that a `return` enables multiloop break. And it's clearly more Pythonic than the boolean alternative – sciroccorics Dec 18 '19 at 11:14

1 Answers1

1

Start using a boolean variable say 'flag' and keep a conditional check in the first for loop.

Whenever the value of old_Sess equals sess, you can set flag to 'true' and break the 2nd loop. Upon resuming the code flow in 1st loop, the condition checking flag will break the first loop