Next / Previous / Contents / TCC Help System / NM Tech homepage

8.def: Defining functions

You can define your own functions in Python with the def statement.

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.

def name ( arg0, arg1, ... ):
    block

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:

name ( param0, param1, ... )

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.
>>> 

8.1.return: Returning values from a function

So far we have seen some simple functions that take arguments or don't take arguments. How do we define functions like len() that return a value?

Anywhere in the body of your function, you can write a 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:

return expression

The expression 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 expression, and just use a statement of this form:

    return
    

    In this case, the special placeholder value None is returned.

  • If Python executes your function body and never encounters a return statement, the effect is the same as a return with no value: the special value None is returned.

Here is another example of a function that returns a value. This function computes the factorial of a positive integer:

The factorial of n, denoted n!, is defined as the product of all the integers from 1 to n inclusive.

For example, 4! = 1󫎿4 = 24.

We can define the factorial function recursively like this:

  • If n is 0 or 1, n! is 1.

  • If n is greater than 1, n! = 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
>>>