Iterating over a list in a function


#1



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


The system says incorrect even though the display on the top right corner says none.


n = [3, 5, 7]

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


#2

a function ends the moment a return keyword is reached, this currently happens in the first iteration of your loop, change the indent of return so the whole loop can run


#3

You saying I should make the last 'return' statement on the same vertical line with the 'for' statement above?


#4

yes


#5

I don't really think that's the case, as it still returns to be incorrect.
Here's the direct screen shot.


Review: Functions
#6

number contains the indexes thanks to range. so then you can use number to access the items in the numbers list.


#7

So you are saying that I should change ... ?


#8

well here:

result=result+number

number are the indexes of numbers list, so you need to get values from the list like you did on line 6


#9

I changed it to : result=result+numbers
But the system returns:
Oops, try again.
total([0, 3, 6]) resulted in an error: unsupported operand type(s) for +: 'int' and 'list'


#10

numbers[number] uses the indexes to get the values from the list, you do it on the line above, why can't you see you need it now?


#11

So I should get the value from the example list on line 1?
I'm sorry I'm still not understanding what exactly is it that I should change.


#12

you have a list. You want to have the total of this list. so you loop over the list, but you use range() which will give you indexes, so you need to add numbers[number] to total since number are the indexes of numbers list


#13

result=result+numbers[number]

Add this to here?


#14

yes


#15

did you slove your problem?


#16

not really, there is still a problem with my code. You can see the screenshot I posted before.


#17

can you please post your update code?


#18

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

It returns :

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

#19

can you please post properly so we can understand :slight_smile:

like after posting select whole code and just click on above </>


#20

guess this should be better