The rap against "while True:" loops
garrickp at gmail.com
Mon Oct 12 21:18:59 CEST 2009
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 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
More information about the Python-list