Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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'
like image 353
Usman Khan Avatar asked Feb 14 '16 15:02

Usman Khan


2 Answers

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

like image 55
Scott Hunter Avatar answered Oct 12 '22 22:10

Scott Hunter


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

like image 23
ForceBru Avatar answered Oct 12 '22 20:10

ForceBru