How to let the user select an input from a finite list?
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"