Iterating over the list will return the item in the list, not the index of the item. The correct code you wrote will look like this:
def grades_sum(grades): total = 0 for grade in grades: total += grade return total
Of course, like the others answered, this can be done much more elegantly using sum .
If you really need an index for something else, you can use enumerate as follows:
def grades_sum(grades): total = 0 for i, grade in enumerate(grades): total += grade
Or, if you do not care at all about receiving the item
def grades_sum(grades): total = 0 for i in range(len(grades)): total += grades[i] return total
Michael mauderer
source share