As we saw in Section 3.9, functions are very useful tools for making your programs more concise and modular.
The libraries provide a useful range of facilities but a programmer will often want or need to write their own functions if, for example, one particular section of a program is to be used several times, or if a section forms a logically complete unit.
Functions must be defined before they are used, so we generally put the definitions at the very top of a program. Here is a very simple example of a function definition that returns the sum of the two numbers it is passed:
>>> def addnumbers(x, y):
sum = x + y
return sum
>>> x = addnumbers(5, 10)
>>> print x
15
The structure of the definition is as follows:
def statement: this consists of
the word def, the name of the function, followed by parentheses
containing the names of the parameters passed as they will be referred
to within the function. 3.12.
return statement. This is the result the function
will return to the program that called it. If your function does not
return a result but merely executes some statements then it
is not required.
If you change a variable within a function that change will not be reflected in the rest of the program. For example:
>>> def addnumbers(x, y):
sum = x + y
x = 1000
return sum
>>> x = 5
>>> y = 10
>>> answer = addnumbers(x, y)
>>> print x, y, answer
5 10 15
Note that although the variable x was changed in the function,
that change is not reflected outside the function. This is because the
function has its own private set of variables. This is done to minimise
the risk of subtle errors in your program
If you really want a change to be reflected then return a list of the new values as the result of your function. Lists can then be accessed by offset in the same way as arrays:
>>> def addnumbers(x, y):
sum = x + y
x = 100000
return [sum, x]
>>> x = 5
>>> y = 10
>>> answer = addnumbers(x, y)
>>> print answer[0]
15
>>> print answer[1]
100000
A fuller discussion of the relationship between variables used in functions and in the main program is discussed in Section 4.4, ``Scope''.
x and y in this case). The actual
parameters (5 and 10 in the example) are assigned to
the formal parameters when the function is called. Parameters are also
often referred to as arguments