How to get a list of numbers as input and calculate the sum?

后端 未结 4 981
有刺的猬
有刺的猬 2021-01-23 05:34
mylist = int(raw_input(\'Enter your list: \'))    
total = 0    
for number in mylist:    
    total += number    
print \"The sum of the numbers is:\", total

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-23 06:35

    Correct way of doing the same is:

    separator = " " #Define the separator by which you are separating the input integers.
    # 1,2,3,4    => separator = ","
    # 1, 2, 3, 4 => separator = ", "
    # 1 2 3 4    => separator = " "
    
    mylist = map(int, raw_input("Enter your list : ").split(separator)) 
    
    print "The sum of numbers is: "+str(sum(mylist))
    

    To find the sum you need to convert the space separated characters into int individually as done above using map function.

提交回复
热议问题