return statement in for loops

Your problem is, precisely, that you’re putting the return statement inside the for-loop. The for-loop runs each statement in it for however so many times.. if one of your statements is a return, then the function will return when it hits it. This makes sense in, for example, the following case:

def get_index(needle, haystack):
    for x in range(len(haystack)):
        if haystack[x] == needle:
            return x

Here, the function iterates until it finds where the needle is in the haystack, and then returns that index (though there’s a builtin function to do this, anyways, list.index()).

If you want the function to run for however many times you tell it to, you have to put the return AFTER the for-loop, not inside it. That way, the function will return after the control gets off the loop

def add(numbers):
    ret = 0
    for x in numbers:
        ret = ret + x
    return ret

(though again, there’s a builtin function to do this as well, sum())

Leave a Comment