If you have done the Battleship exercise, this one will follow the same structure. We will go step by step, giving solutions in case you get stucked. At the end you can look to the solution file Exam.py
.
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
We are going to make a function to print them.print_grades()
with one argument, a list called grades.print_grades()
with the grades list as the parameter.Solution 1
>>> grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
>>>
>>> def print_grades(grades):
... for grade in grades:
... print grade
...
...
>>> print_grades(grades)
100
100
90
40
80
100
85
70
90
65
90
85
50.5
>>>
grades_sum()
that does the following.grades_sum()
function with the list of grades and print the result.Solution 2
>>> grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
>>>
>>>
>>>
>>> def grades_sum (scores):
... total = sum (scores)
... return total
...
>>>
>>> print grades_sum(grades)
1045.5
>>>
>>>
Note:You can also use a for loop.
Define a function grades_average()
, below the grades_sum() function that does the following:
grades_sum
with gradesgrades_average()
function with the list of grades and print the result.Solution 3
>>> def grades_average(grades):
... tot =grades_sum(grades)
... ave=tot/float(len(grades))
... return ave
...
>>> print grades_average(grades)
80.4230769231
grades_variance()
that accepts one argument, scores, a list.grades_average(scores)
.grades_variance(grades)
.Solution 4
>>> def grades_variance(scores):
... average=grades_average(scores)
... variance=0
... for score in scores:
... add=(average-score)**2
... variance += add
... var_tot=variance/len(scores)
... return var_tot
...
>>> print grades_variance(grades)
334.071005917
The standard deviation is the square root of the variance. You can calculate the square root by raising the number to the one-half power.
grades_std_deviation(variance)
.
return the result of variance ** 0.5grades_variance(grades)
.grades_std_deviation(variance)
.Solution 5
>>> def grades_std_deviation(variance):
... return variance**0.5
...
>>> variance=grades_variance(grades)
334.071005917
>>> print grades_std_deviation(variance)
18.2776094147