← All concepts

Lecture 4

Functions

A function packages a few lines under a name, so you can run them again with different inputs.

def, parameters and return

def starts a function. The names in brackets are parameters; the values you pass in the call are arguments. return hands a result back to the caller and ends the function.

def gc_content(seq):
gc = seq.count("G") + seq.count("C")
return gc / len(seq)
print(gc_content("ATGC"))

Output

0.5

print is not return

A function without return hands back None. Printing inside a function shows a value, but the caller cannot use it.

def shout(x):
print(x.upper())
result = shout("hi")
print(result)

Output

HI
None

Defaults and named arguments

A default value is used when the argument is left out. Arguments can also be passed by name, in any order.

def dilute(c, factor=10):
return c / factor
print(dilute(50), dilute(50, 5), dilute(factor=2, c=50))

Output

5.0 10.0 25.0

Going further

From the advanced notebook — this is what the advanced questions test.

Returning several values

return a, b hands back a tuple; unpack it straight into two names.

def stats(values):
return min(values), max(values)
lo, hi = stats([4, 9, 2])
print(lo, hi, stats([1, 5]))

Output

2 9 (1, 5)

Local variables

Variables created inside a function are local: they disappear when it ends and never change a variable with the same name outside.

x = 5
def change():
x = 99
return x
print(change(), x)

Output

99 5

Docstrings

A string on the first line of a function documents it; Python stores it as __doc__, and help() shows it.

def count_cells(image):
"""Count the cells in an image."""
return 0
print(count_cells.__doc__)

Output

Count the cells in an image.