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.
Inside a for loop, what does break do?
Inside a for loop, what does continue do?
You write for i, x in enumerate(["a", "b", "c"]): print(i, x). What does it print?
You write for i, x in enumerate(["a", "b", "c"], start=1): print(i, x). What does it print?
A break runs inside the inner of two nested for loops. Which loop stops?
Given ids = ["P1", "P2"] and ages = [54, 61], what does for x, y in zip(ids, ages): print(x, y) print?
What does [a * 2 for a in [1, 2, 3]] produce?
Given labels = {"A": 0, "B": 1}, what does {v: k for k, v in labels.items()} produce?
I can explain to a peer the difference between break and continue, and pick the right one for a given task.
I can use enumerate to walk a list and report each item's position alongside its value.
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.
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 finishedThe 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.

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.
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 this snippet in the Python Scratchpad on the right.
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.0Without continue, the two zeros would count as readings. The mean would be 46.8 instead of 78. Python would not report an error.

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.
readings = [120, -1, 145, -1, 130]
total = 0
for r in readings:
if r < 0:
continue
total = total + r
print(total)
Try this snippet in the Python Scratchpad on the right.
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
breakA 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.

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

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 bpmTry this snippet in the Python Scratchpad on the right.
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]) # 88This changes only the numbers that enumerate gives back. The first item in the list is still at position 0.
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.
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
breakThe 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:
continueTry 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
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 mgIn 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 dailyThe 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 mgTry this snippet in the Python Scratchpad on the right.
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)

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 this snippet in the Python Scratchpad on the right.
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 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"]) # 5A 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]) # LimThis works only if every bed number is different. If two patients have the same bed number, only the last patient is kept.
Try this snippet in the Python Scratchpad on the right.
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)

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
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.
Inside a for loop, what does break do?
Inside a for loop, what does continue do?
You write for i, x in enumerate(["a", "b", "c"]): print(i, x). What does it print?
You write for i, x in enumerate(["a", "b", "c"], start=1): print(i, x). What does it print?
A break runs inside the inner of two nested for loops. Which loop stops?
Given ids = ["P1", "P2"] and ages = [54, 61], what does for x, y in zip(ids, ages): print(x, y) print?
What does [a * 2 for a in [1, 2, 3]] produce?
Given labels = {"A": 0, "B": 1}, what does {v: k for k, v in labels.items()} produce?
I can explain to a peer the difference between break and continue, and pick the right one for a given task.
I can use enumerate to walk a list and report each item's position alongside its value.
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.
Submit the post-test to see your results.
What is the one thing from this module that is still unclear to you?