如何将数字与输入分开以添加数字?

时间:2019-02-12 13:06:56

标签: python python-3.x

我正在尝试让用户输入一系列数字(用逗号分隔)以接收总数。

我已经尝试过(没有运气):

values = input("Input some comma seprated numbers: ")
numbersSum = sum(values)
print ("sum of list element is : ", numbersSum)

values = input("Input some comma seprated numbers: ")
list = values.split(",")
sum(list)
print ("The total sum is: ", sum)

如果用户输入5.5、6、5.5,则预期输出为17。

7 个答案:

答案 0 :(得分:4)

你快到了。

分割后,值仍然是字符串,因此必须将它们映射为浮点数。

values = "5.5,6,5.5" # input("Input some comma seprated numbers: ")
L = list(map(float, values.split(",")))
print ("The total sum is: ", sum(L))

输出:

The total sum is:  17.0

旁注:请不要命名变量listsum,否则将隐藏python内置函数!

答案 1 :(得分:2)

用逗号将值split values = input("Input some comma seprated numbers: ") lst = values.split(",") lst = [float(x) for x in lst] total = sum(lst) print("The total sum is: ", total) 制成列表后,需要将它们从字符串转换为数字。您可以使用

list

有关参考,请参见List Comprehensions in Python

(此外,您不应该使用KFunction作为变量名,因为这是Python中的函数。)

答案 2 :(得分:1)

您必须将输入转换为float:

numbers = input("Input some comma seprated numbers: ")

result = sum([float(n) for n in numbers.split(',')])

print(result)

答案 3 :(得分:0)

您必须先转换为数字,然后再将其加在一起。

例如,您可以将它们全部转换为float

input_str = input("Input some comma seprated numbers: ")

# Option1: without error checking
number_list = [float(s) for s in input_str.split(',')]

# Option2: with error checking, if you are not sure if the user will input only valid numbers
number_list = []
for s in input_str.split(','):
    try:
        n = float(s)
        number_list.append(n)
    except ValueError:
        pass

print("The list of valid numbers is:", number_list)
print("The sum of the list is:", sum(number_list))

答案 4 :(得分:0)

很难知道出了什么问题而没有错误\输出代码的样本。

我认为问题在于当它是一个字符串列表时,要获取列表的总和(非常糟糕的名字)。

请尝试以下

values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [int(curr) for curr in lst]
sum(lst)
print ("The total sum is: ", sum)

该代码在期望整数时将起作用,如果您要使用浮点数,请更改列表理解。

尽量不要用标准对象的名称来命名对象,例如list,int,str,float等...

答案 5 :(得分:0)

# empty list to store the user inputs
lst = []      

# a loop that will keep taking input until the user wants
while True:
    # ask for the input
    value = input("Input a number: ")
    # append the value to the list
    lst.append(value)
    # if the user wants to exit
    IsExit = input("enter exit to exit")
    if 'exit' in IsExit:
        break

# take the sum of each element (casted to float) in the lst 
print("The sum of the list: {} ".format(sum([float(x) for x in lst])))

输出:

Input a number: 5.5
enter exit to exitno
Input a number: 6
enter exit to exitno
Input a number: 5.5
enter exit to exitexit
The sum of the list: 17.0 

答案 6 :(得分:0)

在下面使用

print('sum of input is :',sum(list(map(float,input('Input some comma separated numbers: ').split(',')))))