15/18 Iterating over a list in a function


#1

Hi,

I have searched through all the other results and can’t find a solution for this apart from using a range.

I dont understand why it isnt looping through all values of x in numbers and adding them to the result.

n = [3, 5, 7]

def total(numbers):
  result = 0
  for x in numbers:
    result += x
    return result
  
print total(n)


Error message i recieved: total([0, 3, 6]) returned 0 instead of 9

#2

by default, at the end of the function a function returns none

if we want to return something else at the end of the function, we can use the return keyword. Thus, when the return keyword is reached, the function ends

so your function ends in the first iteration of the loop (given the return keyword is reached, which ends the function)


#3

A post was split to a new topic: 15/18 iterating over a list in a function


#4

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