Lesson 8 of 14 · 10 min
Writing Reusable Functions
In an earlier lesson you worked out the GC content of a DNA sequence by counting bases and doing the maths directly in your code. If you have ten sequences to check, copying that code ten times is slow and easy to get wrong. A function lets you write the recipe once, give it a name, and reuse it as many times as you like.
Defining a function
def gc_content(seq):
"""Return the GC content of a DNA sequence as a percentage."""
gc = seq.count("G") + seq.count("C")
return gc / len(seq) * 100The word def starts the definition, and gc_content is the name we chose for the function. The seq inside the brackets is a parameter, which is a placeholder for whatever sequence we hand in later. The triple-quoted line just below the def is a docstring, a short human-readable note that describes what the function does. Inside the body, seq.count("G") counts how many times the letter G appears, len(seq) gives the total number of bases, and return sends the final percentage back to whoever called the function.
dna = "ATGCGCGC"
print(gc_content(dna))75.0
Functions with more inputs
def count_base(seq, base):
"""Count how many times one base appears in seq."""
return seq.count(base)A function can take more than one parameter. Here count_base takes two: the sequence to search and the single base to look for. Once both functions are defined, you can call them on any sequence without rewriting the logic. The real payoff shows up when you loop over several sequences, because the same two function calls handle all of them.
sequences = ["ATGC", "GGGGCCCC", "AATTAATT"]
for seq in sequences:
print(seq, gc_content(seq), count_base(seq, "A"))ATGC 50.0 1
GGGGCCCC 100.0 0
AATTAATT 0.0 4
Try it yourself: Following the same pattern as gc_content, write a new function called at_content(seq) that returns the percentage of A and T bases. Call it on the sequence "AATTAATT", then check that gc_content("AATTAATT") and at_content("AATTAATT") add up to 100.