15. Iterating over a list in a function


Oops, try again. total([0, 3, 6]) returned 0 instead of 9

If i remove the indentation on line 7 i know this will work. I figured that out through trial and error. Can someone explain what the difference is by un-indenting 'return'?

n = [3, 5, 7]

def total(numbers):
    result = 0
    for X in numbers:
        result += X
        return result


a function returns None by default at the end, if you want to return something different you can use the return keyword to return something different. This does mean the function ends.

So currently, the function ends in the first iteration of the loop. If you unindent, the return keyword is reached after the loop has finished running


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.