Sum function prob TypeError: unsupported operand type(s) for +: #39;int#39; and #39;str#39;(求和函数概率类型错误:+ 不支持的操作数类型:“int和“str)
问题描述
我是 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
这篇关于求和函数概率类型错误:+ 不支持的操作数类型:“int"和“str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:求和函数概率类型错误:+ 不支持的操作数类型:“
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
