[Tutor] Starting over with Python

wesley chun wescpy at gmail.com
Thu Dec 14 03:34:59 CET 2006


> odd =1
> >>>while odd <=100:
>         if (odd%2)==1:
>                 print odd
>         odd = odd + 1
> -------------------------------------------------------------------------------------------------
> I get a list of the odd numbers from 1 to 99. But now if I wanted to add
> those number together (i.e. 1 + 3 +5 + 7 etc.), what line of coding should I
> include? I have tried to add "odd + odd" but it did not work. In advance

i can't help you with the cryptography stuff, but in cases like your
example, i think reduce() might be useful, but your *specific* case
can be handled with a 1-liner:

>>> sum([x for x in range(100) if x % 2])
2500

or the same using less memory in Python 2.4+:

>>> sum(x for x in range(100) if x % 2)
2500

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list