How can I ensure I’m printing everything properly?
Answer
In this last exercise, Review, we are not creating any new functionality in our program. We’re simply calling all of the functions we’ve built to this point so we can see the output!
When using print_grades(), pass it the grades list, and there’s no need to write print before it because that’s what the function does inside already.
From the previous lessons, you should already have the variance and standard deviation printed out, so all that’s left is printing the sum and average by using the corresponding functions.
If you didn’t yet, be sure to define variance outside of any functions and set it to grades_variance(grades). Having that variable allows us to pass it to our grades_std_deviation() function.
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades_input):
for grade in grades_input:
print grade,
def grades_sum(scores):
total = 0
for score in scores:
total += score
return total
def grades_average(grades_input):
sum_of_grades = grades_sum(grades_input)
average = sum_of_grades / float(len(grades_input))
return average
def grades_variance(scores):
average = grades_average(scores)
variance = 0
for score in scores:
variance += (average-score) ** 2
total_variance = variance/float(len(scores))
return total_variance
def grades_std_deviation(variance):
return variance ** 0.5
variance = grades_variance(grades)
print_grades(grades)
print
print "The sum of grades is %d" % grades_sum(grades)
print
print "The average of grades is %d" % grades_average(grades)
print
print "The variance of grades is %d" % grades_variance(grades)
print
print "The standard deviation of grades is %d" % grades_std_deviation(variance)
It says ‘sum of grades was not printed’ even though it was. What am I doing wrong?
It is not that Codecademy not using modern syntax. It is purely because the course in question was built on Python 2. For modern syntax please check out the new Python 3 course.
I am getting ‘none’ in the output window while printing grades, is this expected or I am doing something wrong here.
Please help me with this.
Output Screen:
Please
The function print_grades() prints a column of grades as it executes, but it has no return statement. In Python, very function lacking a return statement returns the value None.
So, when you call
print “Grades:”,print_grades(grades)
… the print statement prints what it sees, from left to right. First, it prints the string, “Grades”
Next, it comes to the function, print_grades(), so it must execute that function, and print the returned value.
During execution, a column of grades is printed, as we have seen.
But the function returns None, which is exactly what the print statement prints.
Remember, in Python, we print what we want to see on the screen
… but we return what Python needs to use, be it to assign to a variable, pass to a function, or place within a print statement.