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:
# open and read file student / score
student_file = open("Student.txt", "r")
score_file = open("Score.txt", "r")
student = student_file.read().split(' ')
score = score_file.read().split(' ')
addedScore = 0.0
average = 0.0
for i in range(0,len(student)):
print("Student: "+student[i]+" Final: "+score[i])
addedScore = addedScore + score[i]
average = addedScore / 2
print("The class average is:", average)
The score file is full of float numbers:
90.0 94.0 74.4 63.2 79.4 87.6 67.7 78.1 95.8 82.1
The error message
line 12, in <module>
addedScore = addedScore + score[i]
TypeError: unsupported operand type(s) for +: 'float' and 'str'
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])
.
score
is a list of strings, so you definitely cannot add a string to a float as you do here: addedScore = addedScore + score[i]
. You have to convert this string to a float: addedScore = addedScore + float(score[i])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With