Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return value from function which calls itself

I have some function which calls itself:

def rep_func(parent_id, account_id):
    ...

    for page in iterator:
        for item in page['Children']:
            if id == item['Id']:
                //return parent_id
                
    for page in org_iterator:
        for ou in page['Children']:
            rep_func(ou['Id'], account_id)

I need to return the parent_id from the function when the if is succesfull. How can I do this? Do I need a break?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to return the value; this automatically breaks the current loop.

For the recursive case, I’m guessing you want to check whether any value was found, and return it conditionally, so that the loop will keep searching if the recursive call was unsuccessful:

def rep_func(parent_id, account_id):
    # ...

    for page in iterator:
        for item in page['Children']:
            if id == item['Id']:
                return parent_id
                
    for page in org_iterator:
        for ou in page['Children']:
            if result := rep_func(ou['Id'], account_id):
                return result

    # we implicitly return None if no match found
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading