[Tutor] More Function Questions (Joseph Q.)

Alan Gauld alan.gauld at freenet.co.uk
Mon Apr 18 01:47:51 CEST 2005

> So what do you use the
> def bar(x, y):
> return x + y
> bar(4, 5)
> functions for? (I just need a simple example)

As an illustration of what a functionlooks like bar is 
fine but as it stands it's not a great example of a 
real function for several reasons:
1) The name is not descriptive of what it does
2) The body is shorter to write than the function call

Functions serve two useful purposes, the first is to make you 
code easier to read by replacing several lines of primitive code 
to a readable and meaningful description. This is known as 

The second purpose is to cut down the amount of typing you do
(and help make maintenance easier too). This is because the 
function turns what could be a long sequence of instructions 
into a short function name.

Let's look at a slightly more realistic example:

def average(listOfNums):
   total = 0
   if not type(listOfNums) == list:
      raise TypeError
   for num in listOfNums:
      if not type(num) == int: 
         raise TypeError
      total += num
   return total/len(listOfNums)

Now, it's much easier to type

print average([1,3,4,6,8,9,12])
print average([6,3,8,1,9])

than to try to  retype the code inside the function both times
(and any other time you need to average a list...) and in 
addition your code is much easier to read - 'average' gives 
some idea of what to expect in the result.

BTW You could shorten the function slightly using a list 
comprehension but the basic need for type checking etc is 
still valid and the naming/abstaction issue also still holds.


Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list