Home > front end >  Unsupported operand type for sum() function
Unsupported operand type for sum() function

Time:01-25

I was working on a simple project to get me more acquainted with Python since it's been a while and the new semester has started.

import math
count = input('Please enter the number of grades: ')

grade_list = []

while count != 0:
    grade = input('What was the grade for the first test?: ')
    grade_list.append(grade)
    count = int(count) - 1

def mean(x):
    grade_total = int(sum(x))
    grade_count = int(len(x))
    mean = int(grade_total) / int(grade_count)
    return mean

print(mean(grade_list))

Here's the error I keep running into:

Traceback (most recent call last):
  File "C:\Users\hattd\Documents\Python Projects\miniproject1.py", line 17, in <module>
    print(mean(grade_list))
  File "C:\Users\hattd\Documents\Python Projects\miniproject1.py", line 12, in mean
    grade_total = int(sum(x))
TypeError: unsupported operand type(s) for  : 'int' and 'str'

I thought that turning the variables into integers would stop this from happening? What am I missing here?

CodePudding user response:

You never "turn the variables into integers". You read a string from the user and append that to grade_list, and then you pass grade_list (a list of strings) to your mean function. Perhaps you want grade_list.append(int(grade)):

count = int(input('Please enter the number of grades: '))

grade_list = []

while count != 0:
    grade = input('What was the grade for the first test?: ')
    grade_list.append(int(grade))
    count -= 1

I've applied the same logic to the count variable as well. With this change, grade_list is a list of integers and you can pass that to sum.


Note that with these changes, you have a bunch of calls to int in your mean function that are no longer necessary. A cleaned up version of your code might look like:

count = int(input("Please enter the number of grades: "))

grade_list = []

while count != 0:
    grade = input("What was the grade for the first test?: ")
    grade_list.append(int(grade))
    count -= 1


def mean(x):
    grade_total = sum(x)
    grade_count = len(x)
    mean = grade_total / grade_count
    return mean


print(mean(grade_list))

Of course, there is a statistics.mean function, as well:

import statistics

count = int(input("Please enter the number of grades: "))

grade_list = []

while count != 0:
    grade = input("What was the grade for the first test?: ")
    grade_list.append(int(grade))
    count -= 1

print(statistics.mean(grade_list))

And consider some of the answers here if you'd like to ask for something other than "the first test" every time.

  • Related