- Conditional statements and loops are fundamental programming structures that control how a Python program makes decisions and repeats operations. In bioinformatics, these structures are essential for processing biological datasets, filtering sequencing reads, examining DNA and protein sequences, evaluating quality-control criteria, analyzing gene expression, and automating repetitive computational tasks. Conditional statements allow programs to execute different instructions depending on whether specified conditions are satisfied, while loops enable repeated execution of instructions for individual elements, records, or computational steps.
- Biological data analysis often involves thousands or millions of observations. A researcher may need to examine every DNA sequence in a FASTA file, identify samples with unusually low sequencing depth, select genes with particular expression characteristics, or count mutations across multiple genomic regions. Performing these tasks manually is inefficient and error-prone. Conditional statements and loops allow such procedures to be expressed as reusable algorithms that can process large datasets systematically.
- A conditional statement evaluates a Boolean expression, which produces either True or False, and determines which instructions should execute. Python primarily uses the if, elif, and else keywords for conditional decision-making. The if statement executes a block of code when its condition is true. The elif statement, meaning “else if,” tests another condition when earlier conditions were false. The optional else block executes when none of the preceding conditions is satisfied.
- For example, a program might classify a gene expression measurement as high, moderate, or low according to predefined thresholds. If the expression value is greater than or equal to 100, the program could classify it as high; if it is between 20 and 99.99, it could be classified as moderate; otherwise, it could be classified as low. Such categories are meaningful only when the thresholds are justified by the experimental context and the measurement scale.
- The following Python example demonstrates conditional classification of a biological measurement:
expression_level = 75
if expression_level >= 100:
category = “High expression”
elif expression_level >= 20:
category = “Moderate expression”
else:
category = “Low expression”
print(category)
- Python evaluates the conditions from top to bottom and executes the first matching block. In this example, the expression level is classified as moderate because it is below 100 but at least 20. Once a condition is satisfied, the remaining branches are skipped. This makes the order of conditions important, particularly when ranges overlap.
- Indentation defines the structure of conditional statements in Python. Instructions belonging to a condition must be indented consistently, commonly using four spaces. Unlike some programming languages that use braces to mark blocks, Python uses indentation as part of its syntax. Incorrect indentation can produce an error or change the intended behavior of a program.
- Conditional statements can also combine multiple criteria using logical operators. The and operator requires all specified conditions to be true, whereas or requires at least one condition to be true. The not operator reverses a Boolean condition. In a sequencing workflow, a read or sample might pass a simple quality-control rule only if both its read count and mapping rate meet predefined thresholds.
read_count = 15000
mapping_rate = 0.94
if read_count >= 10000 and mapping_rate >= 0.90:
print(“Sample passes the defined quality criteria”)
else:
print(“Sample requires review”)
- This example illustrates how multiple criteria can be combined into a single decision. In real biological analyses, quality-control criteria should be selected according to the sequencing platform, experimental design, and analytical objectives. Passing a basic rule does not automatically establish that a sample is free from technical problems.
- Nested conditional statements are conditional statements placed inside other conditional blocks. They are useful when a decision depends on several levels of evaluation. For example, a program might first check whether a DNA sequence is empty, then determine whether it contains valid nucleotide symbols, and finally calculate its GC content. Nested conditions allow the program to handle these situations separately and avoid performing calculations on invalid inputs.
sequence = “ATGCGTAC”
if sequence:
sequence = sequence.upper()
if all(base in “ACGT” for base in sequence):
gc_content = (
(sequence.count(“G”) + sequence.count(“C”))
/ len(sequence)
) * 100
print(f”GC content: {gc_content:.2f}%”)
else:
print(“Sequence contains ambiguous or invalid symbols”)
else:
print(“Sequence is empty”)
- This example validates that the sequence is nonempty and contains only the four standard DNA bases before calculating GC content. Real-world datasets may contain legitimate ambiguity symbols, such as N, so a practical analysis should distinguish between valid ambiguous bases and genuinely invalid characters. The appropriate validation policy depends on the biological task.
- A loop is a programming structure that repeatedly executes a block of code. Python provides two main loop types: the for loop and the while loop. A for loop iterates over the elements of an iterable object, such as a list, string, tuple, dictionary, file, or range of integers. A while loop repeats its instructions as long as a specified condition remains true.
- The for loop is particularly useful in bioinformatics because biological datasets frequently consist of collections of records. A list may contain DNA sequences, gene identifiers, protein lengths, sample names, or experimental measurements. The loop processes each item in turn, allowing the same operation to be applied consistently to all elements.
- For example, the following program calculates the length of each DNA sequence in a list:
sequences = [
“ATGCGT”,
“GGCCAA”,
“ATATATGC”
]
for sequence in sequences:
print(“Sequence:”, sequence)
print(“Length:”, len(sequence))
- During each iteration, the variable sequence refers to the current item in the list. The program calculates and prints its length before moving to the next sequence. This approach is much more practical than writing separate instructions for every sequence, especially when the number of records is large.
- The built-in range() function is frequently used when a loop must execute a specified number of times. For example, range(5) generates the integers 0 through 4. The upper limit is excluded, which is an important feature to remember. A range can also specify a starting value and a step size, making it useful for iterating over positions, indices, or fixed intervals.
for position in range(5):
print(“Position:”, position)
- This program prints five position numbers, beginning at zero. Python uses zero-based indexing for strings, lists, and many other data structures, meaning the first element is at index 0 rather than index 1. When interpreting biological sequences, researchers should distinguish Python indices from biological coordinate systems, which may use one-based coordinates or zero-based, half-open intervals depending on the file format.
- The enumerate() function provides both the index and the corresponding value during iteration. It is useful when processing biological records that require positional information, such as examining nucleotides at particular sequence positions or associating measurements with their original order. The starting index can be specified explicitly if a different numbering convention is needed for presentation.
sequence = “ATGCGT”
for index, base in enumerate(sequence):
print(index, base)
- This example prints each nucleotide alongside its zero-based Python index. If the output is intended to display conventional one-based sequence positions, the program can use index + 1 for the displayed position without changing the underlying indexing convention.
- A while loop continues executing as long as its condition evaluates to true. It is useful when the number of iterations is not known in advance and depends on a changing condition. For example, a program may continue processing batches of sequencing records until a file has been exhausted or continue refining a numerical estimate until a convergence criterion is reached.
remaining_samples = 5
while remaining_samples > 0:
print(“Samples remaining:”, remaining_samples)
remaining_samples -= 1
- In this example, the variable decreases by one during each iteration. When it reaches zero, the condition becomes false and the loop stops. A while loop must update the variables involved in its condition when necessary. If the condition never becomes false, the program may enter an infinite loop and continue consuming computational resources.
- Python provides the break and continue statements to control loop execution. The break statement terminates the innermost loop immediately, while continue skips the remaining instructions in the current iteration and moves to the next one. These statements are useful when processing biological data with exceptions, such as stopping a search after a target sequence is found or skipping records that fail a defined validation rule.
- For example, a program searching for a particular DNA motif can stop once it finds a matching sequence:
sequences = [“ATATGC”, “GGGCCC”, “ATGAAA”]
target_motif = “GGG”
for sequence in sequences:
if target_motif in sequence:
print(“Motif found in:”, sequence)
break
- The program stops at the first sequence containing the target motif. This is appropriate when only the first matching record is required. If every matching sequence must be identified, the break statement should be omitted so that the loop continues through the complete dataset.
- The continue statement is useful when records that fail certain criteria should be excluded from further processing. For example, a sequence-processing program may skip empty sequences before calculating their lengths or nucleotide composition.
sequences = [“ATGC”, “”, “GGCC”, “ATN”]
for sequence in sequences:
if not sequence:
continue
print(“Processing:”, sequence)
- This program skips the empty string and processes the remaining entries. It does not validate whether each remaining sequence contains only standard nucleotide symbols, so additional conditional checks would be required for a more complete quality-control procedure.
- Loops can be combined with conditional statements to perform complex biological analyses. A common example is counting the occurrence of each nucleotide in a DNA sequence. The program iterates through every base and uses a conditional statement to update the corresponding count. Although specialized methods can perform such calculations efficiently, this example illustrates how loops and decisions work together.
sequence = “ATGCGCATTA”
counts = {“A”: 0, “T”: 0, “G”: 0, “C”: 0}
for base in sequence.upper():
if base in counts:
counts[base] += 1
print(counts)
- The dictionary stores a count for each standard DNA nucleotide. The conditional statement ensures that only bases present in the dictionary are counted, so ambiguous symbols are ignored. For scientific use, researchers should document whether ambiguous bases are excluded, counted separately, or handled using another convention.
- Nested loops are loops placed inside other loops. They are useful when a task requires examining combinations of elements, such as comparing pairs of genes, evaluating interactions between proteins, or calculating distances between observations. However, nested loops can become computationally expensive when datasets are large. A loop over (n) elements takes approximately (O(n)) iterations, while two nested loops that each process (n) elements can require approximately (O(n^2)) operations. Efficient algorithms, vectorized operations, or specialized libraries may be preferable when analyzing large biological datasets.
- For example, the following program compares each pair of sequences in a small collection:
sequences = [“ATGC”, “ATGT”, “GGCC”]
for i in range(len(sequences)):
for j in range(i + 1, len(sequences)):
print(sequences[i], sequences[j])
- The program generates each distinct unordered pair once and avoids comparing a sequence with itself. Pairwise comparisons are common in comparative genomics and sequence analysis, but the appropriate similarity calculation depends on sequence lengths, alignment requirements, and the biological question. For large collections, specialized sequence-search or alignment tools can be far more efficient than a basic nested loop.
- Loops are also used to process biological files. For example, Biopython can read FASTA records one at a time, allowing a program to calculate sequence statistics without storing every record in a separate list. This is useful for large sequence collections because processing records incrementally can reduce memory requirements.
from Bio import SeqIO
for record in SeqIO.parse(“sequences.fasta”, “fasta”):
sequence = str(record.seq).upper()
length = len(sequence)
print(record.id, length)
- This example reads a FASTA file and prints each record’s identifier and sequence length. It requires Biopython to be installed and assumes that the file path is correct and the file is valid FASTA. Production workflows should also handle file errors, malformed records, and any biological validation requirements relevant to the analysis.
- Loops can be used to filter gene expression measurements. Suppose a dataset contains expression values for several genes and a researcher wants to identify those that exceed a chosen threshold. A conditional statement inside a loop can test each value and retain the genes that meet the criterion. In a real differential expression study, however, a threshold on expression alone should not be confused with statistical evidence of differential expression, which usually requires an appropriate statistical model and adjustment for multiple testing.
expression = {
“GeneA”: 12.5,
“GeneB”: 3.2,
“GeneC”: 18.7,
“GeneD”: 7.4
}
threshold = 10
for gene, value in expression.items():
if value >= threshold:
print(gene, value)
- The dictionary’s items() method provides each gene identifier together with its expression value. The loop prints only the genes whose values meet the threshold. This pattern can be adapted to filter samples, variants, proteins, or other biological measurements.
- Python also supports list comprehensions, which provide a concise way to create lists from existing iterables. A list comprehension can combine iteration and conditional filtering in a single expression. For example, a researcher can extract all sequences longer than a specified minimum length from a list. Although list comprehensions are concise, ordinary loops may be clearer when the analysis requires multiple steps, extensive validation, or detailed error handling.
sequences = [“ATGC”, “ATGCGTAC”, “GG”, “ATGCC”]
long_sequences = [
sequence for sequence in sequences
if len(sequence) >= 5
]
print(long_sequences)
- The resulting list contains only sequences with at least five characters. This technique is useful for straightforward filtering, but sequence-length filtering should be scientifically justified and should account for the characteristics of the data and the intended analysis.
- Conditional statements and loops are closely related to error handling. A conditional statement can check whether a file exists, whether a value is missing, or whether a denominator is zero before a calculation is attempted. For more complex situations, Python’s exception-handling structures, including try, except, and finally, allow programs to respond to errors without necessarily terminating unexpectedly. Robust biological data-processing pipelines should validate their inputs, report meaningful error messages, and avoid silently discarding data that may affect scientific conclusions.
- Efficient use of loops is important when analyzing large biological datasets. Python loops are flexible, but repeated element-by-element calculations on large numerical arrays can be slower than equivalent operations implemented in optimized libraries. NumPy provides vectorized operations that perform calculations across entire arrays, while pandas offers filtering and aggregation methods for tabular data. For example, a NumPy array of expression measurements can be filtered using a Boolean mask instead of a Python loop. The choice between explicit loops and vectorized operations depends on the task, clarity, data structure, and performance requirements.
- Good programming practice includes using descriptive variable names, maintaining consistent indentation, avoiding unnecessary nesting, and ensuring that loop termination conditions are correct. Programs should be tested with small datasets for which expected results are known. Biological edge cases, such as empty sequences, ambiguous nucleotides, missing expression values, duplicate identifiers, and samples with zero reads, should be considered explicitly. Testing is particularly important when loops process thousands or millions of records, because a small logical error can affect a large proportion of the output.
- Conditional statements and loops are indispensable tools for implementing biological algorithms in Python. Conditional statements support classification, validation, filtering, and decision-making, while loops automate repeated operations across sequences, genes, samples, and biological records. Together, they enable researchers to transform raw data into structured analyses and reproducible workflows. Mastering these structures provides a foundation for more advanced topics, including functions, file processing, statistical analysis, sequence alignment, machine learning, and automated bioinformatics pipelines.