Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

python - Sum function prob TypeError: unsupported operand type(s) for +: 'int' and 'str'

I'm new to python (PYTHON 3.4.2) and I'm trying to make a program that adds and divides to find the average or the mean of a user's input, but I can't figure out how to add the numbers I receive.

When I open the program at the command prompt it accepts the numbers I input and would print it also if I use a print function, but it will not sum the numbers up.

I receive this error:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

My code is below:

#Take the user's input
numbers = input("Enter your numbers followed by commas: ")
sum([numbers])

Any help would be deeply appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

input takes a input as string

>>> numbers = input("Enter your numbers followed by commas: ")
Enter your numbers followed by commas: 1,2,5,8
>>> sum(map(int,numbers.split(',')))
16

you are telling user to give input saperated by comma, so you need to split the string with comma, then convert them to int then sum it

demo:

>>> numbers = input("Enter your numbers followed by commas: ")
Enter your numbers followed by commas: 1,3,5,6
>>> numbers
'1,3,5,6'   # you can see its string
# you need to split it
>>> numbers = numbers.split(',')
>>> numbers
['1', '3', '5', '6']
# now you need to convert each element to integer
>>> numbers = [ x for x in map(int,numbers) ]
or
# if you are confused with map function use this:
>>> numbers  = [ int(x) for x in numbers ]
>>> numbers
[1, 3, 5, 6]
#now you can use sum function
>>>sum(numbers)
15

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...