0

can anybody help me with this sum code?

i want a program that gets a list of numbers as input and return the sum . I don't know whats wrong with this code?? can anybody help? def sum_of_list(L): total=0 for x in L: total=total+x return total numbers=input() print (sum_of_list(numbers))

31st Oct 2020, 8:32 AM
shahrbanoogolmohamadi
6 Réponses
+ 3
Ok, if you are typing numbers with no space, you can use list(input()) to split your numbers up, then change them to ints (using map() as before). Obviously this limits you to single-digit numbers.
31st Oct 2020, 10:03 AM
Russ
Russ - avatar
+ 4
You need to de-indent your return line (so it is level with the for line). As it is currently, only your first number is added to total before the result is returned. Also, you need to convert your input into a list of numbers. I like to use the map() method for this as input() returns a string (which you need to change to ints). Assuming your input is space-separated numbers, i.e. 4 8 12 13 3 for example, you would split that string (using split()) into individual numbers, then turn each one into an int (using map()). numbers = list(map(int, input().split())) will do all that in one go. Amended code: def sum_of_list(L): total=0 for x in L: total=total+x return total numbers=list(map(int, input().split())) print (sum_of_list(numbers))
31st Oct 2020, 9:23 AM
Russ
Russ - avatar
+ 1
Check this code out. This is exactly the code I posted. You should find it returning the sum. https://code.sololearn.com/cL1uXNsxc46f/?ref=app
31st Oct 2020, 9:49 AM
Russ
Russ - avatar
0
Russ thanks for your help but when I try it in python it only shows the numbers not sum of them ! Im very confused
31st Oct 2020, 9:44 AM
shahrbanoogolmohamadi
0
thanksss .I get it It works when we type the input numbers with distance 5 6 7 8 but when we type without distance like 5678 it only returns the numbers not the sum
31st Oct 2020, 9:53 AM
shahrbanoogolmohamadi
0
Without split it works .thanks for your help . Im new with codes
31st Oct 2020, 9:56 AM
shahrbanoogolmohamadi