Reading character from keyboard

draghuram at draghuram at
Tue Jan 23 18:26:47 CET 2007

Tommy Grav wrote:
> A very simple question. I would like to read a single character from the
> keyboard (y or n). I have tried to look in my Python books and a google
> search, but have come up empty. I am sure the info s out there, but I
> guess I am unable to find the right question or search keyword :o/

You can use "raw_input".

If you are looking for a function to ask the user for confirmation, you
can use something like this:

def confirm(_prompt=None, _default=False):
    """prompts for yes or no response. Return True for yes and False
for no."""
    promptstr = _prompt
    if (not promptstr):
        promptstr = "Confirm"

    if (_default):
        prompt = "%s [%s]|%s: " % (promptstr, "y", "n")
        prompt = "%s [%s]|%s: " % (promptstr, "n", "y")

    while (True):
        ans = raw_input(prompt)
        if (not ans):
            return _default
        if ((ans != "y") and (ans != "Y") and (ans != "n") and (ans !=
            print "please enter again y or n."
        if ((ans == "y") or (ans == "Y")):
            return True
        if ((ans == "n") or (ans == "N")):
            return False


if  (confirm("\nWant to proceed?", _default=False)):
    # proceed


More information about the Python-list mailing list