Control Flow
Control flow determines the order in which your code runs. You will use conditionals to make decisions and loops to repeat actions. These patterns appear constantly in bioinformatics scripts.
Save the Python blocks in page order as control_flow.py, then run
uv run python control_flow.py from your project directory. The examples use
the standard library and require Python 3.10 or later for zip(strict=True).
Conditionals
Section titled “Conditionals”Conditionals let your code take different paths based on a value’s truth value.
Comparisons return Boolean values. Empty collections, zero, and None are
also false in a condition; a nonempty collection is true.
if/else
Section titled “if/else”The simplest conditional checks one condition. If the condition is true, the indented block runs. Otherwise, the else block runs.
adjusted_pvalue = 0.003
if adjusted_pvalue < 0.05: print("Adjusted p-value is below the threshold")else: print("Adjusted p-value meets or exceeds the threshold")Adjusted p-value is below the thresholdThe caller supplies this adjusted p-value. For gene tests, define the tested family before adjustment, as described in Multiple Testing.
if/elif/else
Section titled “if/elif/else”Use elif when you need to check multiple conditions in sequence. Python evaluates each condition from top to bottom. It runs the first block whose condition is true.
log2fc = 2.5
if log2fc > 1: print("Log2 fold change exceeds 1")elif log2fc < -1: print("Log2 fold change is below -1")else: print("Log2 fold change is between -1 and 1")Log2 fold change exceeds 1You can chain as many elif blocks as you need. Only one block will ever execute.
This example classifies the magnitude of a fold change. Statistical significance
also requires a suitable test and its uncertainty or p-value.
Ternary expression
Section titled “Ternary expression”Python supports a one line conditional called a ternary expression. It is useful for simple assignments.
label = "below 0.05" if adjusted_pvalue < 0.05 else "at least 0.05"print(label)below 0.05The syntax is value_if_true if condition else value_if_false. Keep ternary expressions simple. If the logic is complex, use a regular if/else block instead.
For loops
Section titled “For loops”A for loop iterates over an iterable, such as a list, dictionary, or generator.
Each iteration assigns the next item to the loop variable.
genes = ["TP53", "BRCA1", "EGFR", "KRAS"]
for gene in genes: print(f"Processing gene: {gene}")Processing gene: TP53Processing gene: BRCA1Processing gene: EGFRProcessing gene: KRASenumerate
Section titled “enumerate”Use enumerate() when you need both the index and the value. This is common when tracking positions in a dataset.
samples = ["S1", "S2", "S3"]
for i, sample in enumerate(samples): print(f"Sample {i}: {sample}")Sample 0: S1Sample 1: S2Sample 2: S3By default, enumerate() starts counting at 0. You can pass a second argument to start at a different number, like enumerate(samples, 1).
The range() function generates a sequence of integers. It is useful when you need to repeat an action a specific number of times.
for i in range(5): print(i, end=" ")print()0 1 2 3 4range(5) produces the numbers 0 through 4. The stop value is excluded.
Use zip() to iterate over two or more sequences in parallel. This is helpful when you have related data stored in separate lists.
genes = ["TP53", "BRCA1", "EGFR"]adjusted_pvalues = [0.001, 0.04, 0.23]
for gene, pvalue in zip(genes, adjusted_pvalues, strict=True): status = "below 0.05" if pvalue < 0.05 else "at least 0.05" print(f"{gene}: adjusted p={pvalue} ({status})")TP53: adjusted p=0.001 (below 0.05)BRCA1: adjusted p=0.04 (below 0.05)EGFR: adjusted p=0.23 (at least 0.05)With strict=True, zip() raises ValueError if the lists have different
lengths. That check protects the one-to-one correspondence between genes and
p-values. Without it, zip() stops at the shortest input and omits the rest.
Use itertools.zip_longest() only when padding unequal inputs is intentional.
List comprehension as loop alternative
Section titled “List comprehension as loop alternative”A list comprehension builds a new list in a single line. It is a concise alternative to a for loop that appends to a list.
counts = [100, 250, 50, 300, 75]labels = ["high" if c > 200 else "low" for c in counts]print(labels)['low', 'high', 'low', 'high', 'low']List comprehensions are great for simple transformations. If the logic inside becomes complex, use a regular for loop for readability.
While loops
Section titled “While loops”A while loop repeats as long as its condition is true. Use it when you do not know in advance how many iterations you need.
threshold = 100current = 10doublings = 0
while current < threshold: current *= 2 doublings += 1
print(f"Reached {current} after {doublings} doublings")Reached 160 after 4 doublingsIf a loop has no terminating condition or break, it continues indefinitely.
Here, doubling current eventually makes the condition false.
break and continue
Section titled “break and continue”Two keywords let you control loop execution from inside the loop body.
breakexits the loop immediately.continueskips the rest of the current iteration and moves to the next one.
adjusted_pvalues = [0.001, None, 0.04, 0.5, 0.003]
for index, pvalue in enumerate(adjusted_pvalues): if pvalue is None: print(f"Skipping None at position {index}") continue if pvalue < 0.01: print(f"Adjusted p-value below 0.01 at position {index}")Adjusted p-value below 0.01 at position 0Skipping None at position 1Adjusted p-value below 0.01 at position 4Missing data is common in bioinformatics. Using continue to skip None values keeps your code clean and avoids errors from operations on missing data.
Use break when the task needs only the first matching item. This loop stops
after the first value below the threshold.
for index, pvalue in enumerate(adjusted_pvalues): if pvalue is None: continue if pvalue < 0.01: print(f"First match is at position {index}") breakFirst match is at position 0Practice before you open the answer
Section titled “Practice before you open the answer”A sensor supplies [None, 0, 8, 12, 9, None, 15]. Find the index of the first observed value at least ten.
Skip only None, retain zero as an observation, and stop at the first match.
Then count every observed value, including zero, in a separate loop that visits the whole input.
Predict how the two loops behave for an empty input and for an input that contains only None.
Open the explanation and checks.
Use is None for the missing marker. A truth test such as if not value would also discard zero.
The search loop uses break, while the count loop must visit all positions.
readings = [None, 0, 8, 12, 9, None, 15]first_match = Nonefor index, value in enumerate(readings): if value is None: continue if value >= 10: first_match = index break
observed_count = 0for value in readings: if value is not None: observed_count += 1
assert first_match == 3assert observed_count == 5print("First qualifying index:", first_match)print("Observed values:", observed_count)First qualifying index: 3Observed values: 5With an empty input or only missing values, the initial None and zero results remain unchanged.
Keep separate variable names for the match position and observation count because they answer different questions.
Two lists contain sample names and read counts. Explain why ordinary zip() can hide a missing count, then make the mismatch fail explicitly.
Use names ['A', 'B', 'C'] and counts [0, 12].
Open the length check.
sample_names = ["A", "B", "C"]read_counts = [0, 12]print("Ordinary zip:", list(zip(sample_names, read_counts)))try: list(zip(sample_names, read_counts, strict=True))except ValueError: print("Strict zip rejects the missing count.")else: raise AssertionError("Unequal input lengths must fail.")Ordinary zip: [('A', 0), ('B', 12)]Strict zip rejects the missing count.Ordinary zip() omits sample C. The strict iterator detects the mismatch when it reaches the unmatched name, after the earlier pairs have already been yielded.
Validate lengths first if processing those earlier pairs would cause an irreversible action.
The iterator lesson explains why creating an iterator does not consume it.
Quick reference
Section titled “Quick reference”| Concept | Syntax | Use case |
|---|---|---|
if/elif/else |
if condition: |
Branch based on a condition |
| Ternary | x if condition else y |
Simple one line conditional |
for loop |
for item in sequence: |
Iterate over a collection |
enumerate() |
for i, item in enumerate(seq): |
Loop with an index counter |
range() |
for i in range(n): |
Loop a fixed number of times |
zip() |
for a, b in zip(x, y, strict=True): |
Pair inputs of equal length |
| List comprehension | [expr for item in seq] |
Build a list from a transformation |
while loop |
while condition: |
Loop until a condition is false |
break |
break |
Exit a loop early |
continue |
continue |
Skip to the next iteration |
Next steps
Section titled “Next steps”You now know how to control the flow of your Python programs. Next, learn how to organize reusable logic into Functions.
Further reading
Section titled “Further reading”-
The tutorial explains conditional branches, loops, break, continue, and function definitions. Its range examples help distinguish iteration values from list positions.
-
Python tutorial: data structures
The looping techniques section explains items, enumerate, and zip. Use it to compare the paired gene and p-value loop with the indexed sample loop.
The zip reference
explains the strict length check and the alternatives for unequal inputs.
The truth-value reference
defines how numbers, collections, and None behave in conditions.