0
Follow
2
View

Unsupported operand type for sum() function

jmshxy5233 注册会员
2023-01-25 09:32

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 pointless calls to int in your mean function. 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.