On Tue, 08 Sep 2015 17:44:26 -0500, Nassim Gannoun wrote: > Hi I'm also new to Python but would like to reply. > Like others have stated there is a built in function (sum) that can give > the sum of the elements of a list, but if what you are trying to do is > learn how to use the while command here is some code that will work. > Your question: > My question is in a while loop; how do l sum all the numbers in the > given list (list_a)? > > list_a = [8, 5, 2, 4] > sum_a = 0 # for storing the sum of list_a i = 0 # for looping through > the list_a# Use a while loop to sum all numbers in list_a# If you store > the sums into sum_a print(sum_a) # should print 19 My answer: > list_a = [8, 5, 2, 4] > > > > sum_a = 0 i = 0 while i < (len(list_a)): > sum_a += list_a[i] > i += 1 > > > print(sum_a) > This is OK a a learning excise but it is just about the worst way to achieve the result in python.
It should be considered as an example of how NOT to perform the task. I do hope this is NOT a homework question set by a teacher as it would get the student into bad habits. -- It's spelled Linux, but it's pronounced `Not Windows' It's spelled Windows, but it's pronounced `Aieeeeeeee!' -- Shannon Hendrix -- https://mail.python.org/mailman/listinfo/python-list