Iterating over a list in a function


numbers = [3, 5, 7]

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

print total()

This give me an error of : Oops, try again. total([0, 3, 6]) returned 3 instead of 9


i in this instance will be an integer, acting as an index.

result be no more than the sum of the indexes, not the sum of the items.

To sum up the values at each index,

result += numbers[i]

It is possible to write the assignment the way you have it, but the loop will need to be a value loop (look up) rather than index loop.

for i in numbers:
    result += i

assuming of course that i is a number.


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