Iterating over a list in a function


#1



https://www.codecademy.com/courses/python-beginner-nzzVa/3/4?curriculum_id=4f89dab3d788890003000096


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


I figured that this would work. I am not sure what is wrong with my code.


Replace this line with your code. 
n = [3, 5, 7]

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


#2

Be sure the return statement is not inside the loop block.


#4

That didn't help. Same problem, return outside loop.


#5

Now it's returning 5, not 10.


#6

Now it's back to returning 3.
Code:

n = [3, 5, 7]

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

#7

        result += numbers[i]

Remember, when we iterate a range, the value for i is a counting number (index), not an element value.


#8

Solved.
:sunglasses:


#9

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