The rap against "while True:" loops

greg greg at cosc.canterbury.ac.nz
Wed Oct 14 02:06:49 CEST 2009


Steven D'Aprano wrote:
> The best I 
> have seen is that loops should have a single entry point and a single 
> exit point, to make it easier to reason about pre- and post-conditions. 
> But frankly I'm not convinced that's true -- or at least, multiple exists 
> shouldn't *necessarily* leader to difficulty in reasoning about the post-
> condition.

It's not all that difficult.

If you have multiple exit conditions tested in different
places, in general each one can have its own associated
loop invariant. Then the postcondition of the loop is

   (invariant1 and exitcond1) or (invariant2 and exitcond2) or ...

If that gets you where you want to be, then you're
home and dry.

-- 
Greg



More information about the Python-list mailing list