The rap against "while True:" loops

Mensanator mensanator at aol.com
Sat Oct 10 18:34:36 EDT 2009


On Oct 10, 5:02�pm, kj <no.em... at please.post> wrote:
> In <01ccc46d-5ea9-4dfe-ba22-699c6b859... at v36g2000yqv.googlegroups.com> Mensanator <mensana... at aol.com> writes:
>
>
>
>
>
> >On Oct 10, 3:15=EF=BF=BDpm, kj <no.em... at please.post> wrote:
> >> I'm coaching a group of biologists on basic Python scripting. =EF=BF=BDOn=
> >e
> >> of my charges mentioned that he had come across the advice never
> >> to use loops beginning with "while True". =EF=BF=BDOf 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. =EF=BF=BD(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? =EF=BF=BDHas it reached the status of "bes=
> >t
> >> practice"?
> >If you know this "exit that is always reached",
> >why do you pretend not to know it by writing
> >"while True"?
>
> There's no "pretense" of anything. �I just happen to prefer the
> directness of this:
>
> while True:
> � � ...
> � � if test_that_always_succeeds_eventually():
> � � � � �break
> � � ...
>
> over the unnecessary fussiness of this:
>
> my_prissy_little_indicator_variable = True
> while my_prissy_little_indicator_variable:
> � � ...
> � � if test_that_always_succeeds_eventually():
> � � � � my_prissy_little_indicator_variable = False
> � � � � continue �# oh boy this is going to be fun!
> � � ...
>
> In fact, if it were up to me, I would have made the fundamental
> looping construct something like
>
> repeat:
> � � � ...
> � � � if whatever():
> � � � � � �break
> � � � ...

So, the second set of '...' doesn't get executed.

When I use

while not done:
    ...
    if n==1: done = True
    ...

the loop will actually complete (which is what
I want) instead of aborting, like yours does.
I just don't want the loop to execute again.

If there are things that should not be done,
I explicity have the code check that:

    ...
    if not done: write_to_file(test)
    ...

But even if some things are skipped, others
need not be:

    ....
    n += 1
    ...

Now, if I did a break before writing to the file,
I would have to do all kinds of clean-up code
outside the loop, code that would be run only
if the exit were abnormal.

>
> and made all the other looping constructs as syntatic sugar for
> this one.

Luckily, it's not up to you.

>
> kj




More information about the Python-list mailing list