Search code examples
pythonfor-loopnested-for-loop

How to "double pop"?


I'm sorry if my title is a bit unclear, I wasn't sure how to express my problem better. I will give a quick code snippet to illustrate what I am trying to do:

for data_file in data_files:
    analyze(data_file)

def analyze(data_file):
    for _ in np.arange(n_steps):
        foo(data_file)
    do some other things

def foo(data_file):
    do some things
    if (value > 1): 
        do some things
        double_return()
    else:
        continue doing other things

What I want the function double_return() to do then, is to return back to the larger loop:

for data_file in data_files:

(Instead of return, which would continue to the next step in for _ in n_steps). However, I am not sure what command to use here and haven't been able to find it.


Solution

  • foo() could return True, if it completes, or False if you want to “leave early”:

    for data_file in data_files:
       analyze(data_file)
    
    def analyze(data_file):
       for _ in np.arange(n_steps):
           if not foo(data_file):
              return
       do some other things
    
    def foo(data_file):
       do some things
       if (value > 1):
           do some things
           return False
       else:
           continue doing other things
    
       return True
    

    Edit:
    To make the meaning clearer, you could define foo_completed=True, and foo_not_completed=False, and use these constants instead of True/False.