The sum of scores


#1



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

got stuck in this plz pprovide me correct code plz


#2

a function ends the moment a return keyword is reached (even when the return keyword is reached in the loop)

so, your function ends in the first iteration of your loop, is the desired behavior of your program?


#3

no i want sum of all


#4

good :slight_smile: And how do you think we can achieve this? Given return ends the function (and breaks the loop in order for the function to end)


#5

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grades_sum(x):
total=0
for i in range(0,len(x)):
total=total+i
print total
return total
what i've to replace now, i'd taken return out of thr loop??


#6

your loop, using range() will give you indexes of the list, not values

so either don't use range, then you can add the values directly to total or use range, but then you have to use i as index to retrieve the values of the list before adding them to total


#7

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

Oops, try again. Your grades_sum function threw the following error: 'int' object has no attribute 'getitem' for grades_sum([18, 88, 9, 14, 98, 86, 83])


#8

you had to choice, you decide to get rid of range i contains the values from the list and you can add them directly to total (no need for accessing list by index), that is only necessary when you decided to keep range.

i gave you both options, you just have to decide which approach you see as best fit


#9

hey, answer is coming 1045.5 is it correct
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grades_sum(x):
total=0
for i in x:
total=total+i
print total
return total
grades_sum(grades)


#10

sounds about right, does it work?


#11

yes ..it is 1045.5..is it correct..???
and also plz tell what i was doing wrong in that i[x]..??


#12

i is the index, and x is the list, the syntax for accessing a list by index is your_list[index], but this only works when you use range(), given range gives you indexes, otherwise you get the values from the list directly (which might be higher then the indexes, so throwing an index error)


#13

thank u very much big brother...:grinning: so good of u


#14