"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this appendix, we introduce some of the basic syntax and ideas behind the Python programming language and the Jupyter interface."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Python interpreter\n",
"\n",
"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.\n",
"\n",
"So, whenever you want your Python code to run, you give it to the Python interpreter.\n",
"\n",
"There are many ways to launch the Python interpreter. One way is to type\n",
"\n",
" python\n",
" \n",
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Hello, world. and the print() function\n",
"\n",
"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](http://www.amazon.com/The-Programming-Language-Brian-Kernighan/dp/0131103628) 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.\n",
"\n",
"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.\n",
"\n",
"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.\n",
"\n",
"To print `Hello, world.`, enter the code below. To execute the code, hit `shift+enter`."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, world.\n"
]
}
],
"source": [
"print('Hello, world.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## .py files\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Beautiful is better than ugly.\n",
"Explicit is better than implicit.\n",
"Simple is better than complex.\n",
"Complex is better than complicated.\n"
]
}
],
"source": [
"# The first few lines from The Zen of Python by Tim Peters\n",
"print('Beautiful is better than ugly.')\n",
"print('Explicit is better than implicit.')\n",
"print('Simple is better than complex.')\n",
"print('Complex is better than complicated.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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!*\n",
"\n",
"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`.\n",
"\n",
"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.\n",
"\n",
"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\n",
"\n",
" python zen.py\n",
" \n",
"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.\n",
"\n",
"To run the code in this file using the Jupyter console, you can use the `%run` **magic function**."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Beautiful is better than ugly.\n",
"Explicit is better than implicit.\n",
"Simple is better than complex.\n",
"Complex is better than complicated.\n"
]
}
],
"source": [
"%run zen.py"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Jupyter\n",
"\n",
"At this point, we have introduced JupyterLab, its text editor, and the console, as well as the Python interpreter itself. You might be asking...."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### What is Jupyter?\n",
"\n",
"From the [Project Jupyter website](http://jupyter.org):\n",
">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.\n",
"\n",
"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](http://julialang.org/) (a new language for scientific computing), [Python](http://python.org/) (which you know and love), and [R](https://www.r-project.org) (the dominant tool for statistical computation). However, you can run over 40 different languages in a JupyterLab, not just Julia, Python, and R.\n",
"\n",
"Central to Jupyter/JupyterLab are **Jupyter notebooks**. In fact, the document you are reading right now was generated from a Jupyter notebook."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Why Jupyter notebooks?\n",
"\n",
"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.\n",
"\n",
"1. *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.\n",
"2. *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](https://losc.ligo.org/s/events/GW150914/GW150914_tutorial.html) to explain the signal processing involved in their first discovery of a gravitational wave.\n",
"3. *Pedagogy.* All of the content in this book, including this appendix, was developed using Jupyter notebooks!\n",
"\n",
"Now that we know what Jupyter notebooks are and what the motivation is for using them, let's start!"
]
},
{
"cell_type": "markdown",
"metadata": {
"jp-MarkdownHeadingCollapsed": true,
"tags": []
},
"source": [
"### Launching a Jupyter notebook\n",
"\n",
"We discussed how to launch notebooks from the command line and from the Anaconda Navigator in [Chapter 0](../chapters/00_setting_up_python_computing_environment.ipynb). For convenience, those instructions are repeated here.\n",
"\n",
"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`).\n",
"\n",
" jupyter lab\n",
" \n",
"If the default browser on your machine is unsupported (e.g., Microsoft Edge), you can specify the browser you want using, for example,\n",
"\n",
" jupyter lab --browser=firefox\n",
"\n",
"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. \n",
"\n",
"Within the JupyterLab window, you will have the option to launch a notebook, a console, a terminal, or a text editor."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Cells\n",
"\n",
"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.\n",
"\n",
"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.\n",
"\n",
"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.**\n",
"\n",
"Markdown cells contain text. The text is written in **markdown**, a lightweight markup language. You can read about its syntax [here](https://www.markdownguide.org). 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.\n",
"\n",
"Markdown cells can also render LaTeX for mathematics. For example,\n",
"\n",
"```\n",
"An activating Hill function, $f(x)$, can be written as\n",
"\n",
"\\begin{align}\n",
"f(x) = \\frac{(x/k)^n}{1 + (x/k)^n}.\n",
"\\end{align}\n",
"```\n",
"\n",
"renders as:\n",
"\n",
"An activating Hill function, $f(x)$, can be written as\n",
"\n",
"\\begin{align}\n",
"f(x) = \\frac{(x/k)^n}{1 + (x/k)^n}.\n",
"\\end{align}\n",
"\n",
"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.\n",
"\n",
"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`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code cells\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello, world.\n"
]
}
],
"source": [
"# Say hello to the world.\n",
"print('hello, world.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"11"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Would show 9 if this were the last line, but it is not, so shows nothing\n",
"4 + 5\n",
"\n",
"# I hope we see 11.\n",
"5 + 6"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"# Variable assignment, so no visible output.\n",
"a = 5 + 6"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"11"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# However, now if we ask for a, its value will be displayed\n",
"a"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Display of graphics\n",
"\n",
"When we discuss plotting with [Bokeh](https://bokeh.pydata.org/), you will learn about displaying graphics in Jupyter notebooks."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Quick keys\n",
"\n",
"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.\n",
"\n",
"|Quick keys | mode | action |\n",
"|:---:|:---:|:---:|\n",
"|`Esc - m` | command | switch cell to Markdown cell|\n",
"|`Esc - y` | command | switch cell to code cell|\n",
"|`Esc - a` | command | insert cell above|\n",
"|`Esc - b` | command | insert cell below|\n",
"|`Esc - d - d` | command | delete cell|\n",
"|`Alt + Enter` | edit | execute cell and insert a cell below |\n",
"\n",
"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."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Computing environment"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Python implementation: CPython\n",
"Python version : 3.10.9\n",
"IPython version : 8.10.0\n",
"\n",
"jupyterlab: 3.5.3\n",
"\n"
]
}
],
"source": [
"%load_ext watermark\n",
"%watermark -v -p jupyterlab"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.9"
}
},
"nbformat": 4,
"nbformat_minor": 4
}