[Tutor] while with function

alan.gauld@bt.com alan.gauld@bt.com
Mon Nov 18 11:54:02 2002


> I split the functions because it seemed to me I *had* two functions.
> add() allows input for an address book; 

OK, so in that case I'd expect the function look like this:

def add(entry, add_book):....

> get_list() allows me to repeatedly (if necessary)  
> display the list of variables and make corrections 

The interesting phrase here is "*the* list", not "a list".

If a function is specific to a single list then it maybe 
shouldn't stand alone - ideally it should be a method of 
a class binding data and function together...

Of course you could make it generic by passing a list 
of names, prompting for a value for each and returning 
a dictionary keyed by name....

def get_values(namelist):
    values = {}   
    for name in namelist:
      val = raw_input(name+'? ')
      values[name] = val
    return values

But this is limited to returning string values.
If you passed in a list of name,type tuples then you 
could do the conversion there too but then the usability 
of your function becomes a bit strained...  

A better idea might be to get the data required for a 
single entry, in which case the function might be called 
get_entry and reurn the whole group of data as a tuple.

def get_entry():
   try:
       ....
       return (s_name, f_name, phone, etc....)
   except: return None

That way there is no need to couple the two functions 
together since the add entry function call becomes:

add_entry(get_entry(), addressBook)

Or you have a single while loop outside the 
functions like so:

while 1:
  entry = get_entry()
  if not entry: break
  else add_entry(entry, addressBook)

Untangling the dependencies between functions is good 
design practice (with practice having both meanings here!)

HTH,

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld