-3

If I make list for e.g.

lst=['a','b','c','d','e','f','g','h','i','j','k','l','n','o','p','q','s','t','u','v','w','x','y','z']

I want a user to select input only from this given list

def select():
    select=''
    while guess not in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'p', 'q', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']:
        guess=input("select a letter? ")
        
    return (select)

We can use this method but is there any other method so instead of putting the whole list we can put variable assign to that list

  • You can't limit the user. You could only replace all the "wrong" characters before processing them. – Banana Aug 14 '20 at 10:05
  • 2
    Please describe what you want more clearly, e.g. with example input, output, error message, code etc. – khelwood Aug 14 '20 at 10:06
  • Check this discussion [User selects an input from a finite list](https://stackoverflow.com/questions/37565793/how-to-let-the-user-select-an-input-from-a-finite-list) – Gautamrk Aug 14 '20 at 10:18

3 Answers3

1

You need a while loop to ask the user get input till the input is valid like below:

In [1]: valid_input_lst=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
   ...:                  'j', 'k', 'l', 'n', 'o', 'p', 'q', 's', 't',
   ...:                  'u', 'v', 'w', 'x', 'y', 'z']

In [2]:

In [2]: input_char = None
In [4]: while True:
   ...:     print("Input:")
   ...:     input_char = input()
   ...:     if input_char in valid_input_lst:
   ...:         break
   ...:     print("The input is not valid..\n. It should be one of :{}".format(valid_input_lst))
   ...:
Input:
sy
The input is not valid..
. It should be one of :['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'p', 'q', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Input:
x
0

You probably want something like this:

char = input('Enter a character')
if char not in list:
    print("not a valid character")

You can't deny the user from entering anything, you should write software that knows how to handle the possible input.

Eliran Turgeman
  • 1,526
  • 2
  • 16
  • 34
0

get inquirer using pip:

pip install inquirer

here is an example

import inquirer
options = [
      inquirer.List("option",
                     message="Select an option ",
                     choices=["A","B","C","D"],
          ),
]
select = inquirer.prompt(options)
#you can print option using 'select' variable