Functions
Functions let you wrap reusable logic into a single named block. You define a function once and call it many times. This keeps your code organized and reduces copy/paste errors.
Save the Python blocks in page order as functions.py, then run
uv run python functions.py from your project directory. The examples use
the standard library. Python Type Annotations
explains the parameter and return annotations used here.
Download the English captions for this video.
Writing functions
Section titled “Writing functions”Basic function
Section titled “Basic function”Use the def keyword followed by a name and parameters. The return statement sends a value back to the caller.
def calculate_gc_content(sequence: str) -> float: """Calculates the GC content of a DNA sequence.
Args: sequence: A nonempty string containing only A, C, G, and T.
Returns: The fraction of G and C bases in the sequence.
Raises: ValueError: If the sequence is empty or contains another character. """ sequence = sequence.upper() if not sequence or not set(sequence) <= {"A", "C", "G", "T"}: raise ValueError("sequence must contain only A, C, G, and T") gc_count = sequence.count("G") + sequence.count("C") return gc_count / len(sequence)
print(calculate_gc_content("ATGCGATCGA"))0.5print(calculate_gc_content("AAATTTAAATTT"))0.0The triple-quoted string right after def is called a docstring. It describes what the function does. We use the Google style for docstrings throughout this project. More on that below.
The guard rejects an empty sequence before division. It also rejects ambiguous
bases such as N, because this example defines GC content over A, C, G, and T.
Default arguments
Section titled “Default arguments”You can give parameters default values. The caller can override them or leave them as is.
def label_significance( adjusted_pvalue: float, log2fc: float, alpha: float = 0.05, fc_threshold: float = 1.0,) -> str: """Label a gene using adjusted p-value and effect-size thresholds.
Args: adjusted_pvalue: P-value adjusted across the tested gene family. log2fc: The log2 fold change. alpha: Significance threshold. Defaults to 0.05. fc_threshold: Minimum absolute fold change. Defaults to 1.0.
Returns: "up" or "down" when both thresholds pass, and "ns" otherwise. """ if adjusted_pvalue < alpha and log2fc > fc_threshold: return "up" elif adjusted_pvalue < alpha and log2fc < -fc_threshold: return "down" else: return "ns"
print(label_significance(0.001, 2.5))upprint(label_significance(0.001, -1.8))downprint(label_significance(0.5, 3.0))nsYou can override defaults by name. This makes function calls easier to read.
print(label_significance(0.001, 0.5, fc_threshold=0.25))upThe caller supplies the adjusted p-value. This function applies a selection
rule after the statistical analysis. The label ns means that the rule did
not select the gene; it does not establish that the effect is zero.
See Multiple Testing for the adjustment.
Control how arguments bind
Section titled “Control how arguments bind”A function signature can require a name for an option while accepting its main
input only by position. In this filter, / ends the positional-only parameters
and * begins the keyword-only parameters. The caller must name minimum.
def retain_counts(counts: list[int], /, *, minimum: int = 1) -> list[int]: """Return counts that meet a named threshold without changing the input.
Args: counts: Nonnegative integer counts, supplied by position. minimum: Nonnegative count threshold, supplied by keyword.
Returns: A new list of retained counts in input order.
Raises: ValueError: If a count or the threshold is negative. """ if minimum < 0 or any(count < 0 for count in counts): raise ValueError("counts and minimum must be nonnegative") return [count for count in counts if count >= minimum]
read_counts = [0, 4, 12, 2]print("Default threshold:", retain_counts(read_counts))print("Named threshold:", retain_counts(read_counts, minimum=4))print("Original:", read_counts)try: retain_counts(read_counts, 4)except TypeError as error: print("Unnamed threshold rejected:", type(error).__name__)try: retain_counts(counts=read_counts, minimum=4)except TypeError as error: print("Named positional-only input rejected:", type(error).__name__)Default threshold: [4, 12, 2]Named threshold: [4, 12]Original: [0, 4, 12, 2]Unnamed threshold rejected: TypeErrorNamed positional-only input rejected: TypeErrorThese two TypeError exceptions occur during argument binding, before the
function body runs. A negative threshold instead reaches the body’s validation
and raises ValueError. Type annotations do not enforce either rule.
Use a keyword-only parameter when its name makes a call less ambiguous.
Positional-only parameters are useful when callers should not depend on a
parameter name. An ordinary parameter accepts either form, as alpha does in
label_significance.
Collect and unpack arguments
Section titled “Collect and unpack arguments”In a definition, *batches collects extra positional arguments into a tuple.
In a call, *batches expands a collection into separate positional arguments.
The two uses perform opposite operations.
def combine_counts(*batches: list[int]) -> list[int]: """Combine count batches into a new list.
Args: *batches: Count lists in the order they should appear.
Returns: Counts from every batch, preserving batch and element order. """ combined = [] for batch in batches: combined.extend(batch) return combined
batches = [[3, 5], [0, 8]]print("Separate arguments:", combine_counts(batches[0], batches[1]))print("Unpacked arguments:", combine_counts(*batches))print("No batches:", combine_counts())selection_options = {"minimum": 5}print("Unpacked named option:", retain_counts( combine_counts(*batches), **selection_options))try: retain_counts(read_counts, **{"mininum": 4})except TypeError as error: print("Unknown option rejected:", type(error).__name__)Separate arguments: [3, 5, 0, 8]Unpacked arguments: [3, 5, 0, 8]No batches: []Unpacked named option: [5, 8]Unknown option rejected: TypeErrorThe explicit minimum parameter rejects the misspelled option. A function with
**metadata instead accepts additional named arguments and collects them in a
dictionary. That interface suits open metadata fields, but it does not validate
field names against a fixed schema.
def sample_record(sample_id: str, **metadata: str) -> dict[str, str]: """Create a sample record with caller-defined text fields.
Args: sample_id: Identifier for the sample. **metadata: Additional named text fields to include.
Returns: A new dictionary containing the identifier and supplied metadata. """ return {"sample_id": sample_id, **metadata}
print(sample_record("S1", condition="control", batch="B2"))print(sample_record("S2", **{"condition": "treated"})){'sample_id': 'S1', 'condition': 'control', 'batch': 'B2'}{'sample_id': 'S2', 'condition': 'treated'}An unpacked dictionary still obeys the signature. It cannot assign the same parameter twice or supply an unknown parameter unless the definition accepts additional keyword arguments.
Returning multiple values
Section titled “Returning multiple values”A function can return several values at once using a tuple. You unpack them into separate variables on the calling side.
def summarize_counts(counts: list[int]) -> tuple[int, float, int, float]: """Summarizes a list of gene counts.
Args: counts: A nonempty list of nonnegative integer read counts.
Returns: A tuple of (total, mean, nonzero_count, zero_fraction).
Raises: ValueError: If counts is empty or contains a negative count. """ if not counts: raise ValueError("counts must not be empty") if any(count < 0 for count in counts): raise ValueError("counts must be nonnegative") total = sum(counts) mean_val = total / len(counts) nonzero = sum(1 for c in counts if c > 0) zero_fraction = sum(1 for c in counts if c == 0) / len(counts) return total, mean_val, nonzero, zero_fraction
gene_counts = [0, 15, 230, 0, 45, 120, 0, 78]total, mean_val, nonzero, zero_frac = summarize_counts(gene_counts)print(f"Total: {total}")print(f"Mean: {mean_val}")print(f"Nonzero genes: {nonzero}")print(f"Zero fraction: {zero_frac}")Total: 488Mean: 61.0Nonzero genes: 5Zero fraction: 0.375An assignment inside a function normally binds a local name. It does not
rebind a name in the surrounding module unless the function declares that name
with global.
threshold = 0.05
def check_significance(pvalue: float) -> bool: """Compare a p value with the local threshold.
Args: pvalue: P value to assess.
Returns: True when the p value is below the local threshold. """ threshold = 0.01 return pvalue < threshold
print(check_significance(0.03))print(f"Global threshold: {threshold}")FalseGlobal threshold: 0.05The function uses its own local threshold of 0.01. The global threshold stays at 0.05.
The rule protects rebinding, not mutation
Section titled “The rule protects rebinding, not mutation”The caller’s variable and the function parameter can refer to the same object.
A list method such as append changes that shared object. A new assignment to
the parameter changes which object the local name refers to.
def add_flag(genes: list[str]) -> list[str]: """Append a marker to a gene list.
Args: genes: Mutable list of gene names.
Returns: The same list after mutation. """ genes.append("FLAGGED") # mutates the caller's list return genes
my_genes = ["TP53", "BRCA1"]add_flag(my_genes)print(f"Caller after add_flag: {my_genes}")Caller after add_flag: ['TP53', 'BRCA1', 'FLAGGED']Rebinding instead leaves the caller alone:
def rebind(genes: list[str]) -> list[str]: """Return a copy of a gene list with a marker.
Args: genes: Input list of gene names.
Returns: New list containing the marker. """ genes = genes + ["REBOUND"] return genes
other_genes = ["TP53", "BRCA1"]returned_genes = rebind(other_genes)print(f"Caller after rebind: {other_genes}")print(f"Returned list: {returned_genes}")Caller after rebind: ['TP53', 'BRCA1']Returned list: ['TP53', 'BRCA1', 'REBOUND']The returned list contains the new item, while other_genes retains its contents.
For a function that accepts a mutable object, document whether it changes that object.
Mutable default arguments
Section titled “Mutable default arguments”A default is evaluated once, when the function is defined, so every call that does not pass one shares the same object.
def collect(gene: str, seen: list[str] = []) -> list[str]: """Append a gene to the shared default list.
Args: gene: Gene name to collect. seen: List used to collect gene names.
Returns: List containing collected gene names. """ seen.append(gene) return seen
print(collect("TP53"))print(collect("EGFR"))['TP53']['TP53', 'EGFR']The fix is seen=None, then build the list inside:
def collect_safe(gene: str, seen: list[str] | None = None) -> list[str]: """Append a gene without sharing a default list.
Args: gene: Gene name to collect. seen: Optional list of existing gene names.
Returns: List containing collected gene names. """ if seen is None: seen = [] seen.append(gene) return seen
print(collect_safe("TP53"))print(collect_safe("EGFR"))['TP53']['EGFR']Module constants and explicit arguments
Section titled “Module constants and explicit arguments”CUTOFF = 0.05
def is_significant(pvalue: float) -> bool: """Compare a p value with the configured cutoff.
Args: pvalue: P value to assess.
Returns: True when the p value is below the cutoff. """ return pvalue < CUTOFF
print(is_significant(0.01))TrueThis function works in a fresh process when its module defines CUTOFF.
An imported function resolves globals in the module where it was defined.
A stable module constant is a valid dependency. A changing analysis threshold
is easier to inspect and test when the caller supplies it, as in alpha above.
The global declaration makes an assignment update a module name. Here, each
call changes the same counter, so the result depends on earlier calls.
counter = 0
def bump() -> None: """Increment the module-level counter.""" global counter counter += 1
bump()bump()print(f"Counter after two calls: {counter}")Counter after two calls: 2Lambda functions
Section titled “Lambda functions”A lambda is a small anonymous function written on one line. It is useful for short operations you only need once.
genes = ["TP53", "BRCA1", "EGFR", "KRAS", "MYC"]sorted_by_length = sorted(genes, key=lambda g: len(g))print(sorted_by_length)['MYC', 'TP53', 'EGFR', 'KRAS', 'BRCA1']Use lambdas for simple sorting or filtering. For anything longer than one expression, write a regular function instead.
map and filter
Section titled “map and filter”map applies a function to each item from an iterable. filter keeps the items
for which its function returns a true value.
import math
counts = [100, 250, 50, 300, 75]log_counts = list(map(lambda c: round(math.log2(c + 1), 2), counts))print(log_counts)[6.66, 7.97, 5.67, 8.23, 6.25]pvalues = [0.001, 0.23, 0.04, 0.87, 0.005]below_threshold = list(filter(lambda p: p < 0.05, pvalues))print(below_threshold)[0.001, 0.04, 0.005]Both map and filter return iterators. Wrap them in list() to see the results. You can also achieve the same results with list comprehensions, which many Python programmers prefer for readability.
A note on docstrings
Section titled “A note on docstrings”For parameter and return types, continue with Python Type Annotations. That guide separates annotations, docstrings, and runtime checks.
This project uses Google-style docstrings as the standard format. Every function you write should include one. Google-style docstrings use Args:, Returns:, and Raises: sections with indented descriptions beneath each heading.
This format works with documentation generators like Sphinx and its Napoleon extension. These tools can parse your docstrings and produce professional HTML documentation automatically. Writing good docstrings is a habit that pays off when your codebase grows.
Practice without copying the examples
Section titled “Practice without copying the examples”- Filter a count list through
retain_countswithout changing the original list. - Pass the threshold through a dictionary, then explain where a misspelled key fails.
- Combine two batches, change the returned list, and explain whether either input changes.
- Pass a list explicitly to
collect_safeand explain why the caller still sees a mutation.
Show explanations and executable checks.
The filter allocates a new list. ** expands keyword arguments but does not
bypass the signature. The combined list also has its own outer storage.
The safe default creates a new list only when the caller omits the list;
an explicitly supplied list still receives the appended value.
practice_counts = [2, 0, 9, 2]practice_options = {"minimum": 2}practice_retained = retain_counts(practice_counts, **practice_options)assert practice_retained == [2, 9, 2]assert practice_retained is not practice_countsassert practice_counts == [2, 0, 9, 2]practice_left = [3]practice_right = [8]practice_combined = combine_counts(practice_left, practice_right)practice_combined[0] = 99assert practice_left == [3] and practice_right == [8]practice_supplied = ["TP53"]assert collect_safe("EGFR", practice_supplied) is practice_suppliedassert practice_supplied == ["TP53", "EGFR"]print("Argument binding, independent results, and supplied-list checks pass.")Argument binding, independent results, and supplied-list checks pass.Continue with iterators and generators to explain when a function produces values and when its caller consumes them.
Quick reference
Section titled “Quick reference”| Concept | Syntax | Example |
|---|---|---|
| Define a function | def name(params): |
def gc(seq): |
| Default argument | param=value |
alpha=0.05 |
| Positional-only input | def f(value, /): |
Supply value by position. |
| Keyword-only option | def f(*, minimum=1): |
Call f(minimum=4). |
| Extra positional arguments | def f(*values): |
values is a tuple. |
| Extra keyword arguments | def f(**options): |
options is a dictionary. |
| Unpack arguments in a call | f(*values, **options) |
Expand collections before binding parameters. |
| Return a value | return value |
return gc_count / length |
| Return multiple values | return a, b, c |
return total, mean, zeros |
| Lambda | lambda params: expr |
lambda g: len(g) |
| Map | map(func, iterable) |
map(lambda c: c+1, counts) |
| Filter | filter(func, iterable) |
filter(lambda p: p<0.05, pvals) |
| Docstring | """...""" after def |
See examples above |
Next steps
Section titled “Next steps”Now that you can write your own functions, learn how to use code others have written. Head to Working with Packages to learn about importing and managing Python libraries.
Further reading
Section titled “Further reading”-
Python tutorial: function definitions
The function sections explain positional and keyword arguments, default values, and lambda expressions. The mutable-list example explains why a None default creates a fresh collection for each call.