while true: !!!

Greg Jorgensen gregj at pobox.com
Tue Dec 12 03:15:58 EST 2000

"Jaroslav Gergic" <j_gergic at yahoo.com> wrote:

> one thing I dislike in many Python tutorials is
> the style of infinite 'while' loop with 'break' statements:

Learning the syntax of a language will satisfy the compiler, but learning
the idioms will make your code accessible to other programmers, and more
important it will make other programmer's code useful to you. All computer
languages are idiomatic to some degree. It doesn't matter if the idioms are
the "right" way to do things or if they even make sense at first sight; what
is important is that the idioms are commonly used and understood. Reading
code written by someone who doesn't know the idioms is like talking to
someone who knows your language but none of the figures of speech or common
usages (rather like listening to Al Gore).

FORTRAN programs generally use I, J, and K as loop indices because variables
starting with I, J, K are implicitly integers (type declarations are
optional in FORTRAN). This idiom was perpetuated by programmers even when
they moved out of FORTRAN into languages with explicit typing (C, C++,
Pascal) and languages with no typing (Visual Basic, Python).

The C/C++ loop idioms are:

  for (; ;) { ... }

and less common:

  while (1) { ... }

There are any number of ways to write these loops, but the important point
is that the idiom is understood by C/C++ programmers. In "The C Programming
Language" the authors evolve the implementation of the strcpy() function
(copy a string) from the explicit but clunky loop a Basic or FORTRAN
programmer might write to the terse but elegant C idiom that confounds so
many beginniners: "while (*t++ = *s++) ;"

Aside from the loop construction, the variable names s and t are C idioms
introduced by Kernighan & Ritchie. Condemnations of the C idioms--especially
those involving pointers--crop up in the newgroups regularly. A flame war
broke out a few years ago in comp.lang.c++ over which was better: for ( i=0;
i < N; i++ ) or for (i=0; i < N; ++i ). The result is exactly the same, and
K&R use the first (postincrement) idiom, but it turns out that ++i is
usually a tiny bit more efficient than i++. I don't know what the resolution
was, but I notice the preincrement usage is much more common in C++ code
than it is in C.

My advice: learn the idioms of the languages you use.

"...I'm afraid when I'm in this idiom, I sometimes get a bit, uh, sort of
carried away."
    -- Sir Launcelot in "Monty Python and the Holy Grail"

Greg Jorgensen
Deschooling Society
Portland, Oregon, USA
gregj at pobox.com

More information about the Python-list mailing list