Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #96188
| From | alister <alister.nospam.ware@ntlworld.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Hi am new to python |
| Date | 2015-09-09 11:41 +0000 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <msp5td$d9r$1@speranza.aioe.org> (permalink) |
| References | <mailman.265.1441798120.8327.python-list@python.org> |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Hi am new to python alister <alister.nospam.ware@ntlworld.com> - 2015-09-09 11:41 +0000
csiph-web