You can define your own functions in Python with the
Python functions can act like mathematical functions
len(s), which computes the
s. In this example, values
s that are passed to the function
are called parameters to the
However, more generally, a Python function is just a container for some Python statements that do some task. A function can take any number of parameters, even zero.
Here is the general form of a Python function definition.
It consists of a
def statement, followed by
an indented block called the body
of the function.
arg1, ... ):
The parameters that a function expects are called arguments inside the body of the function.
Here's an example of a function that takes no arguments at all, and does nothing but print some text.
>>> def pirateNoises(): ... for arrCount in range(7): ... print "Arr!", ... >>>
To call this function:
>>> pirateNoises() Arr! Arr! Arr! Arr! Arr! Arr! Arr! >>>
To call a function in general, use an expression of this form:
param1, ... )
The name of the function is followed by a left
(”, a list of
zero or more parameter values
separated by commas, then a right parenthesis
The parameter values are substituted for the
corresponding arguments to the function. The value of
is substituted for
is substituted for
; and so forth.
Here's a simple example showing argument substitution.
>>> def grocer(nFruits, fruitKind): ... print "We have %d cases of %s today." % (nFruits, fruitKind) ... >>> grocer ( 37, 'kale' ) We have 37 cases of kale today. >>> grocer(0,"bananas") We have 0 cases of bananas today. >>>
So far we have seen some simple functions that take
arguments or don't take arguments. How do we define
len() that return a value?
Anywhere in the body of your function, you can write
return statement that terminates
execution of the function and returns to the
statement where it was called.
Here is the general form of this statement:
is evaluated, and its value is returned to the caller.
Here is an example of a function that returns a value:
>>> def square(x): ... return x**2 ... >>> square(9) 81 >>> square(2.5) 6.25 >>>
You can omit the
, and just use a
statement of this form:
In this case, the special placeholder value
None is returned.
If Python executes your function body and never
return statement, the
effect is the same as a
return with no
value: the special value
Here is another example of a function that returns a value. This function computes the factorial of a positive integer:
The factorial of
, is defined as the product of all the integers from 1 to
For example, 4! = 1×2×3×4 = 24.
We can define the factorial function recursively like this:
greater than 1,
! = n × (n-1)!.
And here is a recursive Python function that computes the factorial, and a few examples of its use.
>>> def fact(n): ... if n <= 1: ... return 1 ... else: ... return n * fact(n-1) ... >>> for i in range(5): ... print i, fact(i) ... 0 1 1 1 2 2 3 6 4 24 >>> fact(44) 2658271574788448768043625811014615890319638528000000000L >>>