求和函数概率类型错误:+ 不支持的操作数类型:“int"和“str"

2022-01-09 00:00:00 python typeerror sum operand operands

问题描述

我是 python (PYTHON 3.4.2) 的新手,我正在尝试制作一个程序来添加和除以查找用户输入的平均值或平均值,但我不知道如何添加我收到的号码.

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.

我收到此错误:

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 然后求和

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

演示:

>>> 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

相关文章