求和函数概率类型错误:+ 不支持的操作数类型:“int"和“str"
- 作者: 跋涉千里向你道别
- 来源: 51数据库
- 2022-10-21
问题描述
我是 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
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
