The rap against "while True:" loops

Jorgen Grahn grahn+nntp at snipabacken.se
Wed Oct 14 21:50:18 CEST 2009


On Mon, 2009-10-12, Grant Edwards wrote:
> On 2009-10-12, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote:
>
>>> my_prissy_little_indicator_variable = true
>>> while (my_prissy_little_indicator_variable){
>>>     <body>
>>> }
>>> isn't satisfying because it doesn't guard the <body> with any
>>> assurance that the loop invariant will be true before you enter into
>>> that block of code.
>>
>> I think you meant the other way; the above is the simplest loop case, with  
>> the test at the start.
>
> Except the test at the start is meaningless when it comes to
> reading the code and troubleshooting.  What counts are
> assignments to my_prissy_little_indicator_variable inside the
> loop.  And those aren't really any easier to spot that "break"
> statements.

It's a red herring.  A good loop tends to *not* have a boolean
variable as the while ... expression.  That smells like flag
programming, and if I cannot come up with anything better that that, I
often prefer a "while 1" with breaks in it.

For a real-life loop, see for example

  http://en.wikipedia.org/wiki/Binary_search#Iterative

(except it confuses me because it's a repeat ... until and it's in
Pascal with that quaint 1-based indexing)

/Jorgen

-- 
  // Jorgen Grahn <grahn@  Oo  o.   .  .
\X/     snipabacken.se>   O  o   .



More information about the Python-list mailing list