I am doing my homework and it requirers me to use a sum () and len () functions to find the mean of an input number list, when I tried to use sum () to get the sum of the list, I got an error TypeError: unsupported operand type(s) for +: 'int' and 'str'. Following is my code:
numlist = input("Enter a list of number separated by commas: ")
numlist = numlist.split(",")
s = sum(numlist)
l = len(numlist)
m = float(s/l)
print("mean:",m)
The problem is that you have a list of strings. You need to convert them to integers before you compute the sum. For example:
The problem is that when you read from the input, you have a list of strings. You could do something like that as your second line:
You are adding up strings, not numbers, which is what your error message is saying.
Convert every string into its respective integer:
And then take the average (note that I use
float()
differently than you do):You want to use
float()
before dividing, asfloat(1/2) = float(0) = 0.0
, which isn't what you want.An alternative would be to just make them all
float
in the first place:Split returns you an array of strings, so you need to convert these to integers before using the sum function.
For Python 2.7
You can try this.