I am trying to add the contents of the score file together and get an average but I can’t seem to get it to work.
My code:
JavaScript
x
16
16
1
# open and read file student / score
2
student_file = open("Student.txt", "r")
3
score_file = open("Score.txt", "r")
4
student = student_file.read().split(' ')
5
score = score_file.read().split(' ')
6
addedScore = 0.0
7
average = 0.0
8
9
for i in range(0,len(student)):
10
11
print("Student: "+student[i]+" Final: "+score[i])
12
addedScore = addedScore + score[i]
13
14
average = addedScore / 2
15
print("The class average is:", average)
16
The score file is full of float numbers:
JavaScript
1
2
1
90.0 94.0 74.4 63.2 79.4 87.6 67.7 78.1 95.8 82.1
2
The error message
JavaScript
1
4
1
line 12, in <module>
2
addedScore = addedScore + score[i]
3
TypeError: unsupported operand type(s) for +: 'float' and 'str'
4
Advertisement
Answer
Since score
was created by splitting a string, it’s elements are all strings; hence the complaint about trying to add a float to a string. If you want the value that that string represents, you need to compute that; something like float(score[i])
.