loops
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sun Oct 19 03:56:10 EDT 2008
On Sat, 18 Oct 2008 20:45:47 -0700, John Machin wrote:
> On Oct 19, 2:30 pm, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> wrote:
> [snip]
>> making your code easy to read and easy to maintain is far more
>> important.
>>
>> for x in (2**i for i in xrange(10)):
>> print x
>>
>> will also print 1, 2, 4, 8, ... up to 1000.
>
> I would say up to 512; perhaps your understanding of "up to" differs
> from mine.
Well, mine is based on Python's half-open semantics: "up to" 1000 doesn't
include 1000, and the highest power of 2 less than 1000 is 512.
Perhaps you meant "up to and including 512".
> Easy to read? I'd suggest this:
>
> for i in xrange(10):
> print 2 ** i
Well, sure, if you want to do it the right way *wink*.
But seriously, no, that doesn't answer the OP's question. Look at his
original code (which I assume is C-like pseudo-code):
for x=1;x<=100;x+x:
print x
The loop variable i takes the values 1, 2, 4, 8, etc. That's what my code
does. If he was asking how to write the following in Python, your answer
would be appropriate:
for x=1;x<=100;x++:
print 2**x
--
Steven
More information about the Python-list
mailing list