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

后端 未结 4 953
有刺的猬
有刺的猬 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:18

    if you want to store numbers in list, create list. also add a loop for user enters values. you can assign an input to break the loop or add a counter.

    myList = []
    counter = 0 
    while counter<10: #change this to true for infinite (unlimited) loop. also remove counter variables
        num = raw_input("Enter numbers or (q)uit")
        if num == 'q': 
            break
        else:
            myList.append(int(num))
        counter +=1
    
    print sum(myList)  
    

    or without list

    >>> while True:
    ...     num = raw_input("number or (q)uit")
    ...     if num == 'q': break
    ...     else:
    ...             total +=int(num)
    ... 
    

    result

    number or (q)uit4
    number or (q)uit5
    number or (q)uit6
    number or (q)uit7
    number or (q)uit8
    number or (q)uit9
    number or (q)uit9
    number or (q)uitq
    >>> total
    48
    

提交回复
热议问题