我是一个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()
这显然行不通,我怎么能让它发挥作用呢?在
您可以直接将分数相加,循环:
另一种方法是使用列表并将每个新值附加到列表中,然后对批次求和:
^{pr2}$首先,小心你的压痕!Python对代码索引有严格的规则。在
第二,为什么要逐级平均?一个更好的做法是同时获取所有输入,然后除以输入量。在
以下是更正的代码:
sum(iterable)
对数字数组的所有元素求和并返回结果。想知道为什么要把演员选成float
?如果不进行强制转换,我们可能会对整数进行除法,从而得到一个整数结果(我想您希望得到类似7.25
)的结果,因此如果其中任何一个数字应该是float(有关更多信息,请参见here)。在在第一个
for
循环中,每次迭代都要重写变量scores
。相反,您应该在循环之前创建一个变量来跟踪合并的分数,然后在每次迭代中添加当前分数。例如:相关问题 更多 >
编程相关推荐