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

What does print(f"{2 + 3} items") display?

Pre-test

What does f"{4.2e-8:.2e}" produce?

Pre-test

What does f"{0.0423:.1%}" display?

Pre-test

Why does int("banana") raise a ValueError rather than a TypeError?

Pre-test

A script raises KeyError: 'middle_name'. What is the most likely cause?

Pre-test

When you read a Python traceback, which line tells you the exception type and its message?

Pre-test

A line age = int(raw) is wrapped in a try block, with except ValueError setting age = None. If raw is "42", what is age after the block runs?

Pre-test

What happens when Python runs assert len(a) == len(b), "length mismatch" and the two lengths are equal?

Pre-confidence

I can write an f-string that formats a p-value in scientific notation with two decimal places.

Not at all confident
Fully confident
Pre-confidence

I can read a Python traceback and identify which exception was raised and on which line.

Not at all confident
Fully confident
Pre-confidence

I can wrap a risky line in try/except and decide which specific exception to name.

Not at all confident
Fully confident
Section 2

2 Introduction

Now that you can store and combine values, there are two skills to learn next. The first is to print a value in exactly the form that you want. The second is to read and handle the errors that Python reports when something goes wrong. This lesson covers f-strings, format specifiers, the common error types, how to read a traceback, and the keywords try, except, raise and assert.

Try every example in the Python Scratchpad on the right.

Section 3

3 String Formatting with f-strings

To recap, a string is text enclosed in quotes (" " or ' '). The code below prints two strings and the type of each.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
diagnosis = "Type 2 Diabetes"
blood_type = 'O positive'
print(diagnosis)
print(blood_type)
print(type(diagnosis))
print(type(blood_type))

Soon, you will need to build one string from several values, such as a patient ID and a glucose reading. In the example below, line 3 joins them with the plus sign after str() converts the reading. Line 4 does not convert it.

patient_id = "P00472"
glucose_mmol = 7.823
print("Patient " + patient_id + " glucose " + str(glucose_mmol))  # Patient P00472 glucose 7.823
print("Patient " + patient_id + " glucose " + glucose_mmol)
# TypeError: can only concatenate str (not "float") to str

Line 3 works, but it is long and hard to read. Line 4 fails. This is because the plus sign can join a string only to another string. An f-string avoids both problems. It is a string with a lower-case f before the opening quote. Anything in curly braces inside it is a Python expression. Python works out its value and puts it into the string.

patient_id = "P00472"
glucose_mmol = 7.823
print(f"Patient {patient_id} glucose {glucose_mmol}")  # Patient P00472 glucose 7.823
Using f-strings in Python to form a sentence.
Using f-strings in Python to form a sentence.

The example below also uses :.1f and :.1%. The section on format specifiers explains both.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
patient_id = "P00472"
glucose_mmol = 7.823
hba1c_fraction = 0.0654
print(f"Patient {patient_id}: glucose = {glucose_mmol:.1f} mmol/L")
print(f"HbA1c = {hba1c_fraction:.1%}")

Anything that works out to a single value can go inside the braces, such as a calculation or a call to round():

weight_kg = 68.5
height_m = 1.62
print(f"BMI = {weight_kg / height_m ** 2}")  # BMI = 26.101204084743173
print(f"BMI = {round(weight_kg / height_m ** 2, 1)}")  # BMI = 26.1
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
patient = "Sim Hui En"
systolic_bp = 142
diastolic_bp = 91
print(f"Patient {patient} has a blood pressure of {systolic_bp}/{diastolic_bp} mmHg.")
Section 3.1

3.1 Format specifiers

After a colon inside the braces, you can choose how the value is displayed. The text after the colon is a format specifier. These four suit numbers:

  • .2f: a float with two decimal places.
  • .2e: scientific notation with two decimal places, where e-05 means times ten to the power of minus five.
  • ,: a comma between each group of three digits.
  • .1%: a percentage with one decimal place. Python multiplies the value by 100 and adds a percent sign. So the value must be a fraction. A value of 6.5 prints as 650.0%.
p_value = 0.04567
print(f"{p_value:.2f}")  # 0.05
print(f"{3.6e-5:.2e}")  # 3.60e-05
print(f"{1283041:,}")  # 1,283,041
print(f"{0.0654:.1%}")  # 6.5%

Two more specifiers set the width of a field:

  • >10: right-aligned in a field that is 10 characters wide.
  • <10: left-aligned in that field.
print(f"[{'genotype':>10}]")  # [  genotype]
print(f"[{'genotype':<10}]")  # [genotype  ]

A format specifier changes only how a value is shown. The variable still holds every digit:

glucose_mmol = 7.823
print(f"{glucose_mmol:.1f}")  # 7.8
print(glucose_mmol)  # 7.823
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
print(f"[{0.04567:.2f}]")
print(f"[{4.2e-8:.3e}]")
print(f"[{1234567:,}]")
print(f"[{0.0423:.1%}]")
print(f"[{'gene':>10}]")
print(f"[{'gene':<10}]")
In a Python f-string, the colon separates the value from a format spec that controls how it is displayed.
In a Python f-string, the colon separates the value from a format spec that controls how it is displayed.

Try it · Format playground

What does each format do to a number?

Pick a number, then a format. The f-string and what Python prints change straight away.

1. A number

2. A format (the part after the colon)


  

Can you make these?

    Section 4

    4 Common Python Errors and Exceptions

    An error is how Python tells you what it could not do. Every error belongs to one of two groups.

    A syntax error happens before any code runs. Python reads the whole file, finds something that is not valid, and refuses to start. Here the last line has one closing bracket too many:

    glucose_mmol = 7.8
    print("Starting the analysis")
    print(glucose_mmol))
    # SyntaxError: unmatched ')'

    Nothing is printed, not even by the first print line. Every other error is a runtime exception. The program starts, and then something goes wrong in the middle. Here the division stops the program:

    print("Starting the analysis")  # Starting the analysis
    cases = 12
    person_years = 0
    print(cases / person_years)
    # ZeroDivisionError: division by zero
    Section 4.1

    4.1 The errors you will meet first

    You will see these eight errors often. You need to know their names.

    • NameError: you used a name that has no value yet, often from a typo.
    height_m = 1.62
    print(bmi)
    # NameError: name 'bmi' is not defined
    • TypeError: a value has the wrong type for the operation. Here the plus sign cannot add a number to a string:
    age_text = "54"
    print(age_text + 1)
    # TypeError: can only concatenate str (not "int") to str
    • ValueError: the type is right, but the content is wrong. Here int() accepts a string, but the string must contain a whole number:
    glucose_text = "7.8"
    print(int(glucose_text))
    # ValueError: invalid literal for int() with base 10: '7.8'
    • IndexError: you asked for the sixth item of a list that has only five items.
    • KeyError: you asked for a key that is not in a dictionary.
    • ZeroDivisionError: you divided by zero, for example when a group is empty.
    • IndentationError: a line is indented wrongly. This is a kind of syntax error. So Python reports it before the program runs.
    • AttributeError: you used a method that the value does not have. A method is a function that belongs to a value. You write it after the value and a dot.
    Common error types often encountered in Python.
    Common error types often encountered in Python.
    Section 4.2

    4.2 Reading a traceback

    When an exception stops a program, Python prints a traceback. The important part is at the bottom. Read it from the bottom up:

    • The last line names the type of the exception and gives its message.
    • The File line above it gives the line number where the error happened.

    For most bugs, the last line is enough. Run the example below in the Python Scratchpad and read its traceback from the bottom up. The File line points to line 3.

    glucose_mmol = 7.823
    print("Rounding the reading")  # Rounding the reading
    print(glucose_mmol.round(1))
    # AttributeError: 'float' object has no attribute 'round'

    Now fix the broken code in each snippet below. Read the last line of each error to find the cause.

    (a) NameError

    Debug & fix

    The code below is broken. Type a fixed version into the editor, then click Run & check. Success means your code runs without errors and produces output. Use Show hint only if you get stuck.

    Broken code (do not copy verbatim)
    heart_rate = 78
    respiratory_rate = 16
    vitals_total = heart_rate + repiratory_rate
    print(vitals_total)

    (b) TypeError

    Debug & fix

    The code below is broken. Type a fixed version into the editor, then click Run & check. Success means your code runs without errors and produces output. Use Show hint only if you get stuck.

    Broken code (do not copy verbatim)
    weight_kg = "72"
    height_m = 1.75
    bmi = weight_kg / (height_m ** 2)
    print(round(bmi, 1))

    (c) ValueError

    Debug & fix

    The code below is broken. Type a fixed version into the editor, then click Run & check. Success means your code runs without errors and produces output. Use Show hint only if you get stuck.

    Broken code (do not copy verbatim)
    blood_pressure = "120/80"
    systolic = int(blood_pressure)
    print(systolic)

    (d) IndentationError

    Indentation is the empty space at the start of a line. It shows which lines belong together as a group. After a line that ends with a colon, the next lines are pushed to the right. The standard amount is four spaces. The Tab key gives four spaces in most editors.

    In the example below, the two indented print lines belong to the if line. The last print line is not indented. So it always runs.

    glucose = 8.2
    if glucose > 7.0:
        print("high")  # high
        print("recheck in 3 months")  # recheck in 3 months
    print("done")  # done

    Python is strict about consistency. Every line in a group must be indented by the same amount. Never mix tabs and spaces. Here the second print line is indented further than the first:

    glucose = 8.2
    if glucose > 7.0:
        print("high")
          print("recheck in 3 months")
    # IndentationError: unexpected indent

    Now fix the indentation error below:

    Debug & fix

    The code below is broken. Type a fixed version into the editor, then click Run & check. Success means your code runs without errors and produces output. Use Show hint only if you get stuck.

    Broken code (do not copy verbatim)
    temperature_c = 38.4
    if temperature_c >= 38.0:
    print("Fever - notify nursing team")
    Section 4.3

    4.3 Catching exceptions with try/except

    Sometimes you can see an error coming, and you would rather handle it than stop the program. The risky line goes in a try block. What should happen instead goes in an except block that names the exception you expect:

    patient = {"id": "P001"}
    try:
        age = patient["age"]
    except KeyError:
        age = 0
    print(age)  # 0

    Here the dictionary has no key called age. So except KeyError catches the error and sets age to 0. If the risky line works, the except block does not run:

    entered = "250"
    try:
        dose_mg = int(entered)
        print("converted")  # converted
    except ValueError:
        print("not a number")
    A try block runs risky code, and when it raises an exception the matching except block catches it so the program recovers instead of crashing.
    A try block runs risky code, and when it raises an exception the matching except block catches it so the program recovers instead of crashing.

    An except block catches only the exception it names. Here the block names KeyError, but the line raises a ValueError:

    entered = "two tablets"
    try:
        dose_mg = int(entered)
    except KeyError:
        dose_mg = None
    # ValueError: invalid literal for int() with base 10: 'two tablets'

    Now arrange the lines below into a working try/except block.

    Parsons problem · Safely look up a patient diagnosis

    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: The patient ID may not exist in the records dict. Look up the diagnosis, or fall back to "no record found" if the ID is missing.

    Line bank
    • diagnosis = patient_records[patient_id]
    • try:
    • print(diagnosis)
    • patient_records = {"P001": "diabetes", "P002": "hypertension"}
    • except KeyError
    • patient_id = "P003"
    • diagnosis = "no record found"
    • except KeyError:
    • diagnosis = patient_records[patient_id]
    • except:
    Your solution
    • Drop lines here, in order.
    Try it out

    Try this snippet in the Python Scratchpad on the right.

    Try this snippet
    raw = "42"
    try:
        age = int(raw)
    except ValueError:
        age = None
    print(age)

    The next example converts a list of ages. Each entry that cannot be converted becomes None.

    Try it out

    Try this snippet in the Python Scratchpad on the right.

    Try this snippet
    raw_ages = ["42", "NA", "65", "unknown"]
    parsed = []
    for raw in raw_ages:
        try:
            parsed.append(int(raw))
        except ValueError:
            parsed.append(None)
    print(parsed)
    Section 4.4

    4.4 Raising your own exceptions with raise

    Until now, Python raised every exception for you. You can also raise an exception yourself.

    Suppose a dose is entered as a negative number. Python accepts it. The calculation gives a wrong answer with no error:

    dose_mg = -5
    doses_per_day = 3
    total_mg = dose_mg * doses_per_day
    print(total_mg)  # -15

    A wrong answer with no error is hard to find later. It is better to stop the program as soon as your code notices a problem. Think of raise as an emergency brake.

    To raise an exception, write raise, the error type, and a message in round brackets and quotes:

    raise ValueError("Dose must be positive")
    # ValueError: Dose must be positive

    Choose the type that describes the problem:

    • Use ValueError when the data has the right type but the wrong value.
    • Use TypeError when the data has the wrong type.

    The exercise below puts the raise lines inside a function. A function is a named code block. Now arrange its lines.

    Parsons problem · Validate a patient's age before storing it

    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: Write a function that raises TypeError if age is not an int, raises ValueError if age is negative, otherwise returns the age. Then call it with 30.

    Line bank
    • raise TypeError("Age must be an integer")
    • def set_age(age):
    • raise TypeError("Age cannot be negative")
    • return age
    • raise ValueError("Age cannot be negative")
    • if age < 0:
    • if age < 0
    • if not isinstance(age, int):
    • raise ValueError("Age must be an integer")
    • print(set_age(30))
    Your solution
    • Drop lines here, in order.

    The next example also uses a function. Its second call raises a ValueError.

    Try it out

    Try this snippet in the Python Scratchpad on the right.

    Try this snippet
    def calculate_bmi(weight_kg, height_m):
        if weight_kg <= 0:
            raise ValueError(f"Weight must be positive, got {weight_kg}")
        if height_m <= 0:
            raise ValueError(f"Height must be positive, got {height_m}")
        return weight_kg / (height_m ** 2)
    
    print(calculate_bmi(72, 1.75))
    print(calculate_bmi(72, 0))
    Raising an exception stops a function at the moment its input is invalid, so bad data triggers a clear error at the source instead of flowing on to produce a wrong result.
    Raising an exception stops a function at the moment its input is invalid, so bad data triggers a clear error at the source instead of flowing on to produce a wrong result.

    Always make the message descriptive. A message like "Age cannot be negative" says more than "Error!". An f-string can also put the value that caused the problem into the message:

    dose_mg = -5
    if dose_mg <= 0:
        raise ValueError(f"Dose must be positive, got {dose_mg}")
    # ValueError: Dose must be positive, got -5
    Section 5

    5 Sanity checks with assert

    An assert statement is a quick sanity check. It tests if something you believe is true really is true at that moment.

    Write assert, a condition that should be true, a comma, and a message for when it is false:

    n_cases = 12
    assert n_cases > 0, "no cases passed the filter"
    print("Calculating the rate")  # Calculating the rate

    What happens depends on the condition:

    • If the condition is true, the program moves to the next line.
    • If the condition is false, the program stops at once with an AssertionError showing your message:
    n_cases = 0
    assert n_cases > 0, "no cases passed the filter"
    print("Calculating the rate")
    # AssertionError: no cases passed the filter
    Try it out

    Try this snippet in the Python Scratchpad on the right.

    Try this snippet
    features = [[1, 2], [3, 4], [5, 6]]
    labels = [0, 1, 0]
    
    assert len(features) == len(labels), "features and labels must be the same length"
    print("Lengths match - safe to continue")
    
    ages = [54, 61, 47]
    assert all(0 < a < 120 for a in ages), "ages must be between 0 and 120"
    print("All ages look reasonable")
    An assert statement checks a condition at the moment it runs, letting execution continue when the condition is true and halting the program with an AssertionError before the next line if it is false.
    An assert statement checks a condition at the moment it runs, letting execution continue when the condition is true and halting the program with an AssertionError before the next line if it is false.

    When should you use raise or assert?

    Use assert for developer errors, and raise for user errors.

    • Use assert for things that should never go wrong unless your code has a bug.
    • Use raise for things that can go wrong because of outside factors, such as bad user input.
    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

    What does print(f"{2 + 3} items") display?

    Post-test

    What does f"{4.2e-8:.2e}" produce?

    Post-test

    What does f"{0.0423:.1%}" display?

    Post-test

    Why does int("banana") raise a ValueError rather than a TypeError?

    Post-test

    A script raises KeyError: 'middle_name'. What is the most likely cause?

    Post-test

    When you read a Python traceback, which line tells you the exception type and its message?

    Post-test

    A line age = int(raw) is wrapped in a try block, with except ValueError setting age = None. If raw is "42", what is age after the block runs?

    Post-test

    What happens when Python runs assert len(a) == len(b), "length mismatch" and the two lengths are equal?

    Post-confidence

    I can write an f-string that formats a p-value in scientific notation with two decimal places.

    Not at all confident
    Fully confident
    Post-confidence

    I can read a Python traceback and identify which exception was raised and on which line.

    Not at all confident
    Fully confident
    Post-confidence

    I can wrap a risky line in try/except and decide which specific exception to name.

    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)