Python and Jupyter Notebooks
Python and Jupyter Notebooks for Biology Data
What a notebook actually is
A Jupyter notebook is a document made of cells connected to a running Python process called the kernel.
- Markdown cells hold formatted text: the question you are asking, the units of a measurement, what a figure shows.
- Code cells are sent to the kernel when you run them. The label In [7]: means that this cell's most recent run was the seventh execution in this session.
The kernel's memory is the single source of truth. Variables persist from one cell to the next. What matters is the order in which cells were run, not their order on the page.
If you edit a cell, nothing changes until you run it, and running one cell never re-runs any other. This is why a notebook can look correct from top to bottom and still hold stale values.
Two habits prevent most confusion:
- Read the execution counts. Each cell shows the number of its most recent run, so the counts can expose a gap (a number that no visible cell displays) or cells whose numbers are out of page order. They do not preserve the full history of every earlier run.
- Before trusting or sharing results, use Restart Kernel and Run All. That rebuilds the state from the top in page order, so the page and the memory agree.
Worked example. One cell contains count = 0 and a second contains count = count + 1. Run the first cell once and the second cell three times, and count holds 3, even though the page shows only one increment. Restart and run all, and it holds 1.
What gets displayed. An unsuppressed final expression with a displayable, non-None result normally appears as Out[n]. A trailing semicolon suppresses that display, and a final expression that yields None produces no Out[n].
The function print() writes text instead and produces no Out. A plain arithmetic expression displays its result without changing its operands.
An expression can also call a method with a side effect: with readings = [0.12, 0.98], a cell ending in readings.pop() displays 0.98 and leaves readings as [0.12].
Values, types and expressions
Type | Example | Notes |
|---|---|---|
int | 42 | whole numbers |
float | 3.4 | decimals; results can show tiny rounding digits |
str | "wild type" | text in quotes |
bool | True | results of comparisons such as 5 > 2 |
list | [152, 167, 171] | ordered, indexed from 0 |
dict | {"wt": 42, "mutant": 17} | look up values by key |
Arithmetic. 17 / 5 is 3.4, because / always gives a float. 17 // 5 is 3 (floor division), 17 % 5 is 2 (remainder), and 2 ** 3 is 8. Precedence follows mathematics: ** first, then *, /, // and %, then + and -. Comparisons are evaluated after the arithmetic on both sides.
Indexing and slicing
Take heights = [152, 167, 171, 180, 158, 163].
- Positions start at 0, so heights[0] is 152.
- Negative indices count from the end: heights[-2] is 158.
- A slice heights[start:stop] includes start but stops before stop, so heights[2:4] is [171, 180]. For a slice with the default step of 1, non-negative in-range bounds and start <= stop, the number of items is stop - start. Out-of-range bounds are clipped and negative bounds count from the end, so heights[4:10] has 2 items, not 6. In any other case, check with len(heights[start:stop]).
- len(heights) is 6, and the last valid index is len - 1 = 5.
Inspecting simple data
Before any analysis, look at the data. len() counts items, min() and max() give the extremes, and sorted() returns a new ascending list. For a nonempty collection of ordinary int or float values, sum(x) / len(x) computes the arithmetic mean as a float; an empty collection raises ZeroDivisionError.
For a dictionary such as counts = {"wt": 42, "mutant": 17}, counts["wt"] looks up one value, counts.values() gives all the values, and len(counts) counts the keys. Looking up a key that does not exist raises a KeyError, which usually means a typo or an unexpected label.
A first plot
import matplotlib.pyplot as plt
dose_mg = [0, 10, 20, 40]
response = [2.0, 3.1, 4.4, 5.0]
plt.plot(dose_mg, response, "o-")
plt.xlabel("Dose (mg)")
plt.ylabel("Response (units)")
plt.show()In plt.plot(x, y), the first list sets the horizontal positions and the second sets the vertical positions, pairing items by index. The axis labels are just text.
Matplotlib does not check that they describe the lists you passed. A quick sanity check is to pick one point, find its pair of values in the lists, and confirm that it appears where you expect.
Mark Yourself Question
- Grab a piece of paper and try this problem yourself.
- When you're done, check the "I have answered this question" box below.
- View the solution and report whether you got it right or wrong.
Optical density readings from a bacterial culture are stored as:
od = [0.12, 0.25, 0.51, 0.98]
od[-1] / od[0]What value does this expression produce? Report it to two decimal places, and state its type.