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.
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"]
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"]
Others useful links :
Inquirer's Github repo
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"
For an OS agnostic solutions using prompt-toolkit 2 or 3, use questionary
https://github.com/tmbo/questionary
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With