The rap against "while True:" loops

Mensanator mensanator at aol.com
Sun Oct 11 18:35:38 EDT 2009


On Oct 11, 4:51�pm, "bartc" <ba... at freeuk.com> wrote:
> Mensanator wrote:
> > On Oct 10, 3:15 pm, kj <no.em... at please.post> wrote:
> >> I'm coaching a group of biologists on basic Python scripting. One
> >> of my charges mentioned that he had come across the advice never
> >> to use loops beginning with "while True". Of course, that's one
> >> way to start an infinite loop, but this seems hardly a sufficient
> >> reason to avoid the construct altogether, as long as one includes
> >> an exit that is always reached. (Actually, come to think of it,
> >> there are many situations in which a bona fide infinite loops
> >> (typically within a try: block) is the required construct, e.g.
> >> when implementing an event loop.)
>
> >> I use "while True"-loops often, and intend to continue doing this
> >> "while True", but I'm curious to know: how widespread is the
> >> injunction against such loops? Has it reached the status of "best
> >> practice"?
>
> > If you know this "exit that is always reached",
> > why do you pretend not to know it by writing
> > "while True"?
>
> When I'm starting to code something I haven't yet fully worked out, it often
> starts with an infinite loop like this, until the body is coded and I've
> figured out how to escape from it.

And when I'm in the early stages of a
  while not done:
loop, it performs the exact same functionality
while I'm working out what the terminating
conditions are.

>
> At the end if may or may not be tidied up, depending on how much work it is
> to reconcile several possible break points into a single terminating
> condition to be place at one end, and whether that is likely to break or
> obfuscate a currently working program.

Yes, that's a problem and is a good reason to
avoid doing such a thing. With multiple breaks,
your loop may not properly terminates which may
put an unecessary burden on the code which
follows the loop. Seeing the trees is important,
but not at the expense of the forest.

>
> But if it's never going to be seen by the brigade who hate all break, exit,
> goto and multiple return statements, then I won't bother.

Fine, but the OP is coaching others on how to
program. I've not seen any evidence in this thread
that "while true" is considered "best practice".

>
> --
> Bartc




More information about the Python-list mailing list