Section 1

1 Before you start

This is not graded, and it does not count towards anything. Answer every question even if you are only guessing — having a go at something before you have been taught it is one of the best ways to remember it afterwards. The lesson ends with another short check, and there you will be shown the correct answer for anything you missed. Choose an option for every question and confidence rating, then click Submit answers.

Pre-test

Inside a for loop, what does break do?

Pre-test

Inside a for loop, what does continue do?

Pre-test

You write for i, x in enumerate(["a", "b", "c"]): print(i, x). What does it print?

Pre-test

You write for i, x in enumerate(["a", "b", "c"], start=1): print(i, x). What does it print?

Pre-test

A break runs inside the inner of two nested for loops. Which loop stops?

Pre-test

Given ids = ["P1", "P2"] and ages = [54, 61], what does for x, y in zip(ids, ages): print(x, y) print?

Pre-test

What does [a * 2 for a in [1, 2, 3]] produce?

Pre-test

Given labels = {"A": 0, "B": 1}, what does {v: k for k, v in labels.items()} produce?

Pre-confidence

I can explain to a peer the difference between break and continue, and pick the right one for a given task.

Not at all confident
Fully confident
Pre-confidence

I can use enumerate to walk a list and report each item's position alongside its value.

Not at all confident
Fully confident
Section 2

2 Introduction

This lesson follows the previous lesson on control flow. It shows how to stop a loop early, skip an item and find the position of an item. It also shows how to read two lists together and build a list or dictionary in one line.

By the end, you will write one loop that skips missing values, stops at the first match and reports its position.

Try every example in the Python Scratchpad on the right.

Section 3

3 Loop control with break and continue

A for loop normally reads every item in a list. Sometimes you only need the first item that passes a test. The break keyword stops the loop once that item is found.

heart_rates = [88, 64, 101, 76, 93]
for heart_rate in heart_rates:
    if heart_rate > 100:
        print(f"Found {heart_rate}")  # Found 101
        break
print("Search finished")  # Search finished

The loop stops at 101, so 76 and 93 are never checked. Python then moves to the first line after the loop. If no reading is above 100, break never runs. The loop then checks every reading.

Break in a Python loop.
Break in a Python loop.
Predict the output

Read the code carefully and type what you think it will print. Click Submit prediction for AI tutor feedback comparing your prediction against the real output, then click Reveal actual output to run the snippet yourself and see what happens.

Code
glucose_readings = [110, 125, 165, 130, 175]
for reading in glucose_readings:
    if reading > 160:
        print(f"First high reading: {reading}")
        break
print("Done")
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
glucose_readings = [110, 125, 165, 130, 145]
for reading in glucose_readings:
    if reading > 160:
        print(f"High reading: {reading}")
        break

The continue keyword skips the rest of the current pass. The loop then moves on to the next item. This is useful for leaving out missing values.

# A zero means the monitor lost the signal
resting_rates = [72, 0, 78, 0, 84]
total = 0
valid_count = 0
for rate in resting_rates:
    if rate == 0:
        continue
    total = total + rate
    valid_count = valid_count + 1
print(total)  # 234
print(total / valid_count)  # 78.0

Without continue, the two zeros would count as readings. The mean would be 46.8 instead of 78. Python would not report an error.

Continue in a Python loop.
Continue in a Python loop.
Predict the output

Read the code carefully and type what you think it will print. Click Submit prediction for AI tutor feedback comparing your prediction against the real output, then click Reveal actual output to run the snippet yourself and see what happens.

Code
readings = [120, -1, 145, -1, 130]
total = 0
for r in readings:
    if r < 0:
        continue
    total = total + r
print(total)
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
readings = [120, -1, 145, -1, 130]
for r in readings:
    if r < 0:
        continue
    print(f"Valid: {r}")

So break ends the whole loop. In contrast, continue ends only the current pass.

A loop can be placed inside another loop. This is called a nested loop. For each item of the outer loop, the inner loop reads a whole list.

# Potassium results in mmol/L, one list for each patient
potassium = {
    "Tan": [4.6, 5.4, 6.3, 6.8],
    "Lim": [3.9, 4.2, 4.0],
    "Kumar": [5.8, 6.1, 5.5],
}
for name, levels in potassium.items():
    for level in levels:
        if level > 6.0:
            print(f"{name}: {level}")  # Tan: 6.3 / Kumar: 6.1
            break

A slash in the comment separates the printed lines. The break keyword stops the inner loop at 6.3 for Tan and at 6.1 for Kumar. Lim has no result above 6.0, so nothing is printed for Lim. The outer loop then moves to the next patient. This is because break ends only the loop it is directly inside.

Demonstration of break scope in nested loops..
Demonstration of break scope in nested loops..

In the animation, break stops the inner loop when j reaches 3. The inner loop starts again on the next pass of the outer loop. This is why j goes back to 0.

Section 4

4 Index tracking with enumerate

Sometimes a loop needs the position of each item as well as the item. The function enumerate gives you both on every pass.

Enumerate returns both the indexes and values of items.
Enumerate returns both the indexes and values of items.

In the for line, write two names. Put the list inside enumerate. The first name holds the position, which starts at 0. The second name holds the item.

heart_rates = [88, 64, 101]
for position, heart_rate in enumerate(heart_rates):
    print(f"Reading {position}: {heart_rate} bpm")  # Reading 0: 88 bpm / Reading 1: 64 bpm / Reading 2: 101 bpm
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
samples = ["S001", "S002", "S003", "S004"]
for i, sample in enumerate(samples):
    print(i, sample)

To count from 1 instead, add start=1 inside enumerate.

heart_rates = [88, 64, 101]
for position, heart_rate in enumerate(heart_rates, start=1):
    print(f"Reading {position}: {heart_rate} bpm")  # Reading 1: 88 bpm / Reading 2: 64 bpm / Reading 3: 101 bpm
print(heart_rates[0])  # 88

This changes only the numbers that enumerate gives back. The first item in the list is still at position 0.

Predict the output

Read the code carefully and type what you think it will print. Click Submit prediction for AI tutor feedback comparing your prediction against the real output, then click Reveal actual output to run the snippet yourself and see what happens.

Code
patient_ids = ["P07", "P12", "P03"]
for bed, pid in enumerate(patient_ids, start=10):
    print(f"Bed {bed}: {pid}")

You can use break, continue and enumerate in one loop. This loop reports the number of the first reading below 50 that is not missing.

# Overnight heart rates. A zero means a missing reading
night_rates = [62, 0, 57, 0, 46, 58, 44]
for number, rate in enumerate(night_rates, start=1):
    if rate == 0:
        continue
    if rate < 50:
        print(f"Reading {number}: {rate} bpm")  # Reading 5: 46 bpm
        break

The continue keyword skips the two zeros. Reading 5 is the first real reading below 50. The loop prints it. Then break stops the search.

The order of the two checks matters. If the check for a low reading comes first, a missing reading is reported as a low one.

night_rates = [62, 0, 57, 0, 46, 58, 44]
for number, rate in enumerate(night_rates, start=1):
    if rate < 50:
        print(f"Reading {number}: {rate} bpm")  # Reading 2: 0 bpm
        break
    if rate == 0:
        continue

Try it · Loop tracer

Run a loop one line at a time

Guess what the code prints, then press Step to run one line at a time and watch the variables change.

Before you step: what will this code print?

Variables

Printed so far

Section 5

5 Looping over two lists in parallel with zip

Sometimes related values are kept in separate lists, in the same order. The function zip lets one loop go through both lists together.

# Each dose, in milligrams, belongs to the drug in the same position
drugs = ["amoxicillin", "metformin", "warfarin"]
doses = [500, 850, 5]
for drug, dose in zip(drugs, doses):
    print(f"{drug}: {dose} mg")  # amoxicillin: 500 mg / metformin: 850 mg / warfarin: 5 mg

In the for line, write one name for each list. Put both lists inside zip. Each pass gives back the next item from each list.

With a third list, each pass gives three values. The for line then needs three names.

drugs = ["amoxicillin", "metformin", "warfarin"]
doses = [500, 850, 5]
frequencies = ["three times daily", "twice daily", "daily"]
for drug, dose, frequency in zip(drugs, doses, frequencies):
    print(f"{drug} {dose} mg {frequency}")  # amoxicillin 500 mg three times daily / metformin 850 mg twice daily / warfarin 5 mg daily

The function zip stops when the shortest list runs out. Here doses has only two items, so warfarin is left out. Python reports no error.

drugs = ["amoxicillin", "metformin", "warfarin"]
doses = [500, 850]
for drug, dose in zip(drugs, doses):
    print(f"{drug}: {dose} mg")  # amoxicillin: 500 mg / metformin: 850 mg
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
patient_ids = ["P001", "P002", "P003", "P004"]
ages = [54, 61, 47, 72]

for pid, age in zip(patient_ids, ages):
    print(f"{pid}: {age} years")

# Three lists at once
weights = [82.0, 68.5, 75.1, 90.2]
for pid, age, weight in zip(patient_ids, ages, weights):
    print(pid, age, weight)
zip pairs two or more lists by position and lets a single loop step through those pairs together, one item from each list per pass.
zip pairs two or more lists by position and lets a single loop step through those pairs together, one item from each list per pass.
Section 6

6 List and dictionary comprehensions

A loop can build a new list by appending one new value on each pass:

# Convert each dose from milligrams to grams
doses = [500, 850, 5]
grams = []
for dose in doses:
    grams.append(dose / 1000)
print(grams)  # [0.5, 0.85, 0.005]

Python has a one-line shortcut for this pattern, called a list comprehension. Here is the same list in one line:

doses = [500, 850, 5]
grams = [dose / 1000 for dose in doses]
print(grams)  # [0.5, 0.85, 0.005]

The new value comes first, followed by the same for part as in the loop. Read it from left to right: "dose / 1000 for every dose in doses".

You can also add an if part at the end, to keep only the items that pass a test:

heart_rates = [88, 64, 101, 76, 93]
above_90 = [rate for rate in heart_rates if rate > 90]
print(above_90)  # [101, 93]
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
ages = [54, 67, 71, 49, 82]
squared = [a ** 2 for a in ages]
print(squared)

seniors = [a for a in ages if a >= 65]
print(seniors)

labels = ["senior" if a >= 65 else "adult" for a in ages]
print(labels)
A list comprehension builds a new list in one line by evaluating an expression for each item in an iterable, optionally keeping only items that pass a filter condition.
A list comprehension builds a new list in one line by evaluating an expression for each item in an iterable, optionally keeping only items that pass a filter condition.

A dictionary comprehension builds a dictionary in the same way. It uses curly brackets, with a colon between the key and the value:

# zip pairs each drug with its dose
drugs = ["amoxicillin", "metformin", "warfarin"]
doses = [500, 850, 5]
dose_by_drug = {drug: dose for drug, dose in zip(drugs, doses)}
print(dose_by_drug)  # {'amoxicillin': 500, 'metformin': 850, 'warfarin': 5}
print(dose_by_drug["warfarin"])  # 5

A dictionary comprehension can also swap the keys and the values of another dictionary. Here the bed is written before the colon. So the new keys are bed numbers:

# bed_by_patient gives each patient's bed number
bed_by_patient = {"Tan": 4, "Lim": 7, "Kumar": 2}
patient_by_bed = {bed: name for name, bed in bed_by_patient.items()}
print(patient_by_bed[7])  # Lim

This works only if every bed number is different. If two patients have the same bed number, only the last patient is kept.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
pairs = [("P001", 54), ("P002", 61), ("P003", 47)]
lookup = {pid: age for pid, age in pairs}
print(lookup)

labels = {"A": 0, "B": 1, "C": 2}
inverse = {v: k for k, v in labels.items()}
print(inverse)
A dict comprehension builds a dictionary in one line by giving a key expression and a value expression for each item in an iterable, so you can turn pairs into a dict or compute a lookup table on the fly.
A dict comprehension builds a dictionary in one line by giving a key expression and a value expression for each item in an iterable, so you can turn pairs into a dict or compute a lookup table on the fly.

Try it · Loop to one line

Which part of the loop becomes which part of the one-liner?

Matching parts share a colour. Tap any coloured part to light up its twin.

Starting with

The loop

The same thing on one line

Both give

Section 7

7 Check your understanding

You have reached the end of the module. Try the same questions again — your answers here, paired with your pre-test answers, are how we measure what the module taught you. Answer every question and confidence rating, then click Submit and see results to view your score.

Post-test

Inside a for loop, what does break do?

Post-test

Inside a for loop, what does continue do?

Post-test

You write for i, x in enumerate(["a", "b", "c"]): print(i, x). What does it print?

Post-test

You write for i, x in enumerate(["a", "b", "c"], start=1): print(i, x). What does it print?

Post-test

A break runs inside the inner of two nested for loops. Which loop stops?

Post-test

Given ids = ["P1", "P2"] and ages = [54, 61], what does for x, y in zip(ids, ages): print(x, y) print?

Post-test

What does [a * 2 for a in [1, 2, 3]] produce?

Post-test

Given labels = {"A": 0, "B": 1}, what does {v: k for k, v in labels.items()} produce?

Post-confidence

I can explain to a peer the difference between break and continue, and pick the right one for a given task.

Not at all confident
Fully confident
Post-confidence

I can use enumerate to walk a list and report each item's position alongside its value.

Not at all confident
Fully confident
Section 8

8 Your results

Here is how your post-test answers compare with your pre-test answers. The pre/post pairing is the most reliable way to see what this module actually taught you.

Your score

Submit the post-test to see your results.

Muddiest point

What is the one thing from this module that is still unclear to you?

Rate this module

Overall, how would you rate this module?

How likely are you to recommend this module to a peer? (0 = not at all, 10 = extremely likely)