A function groups a block of code under a name so it can be reused.
def gc_content(sequence):
gc = sequence.count("G") + sequence.count("C")
return gc / len(sequence)
print(gc_content("ATGGCC"))
A function without a return returns None.
Arguments
Arguments can be passed by position or by name. Parameters with a default value may be omitted.
def report(gene, depth, minimum=30):
status = "pass" if depth >= minimum else "fail"
return f"{gene} {depth} {status}"
print(report("TP53", 120))
print(report("TP53", 25))
print(report("TP53", 25, minimum=20))
print(report(gene="EGFR", depth=45))
Mutable defaults
A default value is created once, when the function is defined, not each time it is called. A mutable default is therefore shared between calls.
def add_bad(gene, collected=[]):
collected.append(gene)
return collected
print(add_bad("TP53"))
print(add_bad("BRCA1"))
Use None instead:
def add_good(gene, collected=None):
if collected is None:
collected = []
collected.append(gene)
return collected
print(add_good("TP53"))
print(add_good("BRCA1"))
Returning several values
A function can return a tuple, which unpacks on assignment.
def bounds(values):
return min(values), max(values)
low, high = bounds([30, 12, 45])
print(low, high)
Task
Write summarise(depths). It receives a list of integers and returns a tuple
of (count, minimum, maximum, mean). Round the mean to 2 decimal places.
Return (0, 0, 0, 0.0) for an empty list.
Test cases · 3
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | 30 12 45 7 | (4, 7, 45, 23.5) |
| 2 | stdin | 10 | (1, 10, 10, 10.0) |
| 3 | stdin | · | (0, 0, 0, 0.0) |
Hints · 2
01Hint
Handle the empty list first, before calling min() or max().
02Hint
round(total / count, 2) gives the rounded mean.