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

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

    You are not creating a list. You are creating a string with your user input and attempting to convert that string to an int.

    You can do something like this:

    mylist = raw_input('Enter your list: ')
    mylist = [int(x) for x in mylist.split(',')]
    total = 0    
    for number in mylist:    
        total += number    
    print "The sum of the numbers is:", total
    

    Output:

    Enter your list:  1,2,3,4,5
    The sum of the numbers is: 15
    

    What did I do?

    I changed your first line into:

    mylist = raw_input('Enter your list: ')
    mylist = [int(x) for x in mylist.split(',')]
    

    This accepts the user's input as a comma separated string. It then converts every element in that string into an int. It does this by using split on the string at each comma.

    This method will fail if the user inputs a non-integer or they don't comma separate the input.

提交回复
热议问题