Printing highest average – "unsupported operand type(s) for +: 'int' and 'str'"

Question:

I’m trying to achieve an output of the average score printed from highest to lowest. However, when I run the program, I get an error: unsupported operand type(s) for +: 'int' and 'str'.

I’m fairly new to Python and I don’t know where I went wrong with this code:

f = open('ClassA.txt', 'r')
#a empty dictionar created
d = {}
#loop to split the data in the ext file
for line in f:
    columns = line.split(": ")
    #identifies the key and value with either 0 or 1
    names = columns[0]
    scores = columns[1].strip()
    #appends values if a key already exists
    tries = 0
    while tries < 3:
        d.setdefault(names, []).append(scores)
        tries = tries + 1
if wish == '3':
    for names, v in sorted(d.items()):
        average = sum(v)/len(v)
        print ("{} Scored: {}".format(names,average))

The error I get:

Traceback (most recent call last):
  File "N:task 3 final.py", line 33, in <module>
    average = sum(v)/len(v) 
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Asked By: Python Person

||

Answers:

You have strings in your dictionary, but sum() will start with the number 0 to sum numeric values only:

>>> sum(['1', '2'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Convert your scores to numbers, either int() or float() depending on your format:

scores = int(columns[1].strip())
Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.