The rap against "while True:" loops

Jorgen Grahn grahn+nntp at snipabacken.se
Wed Oct 14 15:37:00 EDT 2009


On Mon, 2009-10-12, RDrewD wrote:
...
> I was a bit surprised that nobody in this discussion so far bantered
> around the phrase "loop invariant", but then I looked in
> http://en.wikipedia.org/wiki/Loop_invariant and found it was draped in
> so much formalism that it's sure to put off all but the most dedicated
> of Computer Science fans.

Haven't read it. But much of the CS parts of the Wikipedia sucks, and
whoever writes there doesn't own the trademark on loop invariants
anyway.

IME, a loop invariant is a simple and useful tool for thinking about
the correctness of code. Class invariants (or whatever they are called)
are even better.

> I haven't been in college in 35 years, so
> I'll admit to being rusty on this, but as I remember it, any time we
> wrote a loop, we were expected to be able to say what the loop
> invariant is.

Yes, it's as simple as that.

> 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.

Why not? To me, it obviously does.

It would also help if you didn't use intentionally meaningless and
annoying variable names in your examples. In reality you would have a
meaningful expression like "not inputqueue.empty()" or
"time() < deadline" or something.

/Jorgen

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



More information about the Python-list mailing list