[Tutor] Truckers Log....Me Again [functions]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 21 Jan 2002 02:07:14 -0800 (PST)


[some code cut]
> while  add_days in ( 'y','Y', 'yes','YES', 'ok', 'OK', 'yeah', 'YEAH' ) : 
[more code cut]
> if add_days  in ( 'n', 'N', 'no', 'NO' ):


One suggestion: it might be nice to make up a separate function that says
if an input is "yes"-ish or "no"-ish.  Here's a function that might help:

###
def isYes(answer):
    return answer in ( 'y','Y', 'yes','YES', 
                       'ok', 'OK', 'yeah', 'YEAH' )
###


If we have this definition for isYes(), we can say things like:

###
while isYes(add_days):
    ...
###

to see if the user respons favorably to us.  It's not really a matter of
saving space, since we end up actually typing a little more to write a
function definition.  Instead, it's more for clarity's sake, so that later
on, we can look at isYes() and say "Ah, so that's what it means for the
user's input to be a Yes."



Ok, that does sound picky.  I mean, it's just one line, and its action is
so limited!  Hmmm... I'd better pick another example.  Here's another
section that might be amendable to this function approach:

> print  ' \n', '='*20,'RECAP', '=' *33,' \n', '=' * 60 
> last_7_days = reduce( operator.add,history_list[ -7: ] )
> print ' Total hours on duty last 7 days    : ',  last_7_days
> print ' Total hours available tomorrow     : ' , 70 - last_7_days
> print ' Total hours on duty last 8 days    : ' , last_7_days +
>                                                  history_list [ -8 ]

With functions, it's possible to group this set of statements into a some
imaginative name like...errr... "printSummary()".  I'm sorry, it's late,
and I'm too sleepy to think of a good function name... *grin* If we have
some function like printSummary(), we'd be able to write the code to read
like:

###
print ' You have entered ' , len(history_list), ' Days ', ' \n' 
print '  ' ,history_list, '\n' , '=' * 60, '\n'
add_days = raw_input( 'Do you want to add more days to recap ?  y/n   : ')
printSummary()
###

It's very nice to be able to print out a whole summary of the timesheet
with a single word.  In a sense, functions almost act like paragraphs
because they group related statements together, and by writing a function,
we're almost saying that these set of instructions work in cooperation
toward a common goal.


Functions also allow us to avoid cut-and-pasting old code, but that's a
side benefit.  One of the main reasons we write functions is because they
allow us to group a disparate collection of actions with a good name.  
For some strange reason, this ability to group-and-name often helps humans
deal with simple ideas as well as the complex.


Hope this helps!