As you mentioned, the easiest way is to use raw_input()
(or simply input()
for Python 3). There is no built-in way to do this. From Recipe 577058:
import sys def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == "": return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
(For Python 2, use raw_input
instead of input
.) Usage example:
>>> query_yes_no("Is cabbage yummier than cauliflower?") Is cabbage yummier than cauliflower? [Y/n] oops Please respond with 'yes' or 'no' (or 'y' or 'n'). Is cabbage yummier than cauliflower? [Y/n] [ENTER] >>> True >>> query_yes_no("Is cabbage yummier than cauliflower?", None) Is cabbage yummier than cauliflower? [y/n] [ENTER] Please respond with 'yes' or 'no' (or 'y' or 'n'). Is cabbage yummier than cauliflower? [y/n] y >>> True