4. The sum of scores


#1

Please explain why this text does not pass?

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def grades_sum(grades):
    total = 0
    for i in grades:
        total = total + i
    print total

But this does?

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def grades_sum(grades):
    total = 0
    for i in grades:
        total = total + i
    return total
print grades_sum(grades)

#2

In the first one you don't call the function... ie you forget to put grades_sum(grades) after the function


#3

Instead of "calling" the function I simply print the total instead of return total then print & call function


#4

I don't understand...


#5

There are no problem with your code but just for passing with rule of this site , we should print

print grades_sum(grades)

It's not a problem but we should for passing this exercise


#6

Your two codes are pretty different even though they don't seem like it.

The first code ends by just printing the total sum. Nothing is returned back. while we see the answer, nothing was returned back to the program. while this may seem like splitting hairs, it is very important. Had you wanted to assign that value to another variable, the first code would fail as it doesn't return a value.

The second code does indeed return the total. By calling grades_sum(grades) you initialized the function and it returned "total". you just happened to print out that value.

If we wanted to define a new variable called "total_sum" we can really see how they are different.

eg total_sum=grades_sum(grades)

The first code would never assign a value to total_sum as that function terminates without ever returning a value. You would just have the value printed to the terminal (something that is not very useful in high level coding).

the second code would run and nothing would print to the terminal, but total_sum would be assigned the proper value as the function did indeed return said value.


#7

Thank you Austink26. That description is very helpful. Understanding the transition from solving "problems" in this course is different than creating solutions in real life.


#8

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