Iterating over a list in a function


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]

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)


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.


Thank you! I know how to fix it now!


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


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.


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