B1. Hello, world.
In this appendix, we introduce some of the basic syntax and ideas behind the Python programming language and the Jupyter interface.
The Python interpreter
Python is an interpreted language, which means that each line of code you write is translated, or interpreted, into a set of instructions that your machine can understand by the Python interpreter. This stands in contrast to compiled languages. For these languages (the dominant ones being Fortran, C, and C++), your entire code is translated into machine language before you ever run it. When you execute your program, it is already in machine language.
So, whenever you want your Python code to run, you give it to the Python interpreter.
There are many ways to launch the Python interpreter. One way is to type
python
on the command line of a terminal. This launches the vanilla Python interpreter. Because we are using Python code to explore biological circuit design, we will never really use this. Rather, we will have a greatly enhanced Python experience using Jupyter notebooks. Nevertheless, as you go beyond notebooks and do more sophisticated computing in your adventures with biological circuits, it is good to know about running Python outside of notebooks, so we will do that now.
Hello, world. and the print() function
Traditionally, the first program anyone writes when learning a new language is called “Hello, world.
” In this program, the words “Hello, world.
” are printed on the screen. The original Hello, world.
was likely written by Brian Kernighan, one of the inventors of Unix, and the author of the classic and authoritative book on the C programming language. In his original, the printed text was
“hello, world
” (no period or capital H
), but people use lots of variants.
We will first write and run this little program using a JupyterLab console. After launching JupyterLab, you probably already have the Launcher in your JupyterLab window. If you do not, you can expand the Files
tab at the left of your JupyterLab window (if it is not already expanded) by clicking on that tab, or alternatively hit ctrl+b
(or cmd+b
on macOS). At the top of the Files
tab is a +
sign, which gives you a Jupyter Launcher.
In the Jupyter Launcher, click the Python 3
icon under Console
. This will launch a console, which has a large white space above a prompt that says In []:
. You can enter Python code in this prompt, and it will be executed.
To print Hello, world.
, enter the code below. To execute the code, hit shift+enter
.
[1]:
print('Hello, world.')
Hello, world.
Hooray! We just printed Hello, world.
to the screen. To do this, we used Python’s built-in print()
function. The print()
function takes a string as an argument. It then prints that string to the screen. We will learn more about function syntax later, but we can already see the rough syntax with the print()
function.
.py files
Now let’s use our new knowledge of the print()
function to have our computer say a bit more than just Hello, world.
Type these lines in at the prompt, hitting enter
each time you need a new line. After you’ve typed them all in, hit shift+enter
to run them.
[2]:
# The first few lines from The Zen of Python by Tim Peters
print('Beautiful is better than ugly.')
print('Explicit is better than implicit.')
print('Simple is better than complex.')
print('Complex is better than complicated.')
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Note that the first line is preceded with a #
sign, and the Python interpreter ignored it. The #
sign denotes a comment, which is ignored by the interpreter, but very very important for the human!
While the console prompt was nice for entering all of this, a better option is to store them in a file, and then have the Python interpreter run the lines in the file. This is how you typically store Python code, and the suffix of such files is .py
.
So, let’s create a .py
file. To do this, use the JupyterLab Launcher to launch a text editor. Once it is launched, you can right click on the tab of the text editor window to change the name. We will call this file zen.py
. Within this file, enter the four lines of code you previously entered in the console prompt. Be sure to save it.
To run the code in this file, you can invoke the Python interpreter at the command line, followed by the file name. I.e., enter
python zen.py
at the command line. Note that when you run code this way, the interpreter exits after completion of running the code, and you do not get a prompt.
To run the code in this file using the Jupyter console, you can use the %run
magic function.
[3]:
%run zen.py
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
To shut down the console, you can click on the Running
tab at the left of the JupyterLab window and click on SHUTDOWN
next to the console.
Jupyter
At this point, we have introduced JupyterLab, its text editor, and the console, as well as the Python interpreter itself. You might be asking….
What is Jupyter?
From the Project Jupyter website: >Project Jupyter is an open source project was born out of the IPython Project in 2014 as it evolved to support interactive data science and scientific computing across all programming languages.
So, Jupyter is an extension of IPython the pushes interactive computing further. It is language agnostic as its name suggests. The name “Jupyter” is a combination of Julia (a new language for scientific computing), Python (which you know and love), and R (the dominant tool for statistical computation). However, you can run over 40 different languages in a JupyterLab, not just Julia, Python, and R.
Central to Jupyter/JupyterLab are Jupyter notebooks. In fact, the document you are reading right now was generated from a Jupyter notebook.
Why Jupyter notebooks?
When writing code you will reuse, you should develop fully tested modules using .py
files. You can always import those modules when you are using a Jupyter notebook (more on modules and importing them later in this appendix). So, a Jupyter notebook is not good for an application where you are building reusable code or scripts. However, Jupyter notebooks are very useful in the following applications.
Exploring data/analysis. Jupyter notebooks are great for trying things out with code, or exploring a data set. This is an important part of the research process. The layout of Jupyter notebooks is great for organizing thoughts as you synthesize them.
Sharing your thinking in your analysis. Because you can combine nicely formatted text and executable code, Jupyter notebooks are great for sharing how you go about doing your calculations with collaborators and with readers of your publications. Famously, LIGO used a Jupyter notebook to explain the signal processing involved in their first discovery of a gravitational wave.
Pedagogy. All of the content in this book, including this appendix, was developed using Jupyter notebooks!
Now that we know what Jupyter notebooks are and what the motivation is for using them, let’s start!
Launching a Jupyter notebook
We discussed how to launch notebooks from the command line and from the Anaconda Navigator in Chapter 0. For convenience, those instructions are repeated here.
You can launch JupyterLab is from the command line. On Windows, this is usually accessed through PowerShell and on macOS through Terminal. To launch JupyterLab, type the following on the command line (again, after you have done conda activate biocircuits
).
jupyter lab
If the default browser on your machine is unsupported (e.g., Microsoft Edge), you can specify the browser you want using, for example,
jupyter lab --browser=firefox
Alternatively, you can use the Anaconda Navigator. Upon launching the Navigator, you should see an option to launch JupyterLab on the Home
screen. (Be sure that you select All applications
on biocircuits
in the top pulldown menus.) After clicking Launch
for JupyterLab, a new browser window or tab will open with JupyterLab running.
Within the JupyterLab window, you will have the option to launch a notebook, a console, a terminal, or a text editor.
Cells
A Jupyter notebook consists of cells. The two main types of cells you will use are code cells and markdown cells, and we will go into their properties in depth momentarily. First, an overview.
A code cell contains actual code that you want to run. You can specify a cell as a code cell using the pulldown menu in the toolbar of your Jupyter notebook. Otherwise, you can can press Esc
and then y
(denoted Esc - y
”) while a cell is selected to specify that it is a code cell. Note that you will have to hit enter after doing this to start editing it.
If you want to execute the code in a code cell, hit Enter
while holding down the Shift
key (denoted Shift + Enter
). Note that code cells are executed in the order you shift-enter them. That is to say, the ordering of the cells for which you hit Shift + Enter
is the order in which the code is executed. If you did not explicitly execute a cell early in the document, its results are not known to the Python interpreter. This is a very important point and is often a source of
confusion and frustration for students.
Markdown cells contain text. The text is written in markdown, a lightweight markup language. You can read about its syntax here. Note that you can also insert HTML into markdown cells, and this will be rendered properly. As you are typing the contents of these cells, the results appear as text. Hitting Shift + Enter
renders the text in the formatting you specify.
Markdown cells can also render LaTeX for mathematics. For example,
An activating Hill function, $f(x)$, can be written as
\begin{align}
f(x) = \frac{(x/k)^n}{1 + (x/k)^n}.
\end{align}
renders as:
An activating Hill function, \(f(x)\), can be written as
\begin{align} f(x) = \frac{(x/k)^n}{1 + (x/k)^n}. \end{align}
You can specify a cell as being a markdown cell in the Jupyter toolbar, or by hitting Esc - m
in the cell. Again, you have to hit enter after using the quick keys to bring the cell into edit mode.
In general, when you want to add a new cell, you can click the +
icon on the notebook toolbar. The shortcut to insert a cell below is Esc - b
and to insert a cell above is Esc - a
. Alternatively, you can execute a cell and automatically add a new one below it by hitting Alt + Enter
.
Code cells
Below is an example of a code cell printing hello, world.
Notice that the output of the print statement appears in the same cell, though separate from the code block.
[4]:
# Say hello to the world.
print('hello, world.')
hello, world.
If you evaluate a Python expression that returns a value, that value is displayed as output of the code cell. This only happens for the last line of the code cell.
[5]:
# Would show 9 if this were the last line, but it is not, so shows nothing
4 + 5
# I hope we see 11.
5 + 6
[5]:
11
Note, however, if the last line does not return a value, such as if we assigned value to a variable, there is no visible output from the code cell.
[6]:
# Variable assignment, so no visible output.
a = 5 + 6
[7]:
# However, now if we ask for a, its value will be displayed
a
[7]:
11
Display of graphics
When we discuss plotting with Bokeh, you will learn about displaying graphics in Jupyter notebooks.
Quick keys
There are some keyboard shortcuts that are convenient to use in JupyterLab. We already encountered many of them. Importantly, pressing Esc
brings you into command mode in which you are not editing the contents of a single cell, but are doing things like adding cells. Below are some useful quick keys. If two keys are separated by a +
sign, they are pressed simultaneously, and if they are separated by a -
sign, they are pressed in succession.
Quick keys |
mode |
action |
---|---|---|
|
command |
switch cell to Markdown cell |
|
command |
switch cell to code cell |
|
command |
insert cell above |
|
command |
insert cell below |
|
command |
delete cell |
|
edit |
execute cell and insert a cell below |
There are many others (and they are shown in the pulldown menus within JupyterLab), but these are the ones I seem to encounter most often.
Computing environment
[8]:
%load_ext watermark
%watermark -v -p jupyterlab
Python implementation: CPython
Python version : 3.10.9
IPython version : 8.10.0
jupyterlab: 3.5.3