【问题标题】:Averaging function isn't averaging instead it's resetting平均功能不是平均,而是重置
【发布时间】:2015-05-03 16:44:15
【问题描述】:

我正在尝试利用 TeamTreehouse 学习订阅和这本从编程逻辑和设计开始这本书来尝试学习编程和 python。

目标:结合第 12 行中通过引用传递接收到的输入,然后将传入的每个后续输入添加到 testScoreAverage 以及之前的值。相反,它只是保留一个值而不是运行总计。

我添加了 cmets,逐行指示我的错误/对代码的理解

我真的认为我通过将变量设置为数据类型 int 以某种方式将变量设置为 0,但我不明白这是怎么回事,因为我过去能够做到这一点?

#///////////////Defining Variables/////////////
testScore1=0
testScore2=0
testScore3=0
testScore4=0
testScore5=0
tests=5
testScoreAverage=0
#///////////////Defining Variables/////////////

#///////////////calcAverage Function/////////////

#L2g2h: defines function & receives current testScore int value
def calcAverage(testScore):

    #L2g2h: initiates variable testScoreAverage as an int value type (but doesn't set it to any value)
    testScoreAverage=int()

    #L2g2h: again initiating a variable, variable testScores, to int value type (but not setting it to any numeric value)
    testScores=int()

    #L2g2h: for loop starting
    for i in range(1, tests + 1):

        #L2g2h: testScores is set equal to the current testScores value PLUS the current value of testScore to become a running total
        testScores=testScores+testScore

        #L2g2h: testScoreAverage is dividing the current testScores value by the current counter variable i's value to come up with an average
        testScoreAverage=testScores/i

    #////NEED TO SET NUMBER TO HOLD ONLY 2 DECIMAL PLACES
    #L2g2h: print out the current testScoreAverage
    print("Your test score average so far is ", float(testScoreAverage))

#///////////////calcAverage Function/////////////

#///////////////determineGrade Function/////////////    
def determineGrade(testScore):
#    for i in range(1, tests + 1):     
    if testScore>=90 and testScore <= 100:
        print("Your test score grade is an A.")
    elif testScore>=80 and testScore <= 89:
        print("Your test score grade is a B.")
    elif testScore>=70 and testScore <= 79:
        print("Your test score grade is a C.")
    elif testScore>=60 and testScore <= 69:
        print("Your test score grade is a D.")
    elif testScore<=60:
        print("Your test score grade is a F.")
    else:
        print("That is invalid.")
#///////////////determineGrade Function/////////////
for i in range(1, tests + 1):
    testScore=int(input("Enter test score #" + str(i)))
    calcAverage(testScore)
    determineGrade(testScore)

【问题讨论】:

  • testScores=int() 确实 将其设置为一个值; int() 返回0。只需写testScores = 0

标签: python function for-loop average python-3.3


【解决方案1】:

您在最后一个 for 循环中的每次迭代中调用函数 calcAverage 一次。您应该仅在用户输入所有得分值后计算平均值。

首先将您的值附加到列表中,然后在用户输入所有值后,计算平均值:

#///////////////Defining Variables/////////////
testScore1=0
testScore2=0
testScore3=0
testScore4=0
testScore5=0
tests=5
testScoreAverage=0
#///////////////Defining Variables/////////////

#///////////////calcAverage Function/////////////
def calcAverage(testScore):
    testScoreAverage=int()
    testScoreAverage= sum(testScore)/len(testScore)
#////NEED TO SET NUMBER TO HOLD ONLY 2 DECIMAL PLACES
    print("Your test score average so far is ", float(testScoreAverage))
    return testScoreAverage
#///////////////calcAverage Function/////////////

#///////////////determineGrade Function/////////////    
def determineGrade(testScore):
#    for i in range(1, tests + 1):     
    if testScore>=90 and testScore <= 100:
        print("Your test score grade is an A.")
    elif testScore>=80 and testScore <= 89:
        print("Your test score grade is a B.")
    elif testScore>=70 and testScore <= 79:
        print("Your test score grade is a C.")
    elif testScore>=60 and testScore <= 69:
        print("Your test score grade is a D.")
    elif testScore<=60:
        print("Your test score grade is a F.")
    else:
        print("That is invalid.")
#///////////////determineGrade Function/////////////

scores =[]
for i in range(1, tests + 1):
    scores.append(int(input("Enter test score #" + str(i)+" ")))

average = calcAverage(scores)
determineGrade(average)

请注意,要计算列表中的平均值,您可以使用sum 函数将此列表中的所有值相加,然后除以列表长度,使用len(list)

如果您想确定每个分数的等级,您可以遍历包含分数的列表并为每个分数确定等级,如下所示:

for score in scores: #scores is the list
    determineGrade(score)

【讨论】:

  • 哇,非常感谢拉斐尔。到目前为止,我的学习课程中还没有使用/被介绍过列表 - 我如何将我的列表项通过 determineGrade 函数来获取每个 5 个人的成绩?
  • 为了得到每个分数的分数,做一个 for 循环并对每个分数进行测试。我将编辑帖子以向您展示如何
【解决方案2】:

正确,重新初始化变量将清除以前的值。此外,在 python 中,您并不总是需要初始化或声明变量,请研究何时何地进行。

下面的代码使用list 来存储每个分数。然后calcAverage() 可以一次对整个列表进行平均。所以在任何时候你都可以得到当前的平均值。

还要注意局部变量和全局变量,最好只在函数中使用局部变量,清楚地传入必要的参数并返回特定值。变量的名称略有更改,以举例说明本地(函数)与全局(脚本)范围的差异。

作为建议,determineGrade() 应该只返回字母等级,print 语句应该在脚本级别。这允许重用该功能。例如,获取单项测试的成绩和平均分(见代码)。

#### ///////////////Defining Variables/////////////
tests = 5
testScores = []

#///////////////calcAverage Function/////////////
def calcAverage(scores):
    return float(sum(scores))/float(len(scores))

#///////////////determineGrade Function/////////////    
def determineGrade(score):
    #python allows inequality range comparisons!
    if score >= 90:
        return "A"
    elif 80 <= score <= 89:
        return "B"
    elif 70 <= score <= 79:
        return "C"
    elif 60 <= score <= 69:
        return "D"
    elif score < 60:
        return "F"
    else:
        return "invalid"

#///////////////main script/////////////
for i in range(1, tests + 1):
    testScore = int(input("Enter test score #" + str(i) + ' '))
    testGrade = determineGrade(testScore)

    testScores.append(testScore)

    testScoreAverage = calcAverage(testScores)
    testGradeAverage = determineGrade(testScoreAverage)

    print("Your test grade is " + str(testGrade))
    print("Your test score average so far is " + str(testScoreAverage))
    print("Your test grade average so far is " + str(testGradeAverage))
    print # just to make the output nicer

输出

Enter test score #1 100
Your test grade is A
Your test score average so far is 100.0
Your test grade average so far is A

Enter test score #2 50
Your test grade is F
Your test score average so far is 75.0
Your test grade average so far is C

Enter test score #3 89
Your test grade is B
Your test score average so far is 79.6666666667
Your test grade average so far is invalid

Enter test score #4 90
Your test grade is A
Your test score average so far is 82.25
Your test grade average so far is B

Enter test score #5 45
Your test grade is F
Your test score average so far is 74.8
Your test grade average so far is C

继续学习python!这是一门很棒、简洁且功能强大的语言!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2020-09-20
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多