python - 求和函数概率类型错误: unsupported operand type(s) for +: 'int' and 'str'

标签 python sum typeerror operand operands

我是 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/

相关文章:

python - 小键盘在 pygame 中不起作用

python - 如果该列大于所述日期,如何绕过此错误以使该列为零? "TypeError: invalid type promotion "

xml - SUM() XML 的不同节点

ruby-on-rails - 模型 rails 计算总价

mysql - 两个表的 LEFT JOIN、SUM、GROUP

python - 类型错误:url() 获得意外的关键字参数 'name_space'

python - 在Django项目中获取typeError错误

python - 在转换为日期时间的列上使用 timedelta 和 strftime

python - 有什么方法可以使用Python中的颜色曲线来操作图像吗?

python - 无法获取正确的像素颜色图像python