Need a function. Any built-in function or module for this?

W

wcc

Hello group,

I need to write a function to get input from user. The prompt will be
like this:
Specify direction[Left/Right/Up/Down] or <Left>:

And if user type "L" or <ENTER>, the function will return "Left", if
user type "R", the function will return "Right", etc..

My quick search in python reference did not yield valid result. Any
pointer?

Thanks for your help.

-wcc
 
P

Paul Rubin

wcc said:
Specify direction[Left/Right/Up/Down] or <Left>:

And if user type "L" or <ENTER>, the function will return "Left", if
user type "R", the function will return "Right", etc..

Hmm:

def getchoice(prompt, choices, default):
"""prompt is a format string with a %s where the list of choices
should go, and another %s where the default should go;
choices is a list of choices; default is the default choice"""
assert default in choices
prompt %= ('/'.join(choices), default)

while True:
c = raw_input (prompt)
if not c:
return default
a = [x for x in choices if x.startswith(c)]
if len(a) == 0:
print 'Please choose one of', '/'.join(choices)
elif len(a) > 1:
print 'ambiguous, enter a unique prefix'
else:
return a[0]

def test():
print getchoice('Specify direction %s or <%s>: ',
("Left","Lexy","Right","Up","Down"), "Left")

test()
 
W

wcc

Thanks you very much Paul. I think I have a little more homework to
do.
1. The upper case letter may not be the first letter in each word.
2. There may be more than one (continous) upper case letters in one
word.
I just wanted to find out if there is something already there in python
built-in functions, modules. Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top