Datasheet
Chapter 1: A Python Primer
11
Functions
In many ways, the principle behind a function is analogous to turning on a TV. You don ’ t have to
understand all the electronics and communications technology behind getting the TV signal to your
receiver in order to operate the TV. You do have to know some simple behaviors, however, such as how
to turn it on, where the volume switch is, and so on. In a similar fashion, a function gives the program an
interface through which it can run program code without knowing the details about the code being run.
Defining a Function
You define a function in Python with the following simple syntax:
def functionName(paramenter1, parameter2=default_value):
< code block >
return value (optional)
Note two elements in the preceding example:
Parameters — As you can see, parameters can simply be a variable name (making them required
as part of the function call), or they can have a default value, in which case it is optional to pass
them in the function call.
The return statement — This enables the function to return a value to the code that called it. The
nice thing about this is that you can run a function and assign its output to a variable.
Here ’ s an example of a function definition:
> > > def getname(name):
return name + “ is very hungry”
> > >
Calling a Function
To call a function, simply enter the function name with the function signature:
functionName(paramenter1, parameter2)
If a parameter has a default value in its definition, then you can omit that parameter when you call the
function, and the parameter will contain its default value. Alternately, you can override the default value
by entering the value yourself when you call the function.
❑
❑
c01.indd 11c01.indd 11 6/2/08 12:03:11 PM6/2/08 12:03:11 PM