The rap against "while True:" loops

Mensanator mensanator at aol.com
Mon Oct 12 23:11:17 CEST 2009


On Oct 12, 2:18 pm, Falcolas <garri... at gmail.com> wrote:
> On Oct 12, 12:32 pm, Mensanator <mensana... at aol.com> wrote:
>
>
>
>
>
> > On Oct 12, 1:02 pm, John Reid <j.r... at mail.cryst.bbk.ac.uk> wrote:
> > > Mensanator wrote:
> > > > On Oct 12, 3:36 am, greg <g... at cosc.canterbury.ac.nz> wrote:
> > > >> Mensanator wrote:
> > > >>> while not done:
> > > >>> ...
> > > >>> if n==1: done = True
> > > >>> ...
> > > >> Seems to me that 'while not done:' is no better than
> > > >> 'while True:', because in both cases you have to look
> > > >> inside the loop to find out what the exit condition
> > > >> is.
>
> > > >> Using a more meaningful name for the flag can help,
> > > >> but you can't teach someone that just by giving them
> > > >> an overly simplified rules such as "never use
> > > >> while True:". They'll probably just replace it with
> > > >> 'while not done:' and think they've improved things,
> > > >> without ever really understanding the issue.
>
> > > > You're missing the point. It's not that you have to
> > > > look inside for the terminating condition. It's that
> > > > you don't need a break.
>
> > > Nothing wrong with a having a break IMHO.
>
> > My opinion is that there is everything wrong with
> > having a break. I don't think I have ever used one,
> > I write code that doesn't depend on that crutch.
>
> > > while not done:
>
> > > seems very dangerous to me as you'd have to
>
> > > del done
>
> > > before writing the same construct again. That's the sort of thing that
> > > leads to errors.
>
> > Duh. I won't write silly code like that either.
> > If I need more than one loop structure then I'll
> > do something like
>
> >     while not done_with_this
>
> >     while not done_with_that
>
> > Besides, since I _always_ initialize the flag
> > before entering a loop, the flag can be reused
> > and doesn't have to be deleted (as long as the
> > loops aren't nested). And since I don't use goto,
> > there's no chance the initialization can be avoided.
>
> > The best way to avoid the pitfalls of spaghetti
> > code is to not write it in the first place.
>
> How do you manage code where you need to drop out of a neatly written
> for or while loop early?

I don't. If I thought there would ever be a case when
a for loop had to exit early, I wouldn't use a for loop.

Similarly, if I ever felt the need to escape from a
while loop, I would rewrite it to avoid that situation.

> I don't use break frequently, but just like
> gotos, it does have it's place in well written code.
>
> Glad to hear, by the way, that you don't use gotos in Python. =D

Python doesn't have goto? Gee, I guess I never looked for
one. Learned my lesson from Pascal, eh?

>
> Garrick




More information about the Python-list mailing list