15. Iterating over a list in a function


#1

These are the instructions: Create a function that returns the sum of a list of numbers.
Here is my code:

n = [3, 5, 7]

def total(numbers):
    result = 0
    for item in n:
        result = result + 1
    return result

I don't know what I'm missing.
My error message reads:
Oops, try again. total([0, 3, 6]) returned 3 instead of 9


#2

Hi @loved123

The goal of this program is to determine the sum of a list of numbers, the list in this case being n.

You need to iterate through the n list and each time, add to result the value of, in your program, item. Your program is fundamentally correct, except you are adding 1 to the result instead of the value of item.

result = result+item

Good luck.


#3

instruction:

Create a function that returns the sum of a list of numbers.

Error:

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

suppose you passed the list that is [0, 3, 6] so the sum of this should be 0+3+6=9
but it was 3

why so?
you took a parameter named numbers but did you used it inside function?

problems come from this line

result = result + 1

what are you doing here?what do you have to do?


#4

Thanks for helping guys. I'm going to come back to this with fresh eyes. Thanks for your help.


#5

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