Chapter 3: Loops and conditions

Chapter 3: Loops and conditions

3.1 For loops

Up to now, we’ve seen that a calendar can be represented as a dictionary. For example:

d = {
    "Monday": "Gym",
    "Tuesday": "Bioinformatics",
    "Wednesday": "Basketball"
}

But what happens if we want to see all the activities? Could we check them one by one?

d = {
    "Monday": "Gym",
    "Tuesday": "Bioinformatics",
    "Wednesday": "Basketball"
}

# Checking each day of the calendar
print(d["Monday"])
print(d["Tuesday"])
print(d["Wednesday"])

This works… but is it practical?

  • Not scalable
  • Repetitive
  • Impossible to manage with many items

So what do we need? –> We need a way to go through all the items automatically.

In programming, this is called iteration.

Defining an Iteration

Iterating is the process of going through each element of a collection, one by one. In our example:

image.png

Instead of accessing each item manually, we move through all of them automatically. We are visiting every item in the collection.

—- Let’s do an example! —-

We want to iterate through the days of our calendar.

calendar = {
    "Monday": "Gym",
    "Tuesday": "Bioinformatics",
    "Wednesday": "Basketball"
}

for day in calendar:
    print(day)

What is happening here?

  • for → starts a loop
  • day → is a variable that takes one key at a time
  • in calendar → means we go through all the keys in the dictionary

Iteration step by step:

  1. day = “Monday” → print(“Monday”)
  2. day = “Tuesday” → print(“Tuesday”)
  3. day = “Wednesday” → print(“Wednesday”)

The loop automatically visits each key in the dictionary.

Question: How can we access the activity of each day while iterating?

# Write your answer here

Maybe we want to access both key and values at the same time. To access both the day and the activity at the same time, we can use:

for day, activity in calendar.items():
    print(day, activity)

What is happening here?

  • calendar.items() returns pairs of (key, value)
  • day → stores the key
  • activity → stores the value

At each iteration, we get both elements at the same time. Iteration step by step:

(“Monday”, “Gym”)
(“Tuesday”, “Bioinformatics”)
(“Wednesday”, “Basketball”)

So at each step:

day = “Monday”, activity = “Gym”
day = “Tuesday”, activity = “Bioinformatics”
day = “Wednesday”, activity = “Basketball”

For loops in lists

So far, we have used for loops with dictionaries. But we can iterate through other types of data collections as well.

—- Let’s do an example! —-

We want to iterate through the items of our shopping list.

shopping_l = ["apple", "banana", "chocolate"]

for item in shopping_l:
    print(item)

What is happening here?

  • item takes each element of the list, one by one
  • The loop goes through all elements in order

Iteration step by step:

item = “apple” → print(“apple”)
item = “banana” → print(“banana”)
item = “chocolate” → print(“chocolate”)

Question: What will happen if we do print(item.upper())?

# Write your answer here

Talk about looping and index

3.2 While loops

In python there are also while loops. They are used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.

—- Let’s do an example! —-

We are going to create a while loop which will be iterating until the counter reaches three

cnt = 0 
while (cnt < 3):
    cnt = cnt+1
    print("Hello Guys")

What is happening here?

  • We start with cnt = 0
  • The loop runs while cnt < 3

Iteration step by step:

  1. cnt = 0 → condition is True → print → cnt = 1
  2. cnt = 1 → condition is True → print → cnt = 2
  3. cnt = 2 → condition is True → print → cnt = 3
  4. cnt = 3 → condition is False → loop stops

—- Let’s do another example! —-

Execute the following piece of code. What is happening now?

What happens here?

The loop will never stop (infinite loop)

Why?

  • cnt never changes
  • The condition is always True

👉 Always make sure the condition will eventually become False

Questions:

  • What happens if we start with cnt = 5?
  • How many times will the loop run?

# Write your answer here

image.png

3.3 Conditional statements

Conditional statements are used to execute certain blocks of code based on specific conditions. Imagine you are at the supermarket:

👉 Is this chocolate?

  • YES → Buy it 🍫
  • NO → Don’t buy it ❌

How can we translate this into python?

l = ["chocolate","banana","apple"]
for food in l:
    if food == "chocolate":
        print("Buy",food)

What is happening here?

for each product in the shopping list we’re checking: - if → checks a condition
- food == "chocolate" → is the condition - If condition is True -> Then buying the food item

Think of it like a decision tree:

    condition?
    /       \
  YES       NO
  ↓          ↓
do this  do something else

If/else conditions

Allows us to specify a block of code that will execute if the condition associated with an if statement evaluates to False.

👉 Is this chocolate?

  • YES → Buy it 🍫
  • NO → Don’t buy it ❌ (else)

—- Let’s do an example! —-

If food is chocolate we will buy it, if not we won’t buy it

l = ["chocolate","banana","apple"]
for food in l:
    if food == "chocolate":
        print("Buy",food)
    else:
        print("Not buying",food)

What is happening here?

  • We iterate through the list using a for loop
  • For each element (food), we check a condition
  • If food == "chocolate" → we print “Buy”
  • Otherwise (else) → we print “Not buying”

Iteration step by step:

food = “chocolate” → Buy chocolate 🍫
food = “banana” → Not buying banana ❌
food = “apple” → Not buying apple ❌


elif conditions

Stands for “else if”. Allows us to check multiple conditions, providing a way to execute different blocks of code based on which condition is true

👉 Is this chocolate?

  • YES → Buy it 🍫

👉 NO → Is this banana?

  • YES → Buy it 🍌

👉 NO → Don’t buy it ❌ (else)

Think of it like a chain of decisions:

* if → first condition  
* elif → second condition  
* elif → third condition  
* else → none of the above

—- Let’s do an example! —-

If food is chocolate we will buy it, if it is not but it is banana we will still buy it, but if none of these two are we won’t buy it

l = ["chocolate","banana","apple"]
for food in l:
    if food == "chocolate":
        print("Buy",food)
    elif food == "banana":
        print("Buy",food)
    else:
        print("Not buying",food)

What is happening here?

  • For each food, Python checks conditions in order:
  1. Is it "chocolate"?
  2. If not → is it "banana"?
  3. If none are true → go to else

Iteration step by step:

food = “chocolate” → Buy chocolate 🍫
food = “banana” → Buy banana 🍌
food = “apple” → Not buying apple ❌

3.4 Exercises

Exercise 1

You are given a list of DNA sequences:

seqs = ["ATGCGT", "TTAGGC", "CCGTAA"]

Tasks:

  1. Print only sequences longer than 6
  2. Print only sequences that contain “GG”
# Write your answer here

Exercise 2

You are given a list of sequences:

seqs = ["ATGCGT", "TTAGGC", "CCGTAA"]

Task:

Create a dictionary where: - keys → “seq1”, “seq2”, … - values → sequences

Expected output: {“seq1”: “ATGCGT”, “seq2”: “TTAGGC”, …}

# Write your answer here

Exercise 3

You are given:

seqs = ["ATG", "ATGCGT", "TTA", "CCGTAA", "GG"]

Task:

Create a dictionary that counts how many sequences have each length.

# Write your answer here

Exercise 4

You are given:

fasta = {
    "seq1": {"sequence": "ATGCGT", "length": 6},
    "seq2": {"sequence": "TTAGGCA", "length": 7},
    "seq3": {"sequence": "CCGTAA", "length": 6}
}

Tasks:

  1. Print only sequences with length > 6
  2. Print the name of the sequence that contains “GG”
  3. Count how many sequences satisfy BOTH conditions
# Write your answer here

Exercise 5 — FASTA deep analysis

You are given a FASTA-like dictionary:

fasta = {
    "seq1|human|geneA": "ATGCGTAGGCTA",
    "seq2|mouse|geneB": "TTAGGCGG",
    "seq3|human|geneC": "CCGTAA",
    "seq4|yeast|geneD": "GGGGGGGG",
    "seq5|human|geneE": "ATATATAT",
    "seq6|mouse|geneF": "CGCGCGTA"
}

Each header has the format: “seqX|species|gene”

Tasks:

  1. Create a dictionary that counts how many sequences belong to each species
    Expected: {“human”: ?, “mouse”: ?, “yeast”: ?}

  2. Find the longest sequence for each species
    Expected: {“human”: “…”, “mouse”: “…”, …}

  3. Print only sequences that:

    • belong to “human”
    • AND have more than 50% GC content
  4. Find the gene name of the sequence with the highest GC content


⚠️ Rules:

  • You must parse the header using string operations
  • You must NOT hardcode species or gene names
  • You must compute GC content manually
# Write your answer here

Exercise 6 — Complex filtering and reconstruction

You are given a nested structure:

data = {
    "sample1": {
        "seq1": "ATGCGTAA",
        "seq2": "GGGGTTTT",
        "seq3": "ATATATAT"
    },
    "sample2": {
        "seq4": "CCCGGG",
        "seq5": "TTTTAAA",
        "seq6": "GGATCC"
    },
    "sample3": {
        "seq7": "ATGCGCGC",
        "seq8": "AAAAAAA",
        "seq9": "CGT"
    }
}

Tasks:

  1. Create a new dictionary that only contains sequences that:
    • have length ≥ 6
    • AND contain at least one “G”

Keep the same structure (sample → sequences)


  1. For each sample:
    • count how many sequences passed the filter

Expected: {“sample1”: X, “sample2”: Y, …}


  1. Find the sample with the highest average sequence length

  1. Create a set with all unique sequences across all samples

  1. BONUS: Create a dictionary grouping sequences by GC content:

Example: { “high_GC”: […], “low_GC”: […] }

(Define your own threshold, e.g., >50%)


⚠️ Rules:

  • You must use nested loops
  • You must NOT flatten the structure first
  • You must compute everything dynamically
# Write your answer here