Section 1 of 10

1 Before you start

Before you begin, take a few minutes to check what you already know and how confident you feel. You will see the same questions again at the end of the module — this helps both you and us measure what you have learned. Click an option for every question and confidence rating, then click Next to continue.

Pre-test

Which operator do you use to test whether x holds the value 5?

Pre-test

What tells Python which lines belong to an if block?

Pre-test

bmi = 27.3, checked in order: if bmi < 18.5 prints "underweight", elif bmi < 25 prints "normal", elif bmi < 30 prints "overweight", else prints "obese". What prints?

Pre-test

age = 72 and bmi = 31.4. What is the result of (age > 65) and (bmi > 30)?

Pre-test

What does range(2, 8) produce when used in a for loop?

Pre-test

ages = [54, 67, 71, 49, 82], then seniors = 0 and for age in ages: if age > 65: seniors = seniors + 1. What is the final value of seniors?

Pre-test

A while loop runs while count < 5: but never updates count inside the body. What happens?

Pre-test

glucose = 180, then while glucose > 140: glucose = glucose - 15. What is glucose when the loop ends?

Pre-confidence

I can write an if/elif/else chain that picks between three or more outcomes based on a numeric value.

Not at all confident
Fully confident
Pre-confidence

I can write a for loop that walks a list, applies an if-test to each item, and counts how many items pass.

Not at all confident
Fully confident
Pre-confidence

I can write a while loop that runs until a condition becomes false, and explain how to avoid an infinite loop.

Not at all confident
Fully confident
Section 2 of 10

2 Introduction

So far, every line of code you have written runs once, in the order it appears. That is fine for short snippets, but real work almost always needs two extra abilities: choosing what to do next based on a value (conditionals), and doing the same thing repeatedly without writing it out by hand (loops). Control flow is the umbrella name for both. This first module on control flow covers the three foundational tools:

  • if/elif/else — pick which block of code to run based on a condition, like flagging patients over 65 for the senior cohort.
  • for loops — walk through every item in a collection one by one, like computing the mean of a list of p-values.
  • while loops — keep going as long as a condition stays true, like titrating a dose until a marker drops below threshold.

Try every snippet in the Python Scratchpad on the right. By the end of this module you will write a loop that walks a list, applies a decision to each item, and counts what passes.

Section 3 of 10

3 If/elif/else statements

The simplest decision your code can make is yes or no. For example.

  • If a patient is older than 65, mark them as senior.
  • If a p-value is below 0.05, flag the result as significant.
  • If a sample has fewer than 10 reads, drop it from the analysis.

Every one of those rules is an if statement.

Section 3.1 of 10

3.1 if statements

An if statement starts with the word if, followed by a condition that is either true or false, then a colon.

If statements in Python.
If statements in Python.

The block of code that runs when the condition is true is written on the next line, indented by four spaces. Indentation is not decoration — it is how Python knows which lines belong to the if. The block ends as soon as the indentation goes back to where it was.

An example is shown below.

systolic_bp = 152
if systolic_bp >= 140:
    print("Blood pressure is high")
    print("Flag for follow-up")
print("Screening complete")

In that snippet the print("Blood pressure is high") and print("Flag for follow-up") lines only run because systolic_bp >= 140 is true. The print("Screening complete") line is not indented under the if, so it always runs. Try changing systolic_bp to 118 and run it again — the first two prints are skipped, the last one still happens.

There is a sequence on how you would arrange the codes. You can practice with the example below.

Parsons problem · Classifying a blood-pressure reading

All the lines you need are in the Line bank on the left — some may be distractors you should leave behind. Drag the lines you need into the Your solution column on the right, in the correct order, then click Check.

Task: A patient's systolic reading is stored in systolic. Set status to "hypertensive" if it is 140 mmHg or above, otherwise to "normal", then print status.

Line bank
  • if systolic => 140:
  • status = "normal"
  • if systolic = 140:
  • systolic = 145
  • if systolic >= 140:
  • print(status)
  • else:
  • status == "normal"
  • status = "hypertensive"
Your solution
  • Drop lines here, in order.

Now that you know the logic, let’s try to code and if statement.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
glucose_mmol = 7.4
if glucose_mmol >= 7.0:
    print("Above diabetes threshold")
    print("Order HbA1c test")
print("Reading logged")

To compare two values, Python uses double-equals: ==. A single equals sign means assignment ("put 5 into x"), and double-equals means comparison ("is x equal to 5?"). Mixing them up is the single most common beginner bug in this section. The other comparison operators are != (not equal), <, >, <=, and >=. Each one returns either True or False, which is exactly what an if statement needs.

Try the codes below and see what happens!

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
glucose = 7.2  # = assigns: store the value
threshold = 7.0
print(glucose == 7.2)  # == compares: True
print(glucose > threshold)  # True
print(glucose != 5.0)  # True
if glucose >= threshold:
    print("Above diabetic threshold")
Section 3.2 of 10

3.2 elif and else statements

When you have more than two outcomes, add elif (short for "else if") for each extra branch and a final else for everything that did not match. Python checks the conditions from top to bottom and runs the first one that is true — the rest are skipped, even if they would also be true.

The else block has no condition; it runs only when none of the earlier branches matched.

If, elif and else statements in Python.
If, elif and else statements in Python.

Let’s get use to the code sequence.

Parsons problem · Classifying blood pressure

All the lines you need are in the Line bank on the left — some may be distractors you should leave behind. Drag the lines you need into the Your solution column on the right, in the correct order, then click Check.

Task: Classify a patient with systolic 138 and diastolic 88 mmHg as normal (<120 / <80), elevated (<130 / <80), stage 1 hypertension (<140 / <90), or stage 2 hypertension.

Line bank
  • stage = "elevated"
  • else:
  • elif systolic < 140 and diastolic < 90:
  • else if systolic < 140 and diastolic < 90:
  • elif systolic < 130 or diastolic < 80:
  • systolic = 138
  • elif systolic = 130 and diastolic = 80:
  • stage = "stage 2"
  • diastolic = 88
  • elif systolic < 130 and diastolic < 80:
  • print(stage)
  • stage = "normal"
  • stage = "stage 1"
  • if systolic < 120 and diastolic < 80:
Your solution
  • Drop lines here, in order.

Can you predict what is being printed out in the example below?

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
bmi = 27.3
if bmi < 18.5:
    print("underweight")
elif bmi < 25:
    print("normal")
elif bmi < 30:
    print("overweight")
else:
    print("obese")

You can combine conditions with the words and, or, and not. age > 65 and bmi > 30 is true only when both parts are true. age < 18 or age > 90 is true when either part is true. not is_smoker is true when is_smoker is false. Use round brackets to group parts when the logic gets long — they cost nothing and save you guessing the precedence rules.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
age = 72
bmi = 31.4
is_smoker = False

if (age > 65) and (bmi > 30):
    print("high-risk: senior with obesity")
if (age < 18) or (age > 90):
    print("age outside study range")
if not is_smoker:
    print("non-smoker cohort")
Section 4 of 10

4 For loops

If you have a list of fifty patient ages and you want to know how many are over 65, you do not write fifty if statements.

You write one if statement inside a loop that walks the list for you. That is what a for loop is for: it takes a collection, picks each item in turn, and runs the indented block once per item.

For loop in Python.
For loop in Python.

An example code for a for loop is as below.

patient_glucose_readings = [95, 110, 130, 145, 102]
for reading in patient_glucose_readings:
    print(reading)
Parsons problem · Count hyperglycemic glucose readings

All the lines you need are in the Line bank on the left — some may be distractors you should leave behind. Drag the lines you need into the Your solution column on the right, in the correct order, then click Check.

Task: Given the list of patient glucose readings (mg/dL), count how many are at or above the 140 threshold.

Line bank
  • for reading in glucose_readings
  • for reading in glucose_readings:
  • if reading >= 140:
  • count = count + reading
  • count = count + 1
  • print(count)
  • if reading <= 140:
  • glucose_readings = [95, 110, 130, 145, 102]
  • count = 0
Your solution
  • Drop lines here, in order.

Now is your turn to practice with for loops.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
ages = [54, 67, 71, 49, 82]
seniors = 0
for age in ages:
    if age > 65:
        seniors = seniors + 1
print(seniors)

When you want to repeat something a fixed number of times, or you need the numbers 0, 1, 2, 3, … directly, use range(). range(5) gives you the numbers 0 through 4 (the stop value is excluded, the same rule as list slicing). range(2, 8) gives 2 through 7. range(0, 10, 2) gives 0, 2, 4, 6, 8 — the third number is the step.

Let’s see if you can get the syntax right.

Parsons problem · Schedule biweekly clinic visits

All the lines you need are in the Line bank on the left — some may be distractors you should leave behind. Drag the lines you need into the Your solution column on the right, in the correct order, then click Check.

Task: A 12-week clinical trial has assessments every 2 weeks starting at week 0. Print each visit week and the total number of visits.

Line bank
  • for week in (0, trial_weeks, 2):
  • print(f"Total visits: {visit_count}")
  • visit_count = 0
  • for week in range(0, trial_weeks):
  • visit_count = visit_count + 1
  • trial_weeks = 12
  • for week in range(0, trial_weeks, 2):
  • print(f"Assessment at week {week}")
  • for week in range(trial_weeks):
Your solution
  • Drop lines here, in order.

Now, let’s try out the code.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
for day in range(5):
    print(f"Day {day}")
for hour in range(0, 24, 4):
    print(f"Take dose at hour {hour}")

One habit worth forming early. If you find yourself writing codes such as “for i in range(len(ages)):”, you can write the code as “for age in ages:” instead.

(a) Without the habit – using range(len(…)):

ages = [54, 67, 42, 71, 38]
for i in range(len(ages)):
    print(ages[i])

(b) With the habit – looping directly over the list:

ages = [54, 67, 42, 71, 38]
for age in ages:
    print(age)

Both produce the same output, but the second version reads like a sentence.

Section 5 of 10

5 While loops

A for loop is the right tool when you know in advance what you are looping over — a list of patients, a range of numbers.

A while loop is the right tool when you do not know what you are looping over. In each case, the loop runs as long as some condition stays true; you have no idea ahead of time how many times that will be.

While loop in Python.
While loop in Python.

Here is an example code.

glucose = 180
insulin_units = 0
while glucose > 140:
    insulin_units = insulin_units + 1
    glucose = glucose - 15
print(f"Administered {insulin_units} units
glucose now {glucose}")

The code above can be read as: keep adding one unit of insulin (each drops glucose by ~15 mg/dL) until glucose falls to 140 mg/dL or below.  Basically, it says keep adding one unit of insulin until the patient's glucose drops to 140 or below, then print how many units it took and the final glucose.

Can you rearrange the code below to form a properly while loop?

Parsons problem · Phase I dose escalation

All the lines you need are in the Line bank on the left — some may be distractors you should leave behind. Drag the lines you need into the Your solution column on the right, in the correct order, then click Check.

Task: A phase I trial starts at 10 mg and doubles the dose each cohort while staying at or below 160 mg. Print each cohort number and its dose.

Line bank
  • dose_mg = dose_mg * 2
  • print(f"Cohort {cohort}: {dose_mg} mg")
  • cohort = cohort + 1
  • dose_mg = dose_mg + 2
  • dose_mg = 10
  • while dose_mg >= 160:
  • cohort = cohort - 1
  • cohort = 1
  • while dose_mg <= 160:
Your solution
  • Drop lines here, in order.

Your turn to try!

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
dose = 50
marker = 120
while marker > 90:
    dose = dose + 5
    marker = marker - 12
print(dose)
print(marker)

The single most important rule of while loops: something inside the block must change the value the condition depends on. If you forget that line, the condition is true forever and the loop never stops. That is an infinite loop, and it is the classic while-loop bug.

(a) Wrong — the infinite-loop trap:

glucose = 180
while glucose > 140:
    print("Giving insulin...")

In the code above, glucose starts at 180 and the condition glucose > 140 is true, so the block runs. But nothing inside the block ever changes glucose, so the condition stays true forever. The loop prints "Giving insulin..." again and again with no way to stop — you would have to kill the program manually.

(b) Right — the loop terminates:

glucose = 180
while glucose > 140:
    print("Giving insulin...")
    glucose = glucose - 15

The only difference is the last line: each pass through the loop now lowers glucose by 15. After enough passes the value drops to 140 or below, the condition becomes false, and the loop exits.

The takeaway: when you write a while loop, look at the condition (glucose > 140 here), find the variable it depends on (glucose), and check that something inside the block changes it. If you cannot point to that line, you have an infinite loop.

If you ever start an infinite loop in the Scratchpad, you can stop it by reloading the page. In a terminal, Ctrl+C kills it.

Section 6 of 10

6 Putting it together

The three tools in this module almost always combine. The most common pattern is to walk a list with a for loop and use an if/elif/else inside it to classify each item. The worked example below builds a small histogram of BMI bands using exactly that shape.

Worked example · Count BMI values in each band

Work through this example in three stages. You unlock each stage only after the tutor confirms the previous one. Each stage removes more of the scaffolding — by the end you are writing it yourself.

Problem: Given a list of BMI values, count how many fall into each of four bands: underweight (<18.5), normal (<25), overweight (<30), and obese (>=30). Print the four counts.

Stage 1 · Study the solved example
Fully solved solution
bmis = [22.1, 27.5, 18.0, 31.4, 24.0, 29.8, 17.0, 26.0]
under = 0
normal = 0
over = 0
obese = 0
for bmi in bmis:
    if bmi < 18.5:
        under = under + 1
    elif bmi < 25:
        normal = normal + 1
    elif bmi < 30:
        over = over + 1
    else:
        obese = obese + 1
print(under, normal, over, obese)
Walk-through
  1. First we set up four counters, one per band, all starting at zero.
  2. Then we walk the list of BMI values with a for loop. For each value, an if/elif/else chain picks exactly one band and adds one to that counter.
  3. Because Python checks the elif conditions in order and stops at the first true one, we can write bmi < 25 instead of 18.5 <= bmi < 25 — anything that did not match the first branch must already be at least 18.5.

Conditionals are bread-and-butter codes in most cases, so make sure you know how to write them well. You can practice as below:

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
patients = [120, 180, 210]
for glucose in patients:
    while glucose > 140:
        glucose = glucose - 15
    if glucose >= 130:
        print(f"{glucose}: borderline")
    elif glucose >= 110:
        print(f"{glucose}: target")
    else:
        print(f"{glucose}: low")
Section 7 of 10

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

Which operator do you use to test whether x holds the value 5?

Post-test

What tells Python which lines belong to an if block?

Post-test

bmi = 27.3, checked in order: if bmi < 18.5 prints "underweight", elif bmi < 25 prints "normal", elif bmi < 30 prints "overweight", else prints "obese". What prints?

Post-test

age = 72 and bmi = 31.4. What is the result of (age > 65) and (bmi > 30)?

Post-test

What does range(2, 8) produce when used in a for loop?

Post-test

ages = [54, 67, 71, 49, 82], then seniors = 0 and for age in ages: if age > 65: seniors = seniors + 1. What is the final value of seniors?

Post-test

A while loop runs while count < 5: but never updates count inside the body. What happens?

Post-test

glucose = 180, then while glucose > 140: glucose = glucose - 15. What is glucose when the loop ends?

Post-confidence

I can write an if/elif/else chain that picks between three or more outcomes based on a numeric value.

Not at all confident
Fully confident
Post-confidence

I can write a for loop that walks a list, applies an if-test to each item, and counts how many items pass.

Not at all confident
Fully confident
Post-confidence

I can write a while loop that runs until a condition becomes false, and explain how to avoid an infinite loop.

Not at all confident
Fully confident
Section 8 of 10

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)