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

I am new to Python and am stuck with what to do right now because I keep getting this error. 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 =' ')
score =' ')
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'

I appreciate all the help I can get. Thanks a lot

Solution #1:

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

Respondent: Scott Hunter

Solution #2:

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

Respondent: ForceBru

Solution #3:

When you split the contents of the file, they are still strings. Change score =' ') to score = [float(x) for x in" ")]. You probably don’t need to do .split(" "), because str.split() will by default split by whitespace. Therefore, you can use .split().

Respondent: zondo

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy