我是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 将输入作为字符串
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