在Python中求和所有范围变量?

2024-10-04 11:24:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个Python初学者,一件事都做不好。 看,我们的老师让我们做一个函数来计算所有考试成绩的平均分,考试的次数不确定。它必须是python2.7。在

def main():
    print("This program computes the average of multiple exam scores.")

scoresno = input("Enter number of exam scores: ")
for scores in range(scoresno):
    scores = input("Enter exam score: ")

average = scores/(scoresno + 0.0)

print "Exam score average is:", (average)
main()

这显然行不通,我怎么能让它发挥作用呢?在


Tags: of函数inputmain老师scoreprintaverage
3条回答

您可以直接将分数相加,循环:

total = 0.0
for i in range(scoresno):
    total += input("Enter exam score: ")

average = total/scoresno

另一种方法是使用列表并将每个新值附加到列表中,然后对批次求和:

^{pr2}$

首先,小心你的压痕!Python对代码索引有严格的规则。在

第二,为什么要逐级平均?一个更好的做法是同时获取所有输入,然后除以输入量。在

以下是更正的代码:

def main():
    print("This program computes the average of multiple exam scores.")
    scoresno = input("Enter number of exam scores: ")
    scoreslist = list() #Create a list of scores to be stored for evaluation
    for scores in range(scoresno):
        scoreslist.append(input("Enter exam score: ")) #Get the score and immediately store on the list
    average = float(sum(scoreslist)) / len(scoreslist)
    print "Exam score average is:", (average)

if __name__=='__main__': #Run this code only if this script is the main one
    main()

sum(iterable)对数字数组的所有元素求和并返回结果。想知道为什么要把演员选成float?如果不进行强制转换,我们可能会对整数进行除法,从而得到一个整数结果(我想您希望得到类似7.25)的结果,因此如果其中任何一个数字应该是float(有关更多信息,请参见here)。在

在第一个for循环中,每次迭代都要重写变量scores。相反,您应该在循环之前创建一个变量来跟踪合并的分数,然后在每次迭代中添加当前分数。例如:

total = 0.0
for scores in range(scoresno):
     score = input("Enter exam score: ")
     total += score

相关问题 更多 >