List and Functions - 15. Iterating over a list in a function


#1

May i know why is it that when the return command has the same indention level as the result += numbers[i] line, the interpreter prints out “1”, rather than 15?

When the indent is one tab lesser than that of result += numbers[i] line, the interpreter prints out “15”.

WRONG CODE :

n = [3, 5, 7]

def total(numbers):
  result = 0
  for i in range(len(numbers)):
    result += numbers[i]
    return result
  
print total(n)

CORRECT CODE:

n = [3, 5, 7]

def total(numbers):
  result = 0
  for i in range(len(numbers)):
    result += numbers[i]
  return result
  
print total(n)

#2

The return line is inside the code block of the loop so returns on the firrst iteration, never completing the full loop.