Iterating over a list in a function


#1

I don't understand why I get the following error message:

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

This is my code :

n = [3, 5, 7]

def total(numbers):
    result = 0
    for number in range(len(numbers)):
        result = result + number
        return result

Can someone help me?


#2

using range() will give you indexes which you can use to retrieve values from your list (or don't use range() at all to get values directly from your list)

a function ends the moment a return keyword is reached, if a return keyword is reached in a loop, the loop breaks so the function can end

In other words, your function ends in the first iteration


#3

I am not sure that I understand what you say.

Does it mean that I should write

result = result + number[numbers]

instead of

result = result + number

Is that right?


#4

no, number contains your indexes (thanks to range()) and numbers is your list. so it should be the other way around


#5

the other way around?

I have just tried

result = result + numbers[number]

and I get the same error message as before

What do you mean with "the other way around"?


#6

this is right:

result = result + numbers[number]

but that was only 50% of my original answer:

if you need more help, post a full updated version of your code


#7

Ok this is the updated version of my code:

n = [3, 5, 7]

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

So the function ends in the first iteration. But I use the sample of the method 2 and I was thinking that range will work to the end by default.

I don't understand...


#8

you placed the return inside the loop, a return keyword means the function ends. Because the function needs to end, python will break the loop


#9

Ok I understand now!

The problem was that I have not well indented return result.

Thank you very much!!!


#10

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