Skip to content
Advertisement

Unsupported operand type(s) for +: ‘float’ and ‘str’ error [closed]

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'

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]).

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement