Reputation: 35
I'm want to be able to determine if an input is valid. I have:
servqual = raw_input(">").lower()
while servqual != "great" or "good" or "lacking" or "poor":
print "I didn't understand that. Please try again."
servqual = raw_input(">").lower()
However, whenever I run it through the loop it always assumes True, even if I input a valid answer. I've looked over different answers but none of them seem to work in this scenario.
Upvotes: 0
Views: 438
Reputation: 1509
servqual != "great" or "good" or "lacking" or "poor"
is equivalent to
(servqual != "great") or "good" or "lacking" or "poor"
And since Strings are considered True
, you are always getting it True
The correct way to do it is
servqual != "great" and servqual != "good" and servqual != "lacking" and servqual != "poor"
or
servqual not in ("great", "good", "lacking", "poor")
Your final code will look like
servqual = raw_input(">").lower()
while servqual not in ("great", "good", "lacking", "poor"):
print "I didn't understand that. Please try again."
servqual = raw_input(">").lower()
You can further improve it by using following construct.
while raw_input(">").lower() not in ("great", "good", "lacking", "poor"):
print "I didn't understand that. Please try again."
Upvotes: 5
Reputation: 59222
You have:
while servqual != "great" or "good" or "lacking" or "poor":
This means the same as:
while (servqual != "great") or "good" or "lacking" or "poor"
Since "good" or "lacking" or "poor"
is always true, the whole condition is true.
Rather than that, you can do this:
while servqual not in ("great", "good", "lacking", "poor"):
...
Upvotes: 1