访问函数中的变量

时间:2013-11-16 05:42:29

标签: python

from math import sqrt
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 / len(grades)
    return average

def grades_variance(scores, average):
    variance = 0
    for i in range(len(scores)):
        variance += (average - scores[i])**2
    return float(variance)/len(scores)

def grades_std_deviation(variance):
    grades_variance(grades,grades_average(grades))
    return sqrt(variance)

print grades
print grades_sum(grades)
print grades_average(grades)
print grades_variance(grades, grades_average(grades))
print grades_std_deviation(grades_variance(grades, grades_average(grades)))

对于最后一个打印部分,有没有办法不必在每个函数中调用该函数?例如,在“print grade_std_deviation”中,我需要将方差和平均函数嵌套在里面。 grade_variance和grades_average函数是否有任何方法可以“返回”在相应函数范围之外可访问的变量?

2 个答案:

答案 0 :(得分:4)

为什么不将结果存储在像这样的变量

avg = grades_average(grades)
var = grades_variance(grades, avg)
dev = grades_std_deviation(var)

print avg, var, dev

答案 1 :(得分:1)

函数返回变量,你只需要存储它们。

print grades

g_sum = grades_sum(grades)
g_avg = grades_average(grades)
g_var = grades_variance(grades, g_avg)
g_dev = grades_std_deviation(g_var)

print g_sum
print g_avg
print g_var
print g_dev