查找CSV文件中三个数字的平均值

时间:2016-03-29 08:55:30

标签: python function csv math average

我已经创建了一段编码但是我已经开始尝试找到每个人的平均得分,但不知道还能做什么。代码不起作用:

def average():#makes function 'average'
print ("\nThe Average Score")#outputs the title 'The Average Score'
for pupils in classScore:
    pupil["total"] = (int(pupil["Pupil's Score 1"])+int(pupil["Pupil's Score 2"])+int(pupil["Pupil's Score 3"]))
    pupil["average"] = (pupil["total"]//3)
    print (pupil["Pupil's Name"]+pupil["average"])
average()

CSV文件的布局如下:

Pupil's Name     Pupil's Score 1    Pupil's Score 2       Pupil's Score 3
Joao                  10                 9                       8
Rebecca                7                 6                       5
Snuffles               0                 1                       2

出现的错误消息是:

Traceback (most recent call last):


File "E:/Controlled Assesment Computing/Controlled Assesment/Task 3/Try 18.py", line 56, in <module>
    average()
File "E:/Controlled Assesment Computing/Controlled Assesment/Task 3/Try 18.py", line 53, in average
    print (pupil["Pupil's Name"]+pupil["average"])
TypeError: Can't convert 'int' object to str implicitly

如果有人能提供帮助,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

信息看起来很清楚:

TypeError: Can't convert 'int' object to str implicitly

您必须执行操作才能将数字转换为字符串。试试这个:

print(pupil["Pupil's Name"]+str(pupil["average"]))

通过将此方法限制为三名学生,您已经完成了自己的伤害。您可以轻松地让它适用于任何数量的学生。

我建议不要使用这种平均方法进行打印。一种方法应该做好一件事。