Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #96230 > unrolled thread

Re: Hi am new to python

Started byDenis McMahon <denismfmcmahon@gmail.com>
First post2015-09-09 22:35 +0000
Last post2015-09-09 16:16 -0700
Articles 2 — 2 participants

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Hi am new to python Denis McMahon <denismfmcmahon@gmail.com> - 2015-09-09 22:35 +0000
    Re: Hi am new to python Emile van Sebille <emile@fenx.com> - 2015-09-09 16:16 -0700

#96230 — Re: Hi am new to python

FromDenis McMahon <denismfmcmahon@gmail.com>
Date2015-09-09 22:35 +0000
SubjectRe: Hi am new to python
Message-ID<msqc85$l6g$4@dont-email.me>
On Tue, 08 Sep 2015 17:44:26 -0500, Nassim Gannoun wrote:

> My question is in a while loop; how do l sum all the numbers in the
> given list (list_a)?

You don't normally use a while loop or a counter to iterate over a list. 
Such a question should only be used as a precursor to discussing better 
methods of achieving the required result.

While loop:

> sum_a = 0 
> i = 0 
> while i < (len(list_a)):
>         sum_a += list_a[i]
>         i += 1
> print(sum_a)

Better, use a for loop:

s = 0
for i in list_a:
    s += i
print (s)

Even better, use sum():

s = sum(list_a)
print (s)

And if you only want to display the answer:

print (sum(list_a))

-- 
Denis McMahon, denismfmcmahon@gmail.com

[toc] | [next] | [standalone]


#96231

FromEmile van Sebille <emile@fenx.com>
Date2015-09-09 16:16 -0700
Message-ID<mailman.297.1441840642.8327.python-list@python.org>
In reply to#96230
On 9/9/2015 3:35 PM, Denis McMahon wrote:
> On Tue, 08 Sep 2015 17:44:26 -0500, Nassim Gannoun wrote:
>
>> My question is in a while loop; how do l sum all the numbers in the
>> given list (list_a)?
>
> You don't normally use a while loop or a counter to iterate over a list.
> Such a question should only be used as a precursor to discussing better
> methods of achieving the required result.

As I understand it, the OP was given the homework assignment to sum up a 
list of numbers using while.  Too bad he didn't also specify using 
binary operators along with while.  :)

Emile




[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web