8 Defining Functions

Defining functions is easy:

def factorial(n):
    """a simple factorial function with no overflow protection"""
    if n:
        return n*factorial(n-1)
    else:
        return 1

Note that, like other code blocks, indentation is used to decide what belongs in the function body. Also note that Python allows recursive functions.

The string at the beginning of the function is called a ``doc string'' and contains documentation information on the function. It is available as the __doc__ attribute of the function, so print factorial.__doc__ will print the string for the example function. The doc string can have multiple lines and is by convention enclosed in triple quotes (which allow strings that extend across lines) even when it contains only a single line, as in the sample.

Python provides a great deal of flexibility in handling function arguments. Check books or references to see how to handle default values, keyword arguments and a variable number of arguments.

Questions or comments? Contact help@stsci.edu
Documented updated on 2004 Jun 1