while (a=b()) ...

Derek T. Jones dtj at rinconn.com
Sat May 1 17:27:21 EDT 1999


In article <slrn7ii759.eoc.wtanksle at dolphin.openprojects.net>,
wtanksle at dolphin.openprojects.net wrote:

> On Thu, 29 Apr 1999 16:48:39 -0700 (PDT), Nathan Clegg wrote:
> >I have some deep-rooted "hates" in programming and don't even know where
> >some of them came from.  One of them is "while 1" loops.  They seem
> >somehow at the same level as goto statements and should be used, in my
> >mind, about as rarely.
> 
> I agree.  Especially since while(1) loops require the use of a goto inside
> of them.

I disagree.  A 'break' is not a 'goto'.  The language Icon, which was
part of Python's inspiration, has a 'repeat' loop which can only be
broken out of with a 'break' statement.  The idea of a loop whose exit
condition must be, for design reasons, not either at the very beginning or
the very end of the loop is not a kluge.

In fact, contorting your problem so that the exit condition is forced to
be at the very top or the very bottom can, IMHO, result in some ungainly
code as well.  I agree with you that an assignment statement inside of
a while loop is not a solution.

The solution where the test method and the result method of the object
in the loop are separate is, I believe, the nicest.  But when the object
you're working with doesn't provide that, then I vote for the "forever"
loop.

Finally, I would write the forever loop using the following "idiom":

   while 1 :
      c = curs.fetchone()
      if not c : break
      print c

instead of

   while 1 :
      c = curs.fetchone()
      if c :
         print c
      else :
         break

Reason:  I feel it's easier to read and dispense with the exceptional
conditions first, then save the normal case for the rest of the loop.

-- 
My real email address has only one 'n' in it, for those who care.




More information about the Python-list mailing list