Search code examples
pythonuser-input

How to let the user select an input from a finite list?


Is it possible to ask for selection between multiple choices in Python, without an if loop?

Example:

print "Do you want to enter the door"
raw_input ("Yes or not")

And the user can only choose between the selections.


Solution

  • If you need to do this on a regular basis, there is a convenient library for this purpose that may help you achieve better user experience easily : inquirer

    Disclaimer : As far as i know, it won't work on Windows without some hacks.

    You can install inquirer with pip :

    pip install inquirer
    

    Example 1 : Multiple choices

    One of inquirer's feature is to let users select from a list with the keyboard arrows keys, not requiring them to write their answers. This way you can achieve better UX for your console application.

    Here is an example taken from the documentation :

    import inquirer
    questions = [
      inquirer.List('size',
                    message="What size do you need?",
                    choices=['Jumbo', 'Large', 'Standard', 'Medium', 'Small', 'Micro'],
                ),
    ]
    answers = inquirer.prompt(questions)
    print answers["size"]
    

    Inquirer example

    Example 2 : Yes/No questions :

    For "Yes/No" questions such as yours, you can even use inquirer's Confirm :

    import inquirer
    confirm = {
        inquirer.Confirm('confirmed',
                         message="Do you want to enter the door ?" ,
                         default=True),
    }
    confirmation = inquirer.prompt(confirm)
    print confirmation["confirmed"]
    

    Yes no questions with Inquirer

    Others useful links :

    Inquirer's Github repo