I don’t understand why it won’t be right.

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def grades_sum(grades): sum = 0 for i in grades: sum += grades[i] print(grades_sum(grades)) 

Whats my code and I'm trying to figure out why I get from index tracing.

+7
source share
3 answers

You do not need to do grade[i] because you are already referencing the items in the list - all you have to do is replace it with the plain old i

However, there is already a built-in function for this - sum

 print(sum(grades)) 
+13
source

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 grades[i] return total 

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 
+14
source

for i in grades: iterates over the elements in grades . It does not iterate over indexes.

To fix your code, use i instead of grades[i] .

Do not be afraid to use print . They are great for debugging code.

+6
source

All Articles