Search code examples
pythonloopsreturn

Where to use the return statement with a loop?


Sometimes I get confused as to where to use the return statement. I get what it does, it's just that I don't get its placement properly.

Here's a short example of the same code.

Correct way:

def product_list(list_of_numbers):
    c = 1
    for e in list_of_numbers:
        c = c * e
    return c

Wrong way (which I did initially):

def product_list(list_of_numbers):
    c = 1
    for e in list_of_numbers:
        c = c * e
        return c

Can someone clarify what's the difference between the two and where should the return be when using a loop in a function?


Solution

  • return in a function means you are leaving the function immediately and returning to the place where you call it. So you should use return when you are 100% certain that you wanna exit the function immediately.

    In your example, I think you don't want to exit the function until you get the final value of c, so you should place the return outside of the loop.