while true: !!!

Steve Holden sholden at holdenweb.com
Tue Dec 19 08:22:31 EST 2000


Greg Jorgensen <gregj at pobox.com> wrote in message
news:DnD%5.166633$U46.5342944 at news1.sttls1.wa.home.com...
> "Blair Lowe" <Blair.Lowe at compeng.net> wrote:
>
[snip]
>
> You can define true and false yourself, as many C/C++ header files do, but
> then you run the risk of stuff like this:
>
>     true = 1
>     false = 0
>     ...
>     a = len(s)
>     if a == true:  # fails unless a is 1
>
I've always tried to discourage students from comparing a Boolean with a
constant, but it can be difficult to get the point over that (a) can
evaluate as true even though (a == some_constant) may well evaluate to
false.

Clearly, if what you have is a Boolean value (i.e. one which can be used as
the expression in an "if" statement) then it's adding inefficiency to
compare it with something, when what should be used is either

    if a:

or

    if not a:

This works quite nicely in Python:

>>> not "forever"
0
>>> not ()
1
>>> not(1,2,3)
0

although I have worked in languages where, due to bad semantics, any
non-zero value was treated as true, and the "not" operator simply did a
bitwise inversion, so (not {something true}) also evaluated true.

Be that as it may, I would still argue it's bad pedagogy to suggest that
people write "if Boolean == true_constant", since this *should* (but
sometimes isn't, in poorly designed languages) be equivalent to "if
Boolean".

> It's much harder to track this kind of thing down than learning once in
your
> career what "while 1" means.
>
> > While "while 1" (pardon the pun) is a standard fixture that anyone
> > with any experience knows what is going on, the whole point is to
> > make all our code readable so that we, and others can maintain it and
> > reuse it easily.
>
> Exactly--that's why learning idioms is as important as learning syntax.
>
This is why c.l.p. is so helpful: the idioms are regularly presented.

> > Although the definition is cryptic, the resulting code is
> > very readable. That is what we want.
>
> Until it doesn't work. Encountering "while true:" in a program, a newbie
may
> assume that true is a Python keyword. I remember a C++ programmer I worked
> with who though that true and false were keywords until he discovered this
> (typical) definition in a header file:
>
>     enum { false = 0, true = -1 };
>
Although one could argue that he was using a local idiom.  But in general,
and especially in a learning environment, cryptic definitions aren't always
waht you want.  If someone then wants to look "under the hood" they have to
reach a new level of understanding.  "while 1" isn't really that difficult!

regards
 Steve







More information about the Python-list mailing list