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

Gianni Alessandro picture Gianni Alessandro · Jun 1, 2016 · Viewed 46.9k times · Source

I'm quite new of python and programming, so I'm sorry if it's a "noob question". Anyway, is it possible to ask the selection between multiple choice in python, without a if loop?

Stupid example:

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

And the user can only choose between the selection.

Answer

Khopa picture Khopa · Jun 1, 2016

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