Confused about while statement
Delaney, Timothy C (Timothy)
tdelaney at avaya.com
Thu May 20 21:32:09 EDT 2004
EAS wrote:
> 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?
Because h is only being compared to "hello". The while line is being
parsed as:
while (h != "hello") or "goodbye":
Every object in Python has a truth value - in the case of strings, an
empty string is considered false and all others are considered true.
So the above is effectively equivalent to:
while (h != "hello") or True:
which is always going to be true.
There are two normal ways to write the condition you want:
while (h != "hello") and (h != "goodbye"):
or (more general - extends better):
while h not in ("hello", "goodbye"):
Tim Delaney
More information about the Python-list
mailing list