Introduction to Programming Week 3


Part 1: What is a Function?

A function in Python is a block of code that performs a task. In programming terminology, functions aren't used, they're called. If necessary, functions can take input in the form of parameters, and return output.

Functions are used to simplify coding, by allowing different parts of a program to share code (they could both call the same function), and by abstracting away implementation details (for example, you can use Python's built-in square root function without needing to know how it's implemented).

The general syntax for a function call is

result = function(parameter1, parameter2)

A function might have any number of parameters, which are given in parentheses after the function name and separated by commas. However, in general, functions will have at most one output, which in the code above would be stored in the variable result.

We've already seen a couple examples of functions, including the print function and input function.

Part 2: More Functions

The len function returns the length of a string or sequence, and round(x,n) rounds the float x to n decimal places. The max function returns the "largest" of its inputs. For numbers the behavior is as you would expect, while for strings it returns the string that would come latest in a dictionary.

Functions can be combined in complex expressions, with the output of one or more functions serving as input to others. This is called composition.

Part 3: Modules

See module (Python).

Part 4: Our Own Functions

Of course, there's more to programming than using the functions built in to Python. We can also define our own functions with the reserved word def, followed by the name we chose for the function, and the names of any parameters in parentheses, separated by commas. Finally, the last character of that line should be : (a colon), to signal to Python that the body of the function follows.

Python uses indentation to distinguish between different blocks of code, so after the first def line every line of the function should be indented. The semi-official standard is four spaces, although you could technically use any amount so long as you're consistent.

The first line in the body of any function should always be a special type of comment called a docstring, which should describe what the function does. Docstrings are delimited by three quotation marks, either double quotes ("""this is a docstring""") or single quotes ('''this is also a docstring'''). Docstrings are what Python looks for when you use the help function, so if you call help on your function Python will return the docstring for that functions.

Finally, the indented lines after the docstring make up the body of the function. Functions can have any number of lines, the end of a function is defined by the end of the indentation.

Functions that will produce output need a return statement. The expression following the word return will be the output of the function. Functions can only return once, so as soon as the return statement is executed the function stops. Hence, return statements are usually the last line of a function.

For example, the following is a very simple function, that returns a number five more than its input:

def addFive(x):
    """addFive(num) -> num
    Adds five to the parameter"""
    return x+5

Note that variables created within a function are local to that function. They're destroyed when the function exits, and can't be referenced by other parts of the program. The scope of a variable is what parts of the program have access to it. See the transcript for examples of some errors that may occur if a programmer tries to access variables from the wrong scope.

Internally Python treats functions as any other type of data, so one unusual feature of Python is that functions can be assigned to variables, and passed as parameters to other functions.

See Also

Invalid username
Login to AoPS