# Iterating over a list in a function

#1

Iterating over a list in a function

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

This is the message showed when I submit the code.

I am not get it. Why the number = n = [3, 5, 7] will become [0, 3, 6].

is it a bug?

This is the code I used, which will print
[3, 5, 7]
3
8
15
15
None

``````n = [3, 5, 7]

def total(numbers):

print numbers

result = 0

for i in range(len(n)):

#print i

result += n[i]

#print n[i]

print result

return result

print total(n)``````

#2

Your functions parameter is `numbers`, It represents any general list (local scope)
But inside the function you introduced global list variable `n`
so when CC checks it for different list inputs,It throws an error.

#3

Thank you! I know how to fix it now!

#4

is there any way to use append.() in this exercise to add each number to result?

#5

Using append method will not be effective here.
There is inbuilt function on list data structure called `sum()`.

So we can use it instead of loop and all.

#6

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