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

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

2 Introduction

So far, most code you have written runs once, in the order it appears. Control flow is the name for the tools that change this. These tools let a program choose which lines to run, or run some lines more than once.

By the end of this lesson you will be able to choose what a program does based on a value, and repeat a step for every item in a list or while a condition is true.

Try every example in the Python Scratchpad on the right.

Section 3

3 If/elif/else statements

The simplest decision a program can make is a yes or no choice. This decides whether some lines of code run at all. For example:

  • If a test result is above its reference range, flag it as high.
  • 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.

Each of these rules is an if statement.

Section 3.1

3.1 if statements

An if statement starts with the word if, then a condition, then a colon. The condition is a comparison that is true or false.

If statements in Python.
If statements in Python.

The lines that run when the condition is true go underneath, indented by four spaces. The indentation tells Python which lines belong to the if. A line that is not indented is outside the if, so it runs every time.

Here is an example with a temperature in degrees Celsius:

temperature = 38.6
if temperature >= 38.0:
    print("Fever")  # Fever
    print("Recheck in one hour")  # Recheck in one hour
print("Observation recorded")  # Observation recorded

The condition is true, so all three lines run.

Now change the temperature to 37.2. The condition is false, so Python skips the two indented lines:

temperature = 37.2
if temperature >= 38.0:
    print("Fever")
    print("Recheck in one hour")
print("Observation recorded")  # Observation recorded

To do something else when the condition is false, add an else. It has a colon but no condition. Its block runs when the if condition is false:

temperature = 37.2
if temperature >= 38.0:
    print("Fever")
else:
    print("No fever")  # No fever

With an if and an else, exactly one of the two blocks runs.

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 "below threshold", then print status.

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

Try this snippet in the Python Scratchpad on the right.

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

To check whether two values are the same, Python uses two equals signs: ==. The other comparison operators are != (not equal), <, >, <= and >=. Each gives True or False. A single equals sign assigns a value. Python reports a SyntaxError if you use one in a condition.

Try it out

Try this snippet in the Python Scratchpad on the right.

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

3.2 elif and else statements

For more than two outcomes, add an elif for each extra outcome. The word elif is short for "else if". Each elif has its own condition. Here a temperature is sorted into four outcomes:

temperature = 38.6
if temperature >= 39.0:
    print("High fever")
elif temperature >= 38.0:
    print("Fever")  # Fever
elif temperature >= 35.0:
    print("No fever")
else:
    print("Hypothermia")

Python checks conditions from top to bottom. It runs only the first block whose condition is true. The rest are skipped, even if they would also be true. Here, 38.6 also passes the check temperature >= 35.0, but Python never reaches it.

The else at the end runs only when no condition above it is true.

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

The order of the checks matters. Here the check for 35 or more comes first, so 38.6 matches it. A patient with a fever is recorded as having no fever, and Python reports no error:

temperature = 38.6
if temperature >= 35.0:
    print("No fever")  # No fever
elif temperature >= 38.0:
    print("Fever")
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 = "stage 2"
  • if systolic < 120 and diastolic < 80:
  • systolic = 138
  • elif systolic = 130 and diastolic = 80:
  • else:
  • elif systolic < 130 and diastolic < 80:
  • stage = "elevated"
  • else if systolic < 140 and diastolic < 90:
  • stage = "normal"
  • diastolic = 88
  • print(stage)
  • elif systolic < 130 or diastolic < 80:
  • stage = "stage 1"
  • elif systolic < 140 and diastolic < 90:
Your solution
  • Drop lines here, in order.
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 = 22.4
if bmi < 18.5:
    print("underweight")
elif bmi < 25:
    print("normal")
elif bmi < 30:
    print("overweight")
else:
    print("obese")

A condition can combine comparisons using and, or and not:

  • and is true only if both conditions are true.
  • or is true if at least one condition is true.
  • not reverses a condition. It is true only when the original condition is false.

For example, a patient has a temperature of 39.4 °C and a heart rate of 104 beats per minute:

temperature = 39.4
heart_rate = 104
if temperature >= 38.0 and heart_rate > 90:
    print("Flag for review")  # Flag for review
if temperature < 35.0 or temperature >= 39.0:
    print("Call the doctor")  # Call the doctor

The first condition needs both comparisons to be true, and they are. The second needs only one, and the temperature is at least 39.0.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
age = 81
bmi = 34.2
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")

The word or can shorten a chain of elif branches. When two branches do exactly the same thing, one condition with or can replace both.

Here two branches print the same message:

clinic = "east"
if clinic == "east":
    print("Route to Building A")  # Route to Building A
elif clinic == "west":
    print("Route to Building A")
elif clinic == "north":
    print("Route to Building B")
else:
    print("Unknown clinic")

Here is the same chain with one combined condition:

clinic = "east"
if clinic == "east" or clinic == "west":
    print("Route to Building A")  # Route to Building A
elif clinic == "north":
    print("Route to Building B")
else:
    print("Unknown clinic")

Both versions print the same message. The second is shorter, but two rules apply:

  • Each side of the or must be a complete comparison, so clinic is written twice.
  • Only combine branches that do exactly the same thing. If they might need to behave differently later, keep them separate.
Section 4

4 For loops

Suppose you want to know how many of five heart rates are above 90. Do not write five separate if statements.

Write one if statement inside a for loop instead. The loop runs its indented lines once for each item in a list.

For loop in Python.
For loop in Python.

Here is a loop over five heart rates. It prints each reading on its own line:

heart_rates = [88, 64, 101, 76, 93]
for heart_rate in heart_rates:
    print(heart_rate)  # 88, 64, 101, 76, 93

Now count the readings above 90. Set a counter to zero before the loop. Inside the loop, add one to the counter when the if test is true:

heart_rates = [88, 64, 101, 76, 93]
high_count = 0
for heart_rate in heart_rates:
    if heart_rate > 90:
        high_count = high_count + 1
print(high_count)  # 2

The line high_count = high_count + 1 adds one to the current count and stores the result under the same name. The readings 101 and 93 pass the test, so the counter ends at 2. The print line is not indented, so it runs once, after the loop.

If the print line is indented, it runs on every pass:

heart_rates = [88, 64, 101, 76, 93]
high_count = 0
for heart_rate in heart_rates:
    if heart_rate > 90:
        high_count = high_count + 1
    print(high_count)  # 0, 0, 1, 1, 2
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
ages = [45, 78, 62, 59, 70]
seniors = 0
for age in ages:
    if age > 65:
        seniors = seniors + 1
print(seniors)

The same pattern adds values up. Set a total to zero before the loop, and add each reading to it inside the loop. After the loop, divide the total by the number of readings:

heart_rates = [88, 64, 101, 76, 93]
total = 0
for heart_rate in heart_rates:
    total = total + heart_rate
mean_hr = total / len(heart_rates)
print(mean_hr)  # 84.4

Sometimes you repeat a step a set number of times, rather than once for each item in a list. The range() function gives whole numbers to loop over:

for number in range(4):
    print(number)  # 0, 1, 2, 3
for day in range(1, 6):
    print(day)  # 1, 2, 3, 4, 5
for position in range(0, 50, 10):
    print(position)  # 0, 10, 20, 30, 40
  • range(4) starts at 0 and stops just before 4.
  • range(1, 6) starts at 1 and stops just before 6. This suits counting the days of a five-day course.
  • range(0, 50, 10) adds a step, here 10, between the numbers. This gives every tenth position in a batch of 50.
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 and stopping before week 12. Print each visit week and the total number of visits.

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

Here a culture of 1000 cells doubles four times. The loop needs four passes, but no pass needs to know which pass it is:

cells = 1000
for _ in range(4):
    cells = cells * 2
print(cells)  # 16000

Some loops use range(len(heart_rates)) to step through list positions and look up each item by its position. When you only need the items, loop over the list itself:

heart_rates = [88, 64, 101, 76, 93]
for i in range(len(heart_rates)):
    print(heart_rates[i])  # 88, 64, 101, 76, 93
for heart_rate in heart_rates:
    print(heart_rate)  # 88, 64, 101, 76, 93

Both loops print the same readings. The second loop is easier to read.

Section 5

5 While loops

A for loop is used when you know what you are looping over, such as a list or a set number of passes.

A while loop is used when you do not know in advance how many passes you need. It keeps going as long as its condition is true. It looks like an if statement, but after the indented lines run, Python goes back to the top and checks the condition again.

While loop in Python.
While loop in Python.

For example, the level of a drug in the blood halves with every half-life. How many half-lives does it take for a level of 120 to fall below 10? The loop halves the level while it is 10 or more, and counts each pass:

drug_level = 120
half_lives = 0
while drug_level >= 10:
    drug_level = drug_level / 2
    half_lives = half_lives + 1
print(f"{half_lives} half-lives, level {drug_level}")  # 4 half-lives, level 7.5

The level falls from 120 to 60, 30, 15 and then 7.5. Since 7.5 is below 10, the condition is false and the loop stops. The loop ran four times, so four half-lives have passed.

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)

A while loop has one rule. Something inside the loop must change the value that the condition checks. If nothing does, the loop never ends. This is called an infinite loop.

Suppose the line that halves the level is missing. The counter half_lives still goes up on every pass:

drug_level = 120
half_lives = 0
while drug_level >= 10:
    half_lives = half_lives + 1
    print(half_lives, drug_level)
# This prints 1 120, then 2 120, then 3 120, and never stops

The counter does not help. The condition checks drug_level, and nothing in the loop changes it. So the condition stays true and the loop never ends.

When writing a while loop, find the variable that the condition checks. Then find the line inside the loop that changes it. If there is no such line, the loop never ends.

If you start an infinite loop in the Scratchpad, reload the page to stop it. In a terminal, hold down the Ctrl key and press C.

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 6

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

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