我正在尝试修改我构建的考试平均计算器,以便在结束while循环后计算总体平均值(示例下所需的输出代码)。我有功能代码,目前计算个别学生的平均值,但我无法找到计算整体平均值的方法。当前代码错误说出:TypeError:'float'对象不可迭代
numExams = int(input("How many exam grades does each student have? "))
students = 0
total = 0
moreGrades = "Y"
while moreGrades == "Y" :
print("Enter the exam grades: ")
total = 0
for i in range(1, numExams + 1) :
score = int(input("Exam %d: " % i))
total = total + score
average = total / numExams
print("The average is %.2f" % average)
moreGrades = input("Enter exam grades for another student? (Y/N)")
moreGrades = moreGrades.upper()
students = students + 1
total = sum(average)
print("The overall average is: ", total/students)
示例所需输出:
How many exam grades does each student have? (2)
Enter the exam grades.
Exam 1: (40)
Exam 2: (40)
The average is 40.00
Enter exam grades for another student? (Y/N) Y
Enter the exam grades
Exam 1: 20
Exam 2: 60
The average is 40.00
Enter exam grades for another student? (Y/N) n
The overall average is 40.00
答案 0 :(得分:1)
这是因为你正在尝试
total = sum(average)
您可以将average
循环之外的while
定义为
average = []
所以它是一个列表,您可以将while
循环中的每个平均值附加到此列表中。请参阅sum
。
答案 1 :(得分:0)
您试图总结一个浮点数,这是不可能的:
>>> sum(40.00)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
sum(40.00)
TypeError: 'float' object is not iterable
您的代码也有一些缩进错误,这是您的代码的工作版本:
numExams = int(input("How many exam grades does each student have? "))
students = 0
total = 0
moreGrades = "Y"
average = [] # set average to an empty list
while moreGrades == "Y" :
print("Enter the exam grades: ")
total = 0
for i in range(1, numExams + 1) : # you have indentation error here
score = int(input("Exam %d: " % i))
total = total + score
average.append(total / numExams)
print("The average is %.2f" % average[-1])
moreGrades = input("Enter exam grades for another student? (Y/N)")
moreGrades = moreGrades.upper()
students = students + 1
total = sum(average)
print("The overall average is: ", total/students)
代码输出:
How many exam grades does each student have? 2
Enter the exam grades:
Exam 1: 40
Exam 2: 40
The average is 40.00
Enter exam grades for another student? (Y/N)Y
Enter the exam grades:
Exam 1: 20
Exam 2: 60
The average is 40.00
Enter exam grades for another student? (Y/N)N
The overall average is: 40.0