28.1.1: Jupyter Notebooks
-
- Last updated
- Save as PDF
The concept of a Jupyter Notebook is simple: it’s a Web page with editable “cells.” Each cell is a little text window you can type in.
There are three kinds of cells in Jupyter Notebooks:
-
Raw
- “Raw” is dumb. Never use it.
-
Markdown
- “Markdown” cells are for English text, not Python code. They’re mostly used to describe and annotate what you’re doing in the code cells, like a running commentary. You can type plain-ol’ text in a Markdown cell, plus various cutesy formatting adornments like boldface (putting double-splats (**) around a word or phrase), italics (single splats), outline headings (prefacing a line with one or more hashtags (like # or ###), and so forth. 2 When you type in a Markdown cell, you see the raw text and formatting; to actually get Jupyter to render your cells and make them pretty, you choose “Run All” from the “Cell” menu.
-
Code
- The most important cells are “Code” cells which contain (duh) code. When executed (again, by choosing “Run All” from the “Cell” menu) they actually carry out the Python instructions you have typed in that cell, and display any results.
By the way, a common snafu is to somehow accidentally click in a way that changes the type of a cell from “Code” to one of the other types. If you do this, the Python code in that cell won’t execute until you change the type back to “Code” (more on this below).
Figure 2.1.1 shows a Jupyter Notebook hosted by the CoCalc cloud computing platform, which we’ll use this semester. It has two cells, one Markdown and one Code. Note carefully the cell-type dropdown which is kind of hidden in the middle of the page: it currently reads “Code” because the second cell is the one that’s highlighted. (If we clicked to highlight and edit the top cell, that dropdown would change to “Markdown.”)
The top figure shows the two cells before the user has done a “Run All” from the “Cell” menu: all the Markdown is unrendered (see the literal splats and hashtags) and the code is just sitting there. After “Run All,” the picture changes: you see the formatted message in the top cell, and the output of the Python code snippet after it runs. (The latter is easy to miss; stare at that bottom picture and find the “ Our country is 245 years old! ” message. That’s the “output.”) We haven’t yet covered what that Python code means (that’s the main subject of this book) but you can probably guess some of what it’s doing.
Figure \(\PageIndex{1}\): A Jupyter Notebook with one Markdown cell and one Code cell. In the top image, the two cells have been edited but not yet “run” – hence the Markdown formatting is unrendered and the code has not been executed. The bottom pane shows both cells after the use has chosen “Run All” from the “Cell” menu.
2 For a complete list of formatting options, see https://github.com/ adam-p/markdown-here/wiki/Markdown-Cheatsheet .