Chapter 6. Functions

Table of Contents

6.1. Some definitions
6.2. Operators
6.2.1. Order of evaluation
6.2.2. Object comparisons
6.2.3. . (dot) operator
6.2.4. String formatting
6.3. Defining functions
6.4. Passing arguments to parameters
6.4.1. Reference arguments
6.4.2. Passing arguments by keywords
6.5. Default values of parameters
6.6. Variable number of parameters

6.1. Some definitions

Function

A function is a piece of code that performs a specific sub-task. It takes arguments that are passed to parameters (special place holders to customise the task) and returns a result.

Operator

An operator is a function that takes one or two arguments and that is invoked by the following syntax: arg1 op arg2.

Note

Operators are defined by special methods in Python:

>>> "atgacta" + "atgataga"
'atgactaatgataga'

>>> "atgacta".__add__("atgataga")
'atgactaatgataga'	
	      

Procedure

The terms "function" and "procedure" are often used as if they would be interchangeable. However, the role of a procedure is not to return a value, but to perform an action, such as printing something on the terminal or modifying data (i.e something which is sometimes called "doing side-effects" in functional programming parlance).

Strictly speaking, the definition of a function is the same as the mathematical definition: given the same arguments, the result will be identical, whereas the behaviour of a procedure can vary, even if the task is invoked with the same arguments.

In Python, as in most programming languages, there is no difference in function and procedure definitions or calls. But if no return value is specified or if the return value is empty, then the empty object None is returned. It is important to know if the called function returns a result.

Example 6.1. Differences between functions and procedures

>>> enznames = [ 'EcoRI', 'BamHI', 'HindIII' ]

>>> enznames.index('BamHI')
1

>>> enznames.reverse()                                                    (1)
>>> enznames
['HindIII', 'BamHI', 'EcoRI']
		
1

The reverse() method executes an inversion of the list enzname. It does it inplace, and does not construct a new list.

Method

A method is a function or procedure that is associated with an object. It executes a task an object can be asked for. In Python it is called via the . (dot) operator.

>>> dna='atgctcgctgc'
>>> dna.upper()
'ATGCTCGCTGC'