Confused about while statement

E

EAS

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?
 
E

Erik Max Francis

EAS said:
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?

You meant

while h != "hello" and h != "goodbye": ...
 
R

Roy Smith

Erik Max Francis said:
You meant

while h != "hello" and h != "goodbye": ...

Or, perhaps even better,

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

The meaning is the same, but I think idiomatically, it's a closer match
to the way you would say it in natural language.
 
J

John Roth

EAS said:
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
 
G

Georgy

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

It's always true because even if (h != "hello") evaluates to False,
then "goodbye" is 'tested' and considered to be true.

You probably meant:
h != "hello" and h != "goodbye"
that can be written even better as:
h not in ("hello", "goodbye")

Georgy

| 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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top