Functions

Python has many functions. These have a name and a set of arguments, which must be enclosed in parentheses.

A few examples:


>>> print abs(-10)  # The function is 'abs'.  Its argument is -10.
10
>>>
# The functions are 'min' and 'max'.  They take an
# arbitrary number of arguments.
>>> max(3,6,8,2)
8
>>> min(3,6,8,2)
2
>>> 

# 'sum' takes 1 or two arguments
>>> sum([5, 10, 15])
30
>>> sum([5, 10, 15], 10)
40
>>> 

The list of Python's built-in functions are listed in the Python documentation. Many more functions are available in the modules.

You can make your own functions or redefine the built-in ones using the def statement. This is described in more detail in a later lecture.

Methods*

Methods are a special category of functions which are associated with a particular object. A method combines two operations:

String Methods


>>> seq = "AATGCCG"
>>> seq.lower()
'aatgccg'
>>> seq.count("A")
2
>>> seq.find("GC")
3
>>> seq.find("gc")
-1
>>> seq.replace("C", "U")
'AATGUUG'
>>> import string
>>> seq.translate(string.maketrans("ATCG", "TAGC"))
'TTACGGC'
>>> # Make the reverse complement
>>> seq.translate(string.maketrans("ATCG", "TAGC"))[::-1]
'CGGCATT'
>>> "This is some words separated by spaces.".split()
['This', 'is', 'some', 'words', 'separated', 'by', 'spaces.']
>>> "This is some words separated by spaces.".split("s")
['Thi', ' i', ' ', 'ome word', ' ', 'eparated by ', 'pace', '.']
>>> 

Special Methods

Some methods are used so often they have special syntax.


>>> s = "AATGCCGTTTAT"
>>> s[0]    # index
'A'
>>> s[1:4]  # slice from beginning to end
'ATG'
>>> s[:4]   # default beginning is position 0
'AATG'
>>> s[-1]   # index from the end
'T'
>>> s[-3:]  # default end includes the last character
'TAT'
>>> s[3:-3]
'GCCGTT'
>>> s[::2]  # the optional third parameter is the stride
'ATCGTA'
>>> s[::-1] # returns the string, reversed
'TATTTGCCGTAA'
>>> 

Swap the Values of Two Variables

Here's a simple way to swap the value of two variables in one step:


onions, potatoes = potatoes, onions

NOTE: The obvious alternative DOES NOT work:


onion = potatoes
potatoes = onions  # oops!

Here is a correct non-idiomatic alternative


tmp = onions
onions = potatoes
potatoes = tmp

Rotate the Values of Three Variables


onions, potatoes, turnips = potatoes, turnips, onions

This page based on Functions.
*Taken from Learning Python.


Andrew Dalke
Last modified: Thu Feb 12 17:06:26 SAST 2004