[Tutor] Re: Request for code critique

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Oct 22 17:55:32 EDT 2003


> >         while primes[n]<=limit and len(candidates)>0:
> >             limit=int(candidates[0]**0.5)
> >             if candidates[0]%primes[n]==0:
> >                 del candidates[0]
> >                 n=0
> >             n=n+1

> well. Also I think that your while-solution is not as pythonic as it
could be
> (making it harder to follow for me). It's more common to use a break
statement
> than to define a loop variable outside the while-loop:

While that's a frequently seen Python thing I'm not sure its
necessarily a good thing. Break is one of those features
introduced into C (and whence into many other languages)
which breaks the rules of structured programming and by
so doing makes code more difficult to read reliably.
Break is properly intended to be used to break out of
infinite loops, however because Python cannot support
the common C idiom of:

while value = getValue():
    # do something with value

Nor does it have a do/while loop (Or a repeat/until)

repeat:
     # do something
     until <some condition>

or

do:
    # something
    while <some condition>


so that it has become common practice to do:

while 1:
    value = getValue()
    if not value:
        break
    # do something with value

This seems to have evolved to the point where break is now
seen as being a normal while style. In fact the above is
just using a trick (introducing an infinite loop plus break)
to get around a perceived weakness of Python. If value can
legitimately be set up before entering the loop. This has
the plus point of making the while statement much more
natural - since both the terminating conditions are
combined in the loop test, (as Dijkstra & Wirth intended! :-)
and the minus point of requiring one extra line of code and
the attendant double maintenance issue.

> for candidate in candidates:

But I agree the for loop seems nicer overall.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list