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

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


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"

Tags:

Python