[Tutor] validating user input for cli app

Rance Hall ranceh at gmail.com
Thu Oct 7 03:09:31 CEST 2010

I have the following scenario, during a cli app a function is called
whose purpose is to get enough info from user to create a database

Clearly the input values need to be validated.  How do I handle the
situation where validation fails, but the answer to the question is

so far I have something like this

def moduser(clientid):
   if not len(clientid) == 0:
       client = getclient(clientid) # this is a database call to get
the existing record for modification, entering a zero length string
assumes its a new record instead of a mod.
       if len(client) == 0:
           print("client not found")
            # more code here to wait a second and then go back to the
menu selection that started this function.
       clienttype = input("Enter client type, there are two choices,
Commercial or Individual\n choose C or I ")
       ******* My question is about what goes here *******

This is where life gets confusing, if clienttype is not a c or an I
(case insensitive) then I have to ask the question again or offer a
way out of my function
There are several questions being asked here, about name, address,
etc., each element has its own validation rules, and each question
needs and answer

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

q to quit is no big deal, but it doesn't make sense to ME to clutter
up the code with a whole set of functions that each just ask one
question and return a value.  Especially since when my app is done
there will likely be over a hundred of these type of one or two line
functions. the names will be impossible to keep up with.  Whats more,
debugging and future upgrades will be a major PITA.

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

Based on my Internet research it looks like the only way you get GOTO
capability is with an April Fools joke in 2004.

So how do you do this?


More information about the Tutor mailing list