Skip to content

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.

Conditionals let your code take different paths based on a condition. The condition must evaluate to True or False.

The simplest conditional checks one condition. If the condition is true, the indented block runs. Otherwise, the else block runs.

pvalue = 0.003
if pvalue < 0.05:
print("Result is statistically significant")
else:
print("Result is not significant")
Result is statistically significant

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("Gene is upregulated")
elif log2fc < -1:
print("Gene is downregulated")
else:
print("No significant change")
Gene is upregulated

You can chain as many elif blocks as you need. Only one block will ever execute.

Python supports a one line conditional called a ternary expression. It is useful for simple assignments.

pvalue = 0.003
label = "significant" if pvalue < 0.05 else "not significant"
print(label)
significant

The 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.

A for loop iterates over items in a sequence. 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: TP53
Processing gene: BRCA1
Processing gene: EGFR
Processing gene: KRAS

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: S1
Sample 1: S2
Sample 2: S3

By 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 4

range(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"]
pvalues = [0.001, 0.04, 0.23]
for gene, pval in zip(genes, pvalues):
status = "significant" if pval < 0.05 else "not significant"
print(f"{gene}: p={pval} ({status})")
TP53: p=0.001 (significant)
BRCA1: p=0.04 (significant)
EGFR: p=0.23 (not significant)

zip() stops when the shortest sequence runs out. If your lists have different lengths, consider using itertools.zip_longest() instead.

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.

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 = 100
current = 10
doublings = 0
while current < threshold:
current *= 2
doublings += 1
print(f"Reached {current} after {doublings} doublings")
Reached 160 after 4 doublings

Be careful with while loops. If the condition never becomes false, your program will run forever. Always make sure the loop body changes something that will eventually make the condition false.

Two keywords let you control loop execution from inside the loop body.

  • break exits the loop immediately.
  • continue skips the rest of the current iteration and moves to the next one.
pvalues = [0.001, None, 0.04, 0.5, 0.003]
for i, pval in enumerate(pvalues):
if pval is None:
print(f"Skipping None at position {i}")
continue
if pval < 0.01:
print(f"Found highly significant result at position {i}")
Found highly significant result at position 0
Skipping None at position 1
Found highly significant result at position 4

Missing data is common in bioinformatics. Using continue to skip None values keeps your code clean and avoids errors from operations on missing data.

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): Loop over two sequences together
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

You now know how to control the flow of your Python programs. Next, learn how to organize reusable logic into Functions.