r/PythonLearning • u/WiseDeer42663 • 27m ago
Help Request Getting TypeError: unsupported operand 'int' and 'str' when summing scores from input()
I'm a few weeks into learning Python and working on a small practice project: a program that asks the user for a few course scores with input(), then calculates the total and the average. Nothing fancy, just trying to get the basics to click.
Here's the code I have right now:
courses = 3
total = 0
scores = []
for i in range(courses):
score = input('Enter score ' + str(i + 1) + ': ')
scores.append(score)
for score in scores:
total = total + score
average = total / courses
print('Average:', average)And this is the error I get:
Traceback (most recent call last):
File "grades.py", line 8, in <module>
total = total + score
TypeError: unsupported operand type(s) for +: 'int' and 'str'I think I get the general idea: input() gives me something that isn't a number, and I'm adding it to total, which starts as the int 0. I searched for this error and a lot of answers mention int(), so I know int() converts a string to a number. What I'm stuck on is where to do the conversion. Should I call int() right when I get the input in the first loop, or wait and convert while summing? And if I convert early, will that break something else, like how I'm storing the scores in the list?
So what type does input() actually return, and what's the cleaner way to write this so the total and average work? Thanks in advance, I appreciate any pointers.
