2.2 Coding the other functions
We are not done yet. With main() finished, we now have to fill out the program with the auxiliary functions that were called in the course of main().
valid_digit()
valid_string()
valid_table()
query()
The other functions must be inserted before the main() function is called, otherwise Python will throw a NameError.
valid_digit() and valid_string()
The first three functions should validate input as:
digital, alpha character string, or as a valid number on the table menu
presented to the user. If the input does not check out, then each should
call query() to ask the user for new input, providing the type
of valid input required as an argument with the value input by the
user. The first two require only the value to be validated. They
therefore look like this:
def valid_digit(value):
if value.isdigit() is not True:
value = query(value, "digit")
else:
value = value
return value
def valid_string(value):
if value.isalpha() is not True:
value = query(name, "alpha")
else:
value = value
return value
valid_table()
To validate the table selection, you will remember that we passed the number of the user's selection and the table names to valid_table(). This function compares the user's selection to the number of tables available and calls query() if there is a problem. The function is therefore coded as follows:
def valid_table(choice, tables):
valid_choice = valid_digit(choice) # Check whether the choice is a valid number
valid_choice = int(valid_choice)
while 0 <= valid_choice <= len(tables) : # Ensure the choice is among the valid options
print "Your selection is outside the bounds of possible choices."
valid_choice = query(valid_choice, "digit")
return valid_choice
query()
The function query() uses an if...elif...else structure to alert the user to the malformed data, asks for new input, and validates it. It therefore calls valid_digit() and valid_string() as necessary for the last task. Querying and testing is of two kinds: digit and alpha.
Within the present program, only these two are called, but there is a
chance that this function could be called wrongly from another Python
program. Therefore, we try to fail softly by returning 1 if the wrong argument is passed for type.
def query(value, type):
if type == "alpha":
print "The value you entered ('%s') is not correct. Please enter a valid value." %(value)
new_value = raw_input("New value: ")
valid_string(new_value)
return new_value
elif type == "digit":
print "The value you entered ('%s') is not correct. Please enter a valid value." %(value)
new_value = raw_input("New value: ")
valid_digit(new_value)
return new_value
else:
## if type is neither "alpha" nor "digit"
return 1