Function Definition: The def and return Statements

We create a function with a def statement. This provides the name, parameters and the suite of statements that creates the function's result.

def name ( 〈 parameter ...〉 ): suite

The name is the name by which the function is known. The parameters is a list of variable names; these names are the local variables to which actual argument values will be assigned when the function is applied. The suite (which must be indented) is a block of statements that computes the value for the function.

The first line of a function is expected to be a document string (generally a triple-quoted string) that provides basic documentation for the function. This is traditionally divided in two sections, a summary section of exactly one line and the detail section. We'll return to this style guide in the section called “Functions Style Notes”.

The return statement specifies the result value of the function. This value will become the result of applying the function to the argument values. This value is sometimes called the effect of the function.

return expression

Let's look at a complete, although silly, example.

def odd( spin ):
    """Return true if this spin is odd."""
    if spin % 2 == 1:
        return True
    return False

We name this function odd, and define it to accept a single parameter, named spin . We provide a docstring with a short description of the function. In the body of the function, we test to see if the remainder of spin /2 is 1; if so, we return True. Otherwise, we return False.