2

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

任何帮助将不胜感激。

4

5 回答 5

4

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
于 2014-11-14T05:33:23.987 回答
0

input会给你字符串,你正在尝试用 int 连接字符串。

于 2014-11-14T05:25:52.030 回答
0

试试下面的代码。这个对我有用。实际上input()尝试将输入作为 Python 表达式运行。但是raw_input()将输入作为字符串。input()存在于 Python 3.x 中。您可以在此处找到更多详细信息

numbers = input("Enter your numbers followed by commas: ") ## takes numbers as input as expression
print sum([i for i in numbers]) ## list comprehension to convert the numbers into invisible list. This is done because `sum()` runs only on iterable and list is iterable.

输出:

Enter your numbers followed by commas: 1,2,3,4
10
于 2014-11-14T05:38:44.017 回答
0

首先,您需要将“数字”的元素转换为 int,无需去除逗号或空格。这段代码非常简单并且工作正常。

numbers = input("Enter your numbers followed by commas: ")

numbers_int = [int(x) for x in numbers]

numbers_sum = sum(numbers_int)

print numbers_sum
于 2014-11-14T05:42:57.183 回答
0

简单:列表元素存储为字符串 :) 所以你必须将它们全部转换为 int

于 2016-04-19T17:44:51.400 回答