[Tutor] (no subject)

Alan Gauld alan.gauld at btinternet.com
Mon Jul 21 09:16:12 CEST 2014


On 21/07/14 01:34, Marc Tompkins wrote:

> noticed that you often advise it.  I don't know who _does_ think this
> is a desirable pattern; I'd love to hear their argument for it - it
> must be really good.


Nope, it doesn't need to be "really good", it just needs to
have enough advantage over the alternatives for people
to prefer it.

In the case of while loops the options are:

1) while True:

while True:
     read input
     if end condition: break
     process loop

2) While test

read input
while test:
    process loop
    read input


The argument against the latter form is simply
that you have to maintain the read input line
in two places.

So far as I can tell, that's it. But it seems
to be enough to make it the default Python while
idiom. Now that doesn't mean that you should not
use form 2 in Python, form 1 is only justified
if you need to repeat the call (or the test).
There are many cases where form 2 would be
better,. and sadly sometimes we see
form 1 being used when it should not.

But even more often we see while loops being
used where they should not. A for loop is
usually a better option if the number of
iterations is known.

Loop choice is one area where Python is not
as expressive as other languages but the
two(*) we have are adequate if not ideal.


(*)And you can extend those somewhat using
generators and itertools.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list