how to write a C-style for loop?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Feb 15 07:37:52 EST 2006


On Wed, 15 Feb 2006 10:20:13 +0000, ZeD wrote:

> Ciao, John Salerno! Che stavi dicendo?
> 
>> for (int i = 0; i < 50; i += 5)
>> 
>> How would that go in Python, in the simplest and most efficient way?
> 
> i=0
> while i<50:
>     #...
>     i+=5

That's exceedingly unPythonic. In fact I'd go far to say it is bad
practice in just about any programming language that has for loops. Why on
earth would any sensible programmer want to manage the loop variable by
hand if the language can do it for you?


> about range()/xrange(): what if you want to traslate this c-loop? for
> (int i=1; i<50; i*=2)

That's a completely different question, so of course it has a completely
different answer. Here is one way:

for i in [2**n for n in range(6)]:
    do_something(i)

Here is another:

for i in range(int(math.log(50)/math.log(2)+1)):
    do_something(2**i)

Here is a third way:

i = 1
while i < 50:
    do_something(i)
    i *= 2

Here is a fourth way:

import operator
def looper(start, (op, finish), (op2, x)):
    n = start
    while op(n, finish):
        yield n
        n = op2(n, x)

loop = looper(1, (operator.__lt__, 50), (operator.__mul__, 2))

for i in loop:
    do_something(i)



-- 
Steven.




More information about the Python-list mailing list