The rap against "while True:" loops

Raymond Hettinger python at
Wed Oct 14 22:23:42 CEST 2009

> And I know somebody, in other languages, thinks
> it's a Best Practice to avoid using exceptions for flow control.

Ah, now we have two code prions in just one thread.
I hope no newbie or supervisor reads this thread and latches
on to those two counter-productive ideas.

ISTM, both ideas are dangerous contagious because they are
true in some limited contexts but useless (and harmful)
when applied to programming in general.

IIRC, the C++ admonition against using exceptions for flow control
was rooted in performance concerns specific to that language and
its compilers.  It was not stylistic advice and did not deny that
flow control exceptions could provide elegant solutions to some
programming challenges.

Python's IndexError and KeyError are all about flow control.
The notion is deeply embedded in the language and it would
be a disservice to advise people to not use the language as

Likewise, the use of "while True" tends to be more important
in Python than in other languages because we can't combine
assignment with a conditional as we can in C.  So instead,
we have this idiom:

    while True:
        s =
        if not s:

Suggested further reading for those who are interested:

"The Little MLer" -- a chunk of this book is devoted to showing
how exceptions can simplify code that would otherwise be
somewhat awkward to express (the remainder of the book is devoted
to thinking about types and how to compose program components).

"Structured Programming with go to Statements" by Donald Knuth
has an in-depth comparative analysis of many different looping


More information about the Python-list mailing list