Skip to main content
 首页 » 编程设计

python之求和函数概率 TypeError : unsupported operand type(s) for +: 'int' and 'str'

2024年10月25日27zhwl

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