Search code examples
pythonwhile-loopraw-input

Python: Repeating a function when raw_input is not valid


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.


Solution

  • 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."