[Tutor] 'for' loops

Lie Ryan lie.1296 at gmail.com
Sun Dec 7 18:14:14 CET 2008


On Tue, 02 Dec 2008 01:17:41 +0000, Alan Gauld wrote:

> while loops are used much less in Python than in other languages because
> for loops are so powerful.

Actually, I think python's for-loop is so powerful that while loop could 
be removed from the language and no power would be lost (although many 
idioms are much better (and faster) written in while loop). This is 
because python allows infinite-length iterable, you can emulate "while 
True" loop with something like this:

eternity = __import__('itertools').count()
for ever in eternity:
    print "can't stoooop...."

# the code above is slightly obfuscated, 
# I wouldn't normally write it like that
# ...
# [1]

> while lops are generally used in cases where you don't know how many
> times you need to loop or you want to loop 'forever'.
> 
> while True:
>     print 'Can't stop me now!'
> 
> will keep on looping until you close the program
> 
> c = 0
> while c != -1:
>     c = int(raw_input('Enter a number(-1 to stop) ')) 
>     print c
> 
> will keep looping until the user enters -1

while that can be turned into something like this:

for ever in eternity:
    c = int(raw_input('Enter a number(-1 to stop) ')) 
    print c

OR

from itertools import repeat
from functools import partial
def ask():
    def stop(): raise StopIteration
    asker = partial(raw_input, 'Enter a number(-1 to stop) ')
    for n in repeat(asker):
        n = n()
        yield n if n != '-1' else stop()

for c in ask():
    print c

> More info and a comparison with JabaScript and VBScript can be found in
> my tutor in the looping topic.

[1] I cheated slightly, there is a while loop in the C code for itertools
[2] I'm not suggesting that while loop should go away, I'm illustrating 
the power of the for(ce).



More information about the Tutor mailing list