Welcome, guest | Sign In | My Account | Store | Cart

Ask the user a question using raw_input() and looking something like this:

QUESTION [Y/n] 
...validate...

See also: Recipe 577096 (query custom answers), Recipe 577097 (query yes/no/quit), Recipe 577098 (query long), Recipe 577099 (query)

Python, 31 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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 one of "yes" or "no".
    """
    valid = {"yes":"yes",   "y":"yes",  "ye":"yes",
             "no":"no",     "n":"no"}
    if default == 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 1:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower()
        if default is not None and choice == '':
            return default
        elif choice in valid.keys():
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "\
                             "(or 'y' or 'n').\n")

3 comments

Joe Eggen 11 years, 11 months ago  # | flag

Hello - this is my first post here and I am pretty new to python. This recipe looks perfect for what I need at the moment, but I am having trouble with the implementation. For example, I want my program to ask the user "do you want to use all the .fits files in this directory?"

If "yes" - proceed to a certain line later in the program If "no" - provide a .txt list of the files you would like to use

I cannot figure out how this code stores the answer to any question that is asked of it, so I cannot use the results of the query to take any specific action. Any ideas?

cptsupermrkt 9 years, 2 months ago  # | flag

Better late than ever I guess, but basically Joe, the recipe given here doesn't store the answer, it just returns it, and the caller is responsible for either storing or ignoring the answer.

You copy/paste the above code into your current module or a separate one (in that case import it). In this example below I've copy/pasted the recipe into MyModule.py. Then in the module where I want to use it...

import MyModule

answer = MyModule.query_yes_no("Do you want to use all the .fits files in this directory?") if answer == "no": get_txt_files() else: do_something_else()

moonkid 8 years, 4 months ago  # | flag

What is a bout the licence of this code? I want to use it in a GPLv3 software.

Created by Trent Mick on Fri, 19 Feb 2010 (MIT)
Python recipes (4591)
Trent Mick's recipes (28)

Required Modules

  • (none specified)

Other Information and Tasks