The best way to manage the
development of large programs
is to construct them from smaller
parts. This technique is called
divide and conquer.
and another subpart to handle data
output.
These subparts or subprograms are
given a name and are considered
as a separate entity. They are known
as functions.
as many times as you wish in the same program.
You may use the same function in different programs.
You may package similar functions into a single module for ease of
use.
*
Easy to debug
*
Easy to understand
*
Easy to change
Python has a huge selection
of built-in functions ready for immediate use.
These are packaged into modules according to their purpose.
The math module is part of Python's standard
library.
Python's standard library is a
collection of modules
providing functions such as
math calculations,
string (text) manipulations,
web programming,
graphics programming,
as well as many other operations.
Python's standard library is
provided
as part of the core Python language
and is located in the library folder
(\lib)
of the Python installation.
The math module contains functions
that allow programmers to perform
certain mathematical calculations,
for example,
to find the square root of a number.
Using Python's math Functions
To use a built-in function
that is defined in a module,
a program must first import the
module,
using the keyword import, e.g.
import
math
See:
http://www.python.org/doc/2.3.5/lib/module-math.html
Calling a built-in function
After the module has been imported,
the program can invoke (call) functions
in that module
by using the module's name, followed
by a dot (.)
and the function's name followed by
parentheses...
modulename.functionname()
import
math
print
math.sqrt(16)
print
math.sqrt(16.5)
# see
program 06-01.py
# of www.annedawson.net/PythonPrograms.txt
Objects sent to a function
Any object or objects sent to a function
are known as the argument(s) of the function,
and are placed between the brackets after the function's
name.
print
math.sqrt(16)
In the example above, 16 is the argument.
Depending on how it is defined,
a function may have zero, one or many arguments.
import
math
print math
print
dir(math)
# see
program 06-02.py
# of www.annedawson.net/PythonPrograms.txt
Python's Always-Available Built-in Functions
See:
http://www.python.org/doc/2.3.5/lib/built-in-funcs.html
The link above lists all the
always-available Python functions in alphabetical order.
Note: you do not need to use an import statement to use
these functions.
Some Always-Available Functions
This is a list of always-available functions
that we've used in this course so far:
float (x)
id (object)
int (x)
range ([start,]
stop[, step])
raw_input ([prompt])
str (object)
type (object)
6.3 Programmer-defined Functions
Python's standard library modules
simplify the job of the programmer,
because programmers only have to write new functions
if a built-in function isn't sufficient for the job in hand.
Creating and Using a Programmer-Defined Function
The Function Definition
The syntax of a function definition is:
def function-name( parameter-list ):
statements
Note that the
statements must be indented.
def is one of Python's 29 keywords.
The function definition does not execute the function body.
The function body (block of statements) is executed only
when the function is called.
An Example Program containing a Programmer-Defined Function
def cube( y ):
return y * y * y
# prints the cube of numbers 1 to
5
for x in range(1,6):
print cube(x)
print "last value of x
is:",x
# see
program 06-03.py
# of www.annedawson.net/PythonPrograms.txt
Note that the
value of x is not changed by the function.
Placement of Function Definitions
A Python program may have one or more function definitions,
but the definitions must be placed at a position in the code
before the corresponding function call statement.
We usually place function definitions at the top of the
code,
after the heading comments.
An Example Program containing
Two Programmer-Defined Functions
def cube( y ):
return y
* y * y
def doubleIt ( z ):
return 2
* z
print "1 to 5 cubed"
for x in range(1,6):
print
cube(x),
print
print
print "1 to 5 doubled"
for x in range(1,6):
print
doubleIt(x),
# see
program 06-04.py
# of
www.annedawson.net/PythonPrograms.txt
Saving Programmer-Defined Functions in a Separate File (Module)
def cube( y ):
return y * y * y
def doubleIt ( z ):
return 2 * z
# see
program myFunctions.py
# of www.annedawson.net/PythonPrograms.txt
Functions saved in a separate file (module)
can be called from another program
import myFunctions
print "1 to 5 cubed"
for x in range(1,6):
print myFunctions.cube(x),
print
print
print "1 to 5 doubled"
for x in range(1,6):
print myFunctions.doubleIt(x),
# see
program 06-05.py
# of www.annedawson.net/PythonPrograms.txt
Python automatically creates
a compiled version of function files
This means that they don't need to be recompiled into byte
code
every time they're used, only when they're changed.
This significantly speeds up execution time of programs
which use functions.
Note the compiled version of the myFunctions.py file is myFunctions.pyc.
return sends a result object
back to the caller
When a function is called, the caller stops execution
until the function has finished and returns control to the
caller.
Functions that compute a value send it back to the caller
with a return statement; the
returned value
becomes the result of the function call.
All of our example functions so far have returned a value.
The return statement
The Python return statement can
show up
anywhere in a function body;
it ends the function call and sends a result back to the caller.
The return statement is
optional
The return statement is optional;
if it's not
present,
the function ends
at the last line in the function body. . .
def times(x):
for i in
range(1,11):
print "%d x %d =
%d" % (i, x, i * x)
# see
program 06-06.py
# of www.annedawson.net/PythonPrograms.txt
A function can have many return statements
A Python function can contain several return statements.
In the case where a function can contains several return statements,
execution of the function ends at the first return statement
encountered. . .
def division(x,y):
if (y == 0):
print "division by
zero not allowed"
return
else:
" returning %f divided by %f " % (x,
y)
return x / y
# see program
06-07.py
# of www.annedawson.net/PythonPrograms.txt
The absent or empty return statement
If the return statement is
absent from a function,
or it's executed on a line on its own,
then Python automatically returns the None object,
but it is generally ignored.
The None object
The None object is a Python value that represents null
- indicating that
no value (object) was created.
None has a numerical value of zero,
thus evaluates to
false in boolean expressions.
# see program
06-07.py
# of www.annedawson.net/PythonPrograms.txt
A function with no arguments
Functions defined
without a parameter list are called with no arguments. . .
def greeting():
print
"Hello out there!"
greeting()
greeting()
greeting()
# see
program 06-08.py
# of www.annedawson.net/PythonPrograms.txt
A Boolean function
A Boolean
function is one which returns either true or false.
The following
example program includes a boolean function.
def isPositive(x):
if (x
>= 0):
return 1 # 1 is
true
else:
return 0 # 0 is false
# see
program 06-09.py
# of www.annedawson.net/PythonPrograms.txt
A function can operate on objects of different types
As with everything
else in Python, there are no type constraints on functions.
We can pass
arguments of any type to a function and return any kind of object.
def doubleIt(x):
return (2
* x)
y = 3
print doubleIt(y)
z = "Spam "
print doubleIt(z)
# see
program 06-10.py
# of www.annedawson.net/PythonPrograms.txt