Search code examples
listloopsraw-input

How to see if the user chose a element in a list (python)


I'm trying to use the following code :

blosum = input("pick a matrix:")
x = [30, 40, 50, 100, 75, 70]
while blosum not in x :
    blosum = raw_input("Incorrect, pick a valid matrix:")
print ('ok')    

I want it to decide whether the user chose one of the options of the list. If the user chose one of them, then the program should keep running, otherwise, it keeps telling the user to pick a valid matrix. But it doesn't work, why?


Solution

  • Go ahead and change raw_input to input in your code like so and cast the user supplied data to an integer like so:

    blosum = int(input("pick a matrix: "))
    x = [30, 40, 50, 100, 75, 70]
    while blosum not in x:
        blosum = int(input("Incorrect, pick a valid matrix:"))
    print ("OK")
    

    Test

    $ python test.py
    pick a matrix: 1
    Incorrect, pick a valid matrix:2
    Incorrect, pick a valid matrix:30
    OK
    

    This will work for both Python 2.7+ and 3+, I believe, but you should test it out nonetheless.

    See the difference between raw_input and input in questions like these: