记录以grades列表为例,分别定义输出、求和、平均值、方差和标准差函数,并输出相应的值
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
#定义求和函数
def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total
#定义求平均值函数
def grades_average(grades):
sum_of_grades = grades_sum(grades)
average = sum_of_grades / float(len(grades))
return average
#定义求方差函数
def grades_variance(scores):
average=grades_average(scores)
variance=0
for score in scores:
variance+=(average-score)**2
return variance/len(scores)
#定义求标准差函数
def grades_std_deviation(variance):
return variance**0.5variance=grades_variance(grades)
#调用函数分别输出对应的值
print print_grades(grades)
print grades_sum(grades)
print grades_average(grades)
print grades_variance(grades)
print grades_std_deviation(variance)
Python学习_算数运算函数
时间: 2024-11-07 19:09:43