Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 952
Gianni Alessandro Avatar asked Jun 01 '16 10:06

Gianni Alessandro


3 Answers

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

like image 173
Khopa Avatar answered Oct 18 '22 05:10

Khopa


One possible way to achieve what you appear to require is with a while loop.

print "Do you want to enter the door"
response = None
while response not in {"yes", "no"}:
    response = raw_input("Please enter yes or no: ")
# Now response is either "yes" or "no"
like image 7
holdenweb Avatar answered Oct 18 '22 07:10

holdenweb


For an OS agnostic solutions using prompt-toolkit 2 or 3, use questionary

https://github.com/tmbo/questionary

like image 6
M.Vanderlee Avatar answered Oct 18 '22 05:10

M.Vanderlee