What did I do wrong? (Iterating over a list in a function)


#1


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

total([0, 3, 6]) resulted in an error: local variable 'result' referenced before assignment


I expect the program to add up all the elements of an arbitrary list and returns that count.


n = [3, 5, 7]

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


#2

result is undefined, before the loop create a variable named result and give it a value of zero


#3

Tried it:

n = [3, 5, 7]

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

didn't work!


#4

here:

print numbers[i]
result = result + result[i]

numbers[i] will get you values from the list, which is very good, But this you should add tot total, but then in total for some unknown reason you decide to use result[i], which doesn't make much sense


#5

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