Confused about while statement

John Roth newsgroups at jhrothjr.com
Thu May 20 21:48:40 EDT 2004


"EAS" <eriksp at attbi.nospam.com> wrote in message
news:dHcrc.86491$536.14466932 at attbi_s03...
> In theory, the following code should ask for the user to enter a value for
h
> until he/she enters hello or goodbye.
>
> h = "hi"
> while h != "hello" or "goodbye":
>         h = raw_input("Value for h:")
>
> But the program keeps asking for a value no matter what I enter. Why
doesn't
> it work?

Operator precedence and a misunderstanding about how "or" works.

Operator precedence means that the expression is equivalent to:

(h != "hello") or "goodbye"

The result of h != "hello" is either True or False.
The way "or" works, if the result was false, the
second operand would be substituted, so you
would get "goodbye" which is true. In other words,
the result of the entire expression is either True
or "goodbye", which is also true. So the loop never terminates.

The "proper" way to write this test is:

while h not in ("hello", "goodbye"):

There are other ways, but this is probably the most readable.

John Roth


>
>





More information about the Python-list mailing list