How to test that variable is not equal to multiple things?

This is the piece of code I have:

choice = ""

while choice != "1" and choice != "2" and choice != "3": 
    choice = raw_input("pick 1, 2 or 3")

    if choice == "1":
        print "1 it is!"

    elif choice == "2":
        print "2 it is!"

    elif choice == "3":
        print "3 it is!"

    else:
        print "You should choose 1, 2 or 3"

While it works, I feel that it's really clumsy, specifically the while clause. What if I have more acceptable choices? Is there a better way to make the clause?


The while bit could be refactored a little to make it a little bit cleaner by checking if the element is within a list of choices like so

while choice not in [1, 2, 3]:

This is checking if the value of choice is not an element in that list


You can push the logic into the loop, and replace

while choice != "1" and choice != "2" and choice != "3": 

with

while True:

and then the initial line choice = "" is unnecessary. Then, in each branch, once you're done what you want to do you can break.


I think something like that would be better

possilities = {"1":"1 it is!", "2":"2 it is!", "3":"3 it is!"} 
choice = ""

while True:
    choice = raw_input("pick 1, 2 or 3")
    if choice in possilities:
        print possilities[choice]
        break
    else:
        print "You should use 1, 2 or 3"

You can use a dictionary to map 1 to the code you want to execute when 1 is the value, and so on... That way you get rid of the ifs and your code can support other values in the future by simply updating the dictionary. As for the condition in the while, you just check if the key is in the dictionary.