[Tutor] validating user input for cli app
alan.gauld at btinternet.com
Thu Oct 7 15:45:56 CEST 2010
"Rance Hall" <ranceh at gmail.com> wrote
> 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
Thats what loops are for...
> The old GOTO syntax that everybody hates was ideal for this type of
> thing, if validation fails, just goto the question again and re-ask
Nope, it wasn't ideal and thats why it was removed from most
Structured Loops are better.
> So how do you do this?
You either write a loop that cycles until you get valid input or you
could create a heirarchy of Field classes(*) that know how to request
and validate it. If the data is invalid they request input again -
takes us back to loops...
(*) Or even a single Validator class that takes a validation function
an input parameter....
One possible loop would look something like:
a = b = c = None
dataOK = False
while not dataOK:
if not a:
a = raw_input('Enter a: ')
if not validA(a):
a = None
if not b:
b = raw_input('Enter b: ')
if not validB(b):
b = None
if not c:
c = raw_input('Enter a: ')
if not validC(c):
c = None
And since the input blocks are repeated you could even
convert them to a function if you really cared or had a lot
Author of the Learn to Program web site
More information about the Tutor