[Tutor] validating user input for cli app
Steven D'Aprano
steve at pearwood.info
Thu Oct 7 12:42:08 CEST 2010
On Thu, 7 Oct 2010 12:09:31 pm Rance Hall wrote:
> I know how to write the if statements to decide if the data entered
> is valid or not, but I need a way to deal with what happens when it
> is NOT valid.
>
> I'd like to be able to just ask the question again, and re-validate
> the new input or offer a "press q to quit" option
Here is one way:
def ask_again(prompt, condition):
if not prompt.endswith(" "):
prompt = prompt + " "
while True: # loop forever
response = input(prompt) # use raw_input in Python 2.x
response = response.strip()
if response.lower() == 'q':
raise SysExit('user quit')
if condition(response):
return response
else:
print("I'm sorry, that is invalid. Please try again.")
And an example of it in use:
>>> ask_again("Enter two letters ", lambda s: len(s) == 2)
Enter two letters abcd
I'm sorry, that is invalid. Please try again.
Enter two letters a
I'm sorry, that is invalid. Please try again.
Enter two letters xy
'xy'
>>>
>>> ask_again("Please enter a number", str.isdigit)
Please enter a number fg
I'm sorry, that is invalid. Please try again.
Please enter a number yu
I'm sorry, that is invalid. Please try again.
Please enter a number 56
'56'
>>>
You can build in as much intelligence as you want, depending on how much
effort you care to put into it. For instance, you might like to
escalate the error messages:
"Please try again."
"I'm sorry, your answer is incorrect, please try again."
"You must enter a number like 42 or 75. Please try again."
"Hey dummy, don't you know what a number is?"
although of course this requires more programming effort.
And naturally the condition functions can be as simple, or as
complicated, as you need.
--
Steven D'Aprano
More information about the Tutor
mailing list