Functions

How do I write a function?

A function is a fragment of code that you may want to execute over and over again. You can also think of it as a mini-machine that takes a few things, works with them and gives back some other things. Writing a function allows you to break up your code into small chunks so that you can tackle each chunk separately ("divide and conquer"). There are two separate problems in writing functions:

  1. What exactly is the function supposed to do? (the function specification)
  2. How exactly should it do that?

Function specifications

Remeber that a function is essentially a mini-machine, taking some things and giving back others? A function specification dictates what things the function takes (parameters) and what it gives back (returns).

As with if statements, this situation is also common in real life. For example, making a sandwich involves taking some things (bread, butter, filling) working with them and returning something else (a sandwich). Sitting an exam involves taking some thing (an exam paper) working with it (answering the questions) and returning something else (a set of answers). Note that in both these cases, the way the function behaves will depend on the values given to the parameters - these values are called arguments. If you're making a sandwich with tomato, you have to chop it whereas tuna needs to be taken out of the tin. Similarly, functions in programming can be made to behave differently based on the arguments.

Here is a table describing these function specifications:

Function name Description Parameters Returns
makeSandwich() makes a snack bread, butter, filling sandwich
sitExam() sits an exam exam paper answer sheet

In programming, function specifications have to work with [[[glossary|#type types]]] that the language will understand, but the principle is exactly the same. Here are some example function specifications.

Function name Description Parameters Returns
multiply() multiplies two integers integer, integer integer
mean() finds the mean of a list of integers list of integers integer
ncopies() returns n copies of a string stuck together string, integer string

Implementing functions

The first step to implementing a function is to be sure you understand the function specification How many parameters are there? What type? What are we returning? What type? The implementation of the function then becomes using the parameters to the function to arrive at what needs to be returned.

As for the syntax for expressing the functions themselves, the easiest way is to look at examples. Look carefully at the keywords ("def") the indenting and the way that parameters have been arranged, as well as the use of the return statement. Then try to apply this method to your own functions.

Below are implementation examples. These examples are very simple, and not all of them would be appropriate to implement as functions (multiply, for example). These are here to show the relationship between parameters and return values, and how a function implementation is related to its specification. More complex examples are available here

Multiply:

def multiply(x, y):
    return x*y

example usage:

>>> multiply(4,5)
20

Ncopies:

def ncopies(mystring, num):
    return mystring * num

example usage:

>>> ncopies("la", 3)
'lalala'

Mean:

def mean(listofint):
    sum = 0
    for i in listofint:
        sum = sum + i
    return sum/len(listofint)

example usage:

>>> mean([2,3,4,5,6])
4

The return statement

One of the problems people have when first implementing functions is understanding the purpose of the "return" statement. A function does not need to have a return statement - it might just contain some "print" statements and not need to give back anything after it has finished working. However, it is important to know when you should use a return statement and how.

The return statement is like asking the "mini machine" to give back what it has been working on. Without a return statement, the sandwich function makes the sandwich and leaves it in the kitchen, without giving it to you to eat. Using return statements, a function can be used as part of expressions to build up more complex code.

For example, consider the function square:

def square(x):
    return x*x

With this function defined, we are able to write code like this:

pi = 3.1415
r = 5
circlearea = pi * square(r)

How to use functions

Beginner programmers often confuse how the return function allows them to get access to the value computed by the function. For example they might type:

def divisor(x,y):
    return x%y==0

divisor(4,6)

and wonder why this code doesn't do anything. The key to understanding this issue is the difference between an expression and a statement. A statement is a piece of code that changes the internal state of the program in some way whereas an expression just evaluates the current state of the program so:

3+x

is an expression, and doesn't actually *do* anything, whereas

y = 3+x

is a statement - it assigns the result of the expression into y. In the same way,

divisor(4,6)

is just an expression - on its own in a line like that, whatever value is returned by the function will not be used, just like 3+x. However, this value can be used as part of a statement, like this:

if divisor(4,6):
    print "yes, it divides!"

More help

There is more help all over the web. To start, try here, here and here.

Still no clue?

Add your question to the to-do list. Or ku.ca.alg.scd|szp#em liam.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License