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".
http://docs.python.org/lib/built-in-funcs.html
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")
else:
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 !=
"N")):
print "please enter again y or n."
continue
if ((ans == "y") or (ans == "Y")):
return True
if ((ans == "n") or (ans == "N")):
return False
--------------------------------------------
Usage:
if (confirm("\nWant to proceed?", _default=False)):
# proceed
------------------------------------------------