我是 python (PYTHON 3.4.2) 的新手,我正在尝试制作一个程序,通过加法和除法来查找用户输入的平均值或均值,但我不知道如何相加我收到的数字。
当我在命令提示符下打开程序时,它接受我输入的数字,如果我使用打印功能,它也会打印它,但它不会将数字相加。
我收到此错误:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
我的代码如下:
#Take the user's input
numbers = input("Enter your numbers followed by commas: ")
sum([numbers])
任何帮助将不胜感激。
最佳答案
input
将输入作为字符串
>>> numbers = input("Enter your numbers followed by commas: ")
Enter your numbers followed by commas: 1,2,5,8
>>> sum(map(int,numbers.split(',')))
16
您告诉用户输入以逗号分隔,因此您需要用逗号分隔字符串,然后将它们转换为 int 然后求和
演示:
>>> 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
关于python - 求和函数概率类型错误: unsupported operand type(s) for +: 'int' and 'str' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26923445/