Jupyter Notebooks Introduction

Unidata Logo

Jupyter Notebooks Introduction

Unidata Python Workshop


Jupyter notebooks are a great way to have code, output, images, video, and other information in one place. Notebooks are an ideal tool for the student, research scientist, and even software developer. In this lesson we will go over the basic features of Jupyter notebooks and how to use them.

Getting Started

Before you can explore Jupyter notebooks, you need to get them up and running! On the command line, type jupyter lab and press Enter. This will start up a jupyter lab server and open your default browser connected to this server. On the main page you'll see a file explorer interface. Notice that you cannot go any further up the directory structure that where you started the server. For security reasons, you should run out of a sane sub-directory, not from your home directory. Clicking on a part of the path at the top of the page will change the working directory to that location.

The tabs at the top of the interface File, Running, and Clusters allow you to see the file explorer, state of running notebooks, and parallel execution information. In the File tab you can navigate to find notebooks and click to launch them or create new ones. Click on the New button to create a new item. New items can be:

  • Notebook - Create a new notebook
  • Text File - Opens a built-in editor to create text based files
  • Folder - Create a new directory
  • Terminal - Open an instance of your default terminal

Notebook Components

Notebooks consist of cells that contain information of various forms. New cells can be created easily by pressing a for above for b for below the current cell when in command mode.

  • Active cells have an outline around them
  • You can navigate with the mouse or arrow keys
  • The cell type is shown in the dropdown menu at the top of the notebook.
  • Think of cells as paragraphs in an essay - they contain a complete set of ideas. Splitting your notebook into properly sized cells is really an art and matter of personal preference.

Using Notebooks

Notebooks provide an easy-to-use interface to make some potenitally complicated documents. Notebooks operate in one of two modes:

  • Edit Mode - Press Enter in a cell to enter edit mode.
  • Command Mode - Press ESC or Ctrl-m to enter command mode. The notebook will accept keyboard commands.

Notebook Menus

At the top of the notebook window you will find menus containing many useful functions.

  • File - Save, copy, export notebooks
  • Edit - Move, split, cut, copy, and insert
  • View - Modify the notebook's appearance
  • Run - Run cells
  • Kernel - Interrupt, restart, or change the active kernel
  • Tabs - Control jupyter lab tabs
  • Help - Access documentation and helpful information

There are lots of keyboard commands so you never have to use a mouse, but for the workshop the Shift-Enter shortcut is probably the most useful. It runs the current cell and advances to the next cell. Ctrl-Enter will run the current cell without advancing. Shortcuts for split, merge, and delete are also very useful. Don't do these operations by hand - let the computer do the work!

Notebook Toolbar

Below the menus at the top of the notebook is a toolbar. It contains buttons to allow you to save, copy, move, etc. as well as run cells and change cell type. Generally you'll be using keyboard shortcuts, but these buttons are available. If you decide to not use the toolbar, it can be hidden in the View menu, as can the left file view panel.

Cells

Notebooks have cells that can be one of three types. Using a mix of cell types can result in a really nice looking and useful document. We'll cover the two you'll be most likely to use: code and markdown cells.

Code

Code cells contain.... well... code. While most commonly associated with Python, Jupyter notebooks can run many kernels including R, Ruby, Julia, and many more. Each notebook can only use a single kernel though. Let's run some simple code in this notebook. Remember, run the cell via the keyboard (Shift-Enter) or by pressing the button.

In [1]:
temperature = 25
In [2]:
print(temperature)
25

Notice that the standard output is displayed right below the cell that generated it. The system standard error is also displayed below cells.

In [3]:
import sys
print('I\'m afraid I\'ve made a horrible mistake', file=sys.stderr)
I'm afraid I've made a horrible mistake

The output of the cell appears as it is generated - you can see what's happening as the process is running. The cell below will countdown from 10. If this were a long process that you wanted to interrupt, you could press the button. Try it!

In [4]:
import time 

for i in range(10, 0, -1):
    print(i)
    time.sleep(1)
print("Blast off!")
10
9
8
7
6
5
4
3
2
1
Blast off!

Help on functions can be obtained by putting a ? afterwards:

In [5]:
import numpy as np
np.arange?

You can also use the tab-completion feature to help save time or find functions.

In [ ]:
 

Markdown Cells

Markdown is a convenient way to create formatted text using a simple syntax. There are different flavors of markdown, but the basics are supported across the board and generally cover 80% of the use cases. HTML is also valid in markdown cells. In fact, all of the text and the header of this notebook are markdown/HTML. With markdown you can create headings, embed images, link to other pages, create lists, and more. We aren't going to exhaustively cover markdown, but the essentials can help you make really nice notebooks. Remember, the better your documentation, the more you'll thank yourself later. Think of the notebook as a lab notebook.

Basic Text Formatting

Text can be made bold or italic by enclosing it in astericks. Notice that a preview even renders in the cell to help you see the formatting that will be applied!

**This text will be bold**
*This text will be in italics*

This text will be bold

This text will be in italics

Headings

You can create headings by prepending the text with a number of octothorpes (that's these: #). These go up to five levels deep!

# Heading
## Sub-Heading
### Subsub-Heading
#### Subsubsub-Heading
##### Subsubsubsub-Heading

Heading

Sub-Heading

Subsub-Heading

Subsubsub-Heading
Subsubsubsub-Heading

PS - Notice the horizontal lines helping separate content above? Create them with ---

Lists

You can create ordered and unordered lists with markdown in a format that is much more human readable and editable than making an HTML list. For ordered lists the markdown rendering will even take care of numbering, just use all ones. Remember, let the computer do your work! Sublist formatting is also handled in a sane way automatically.


* This is an unordered list
* It is useful for many things
    * Grocery lists
    * Plans to take over the world
        * Large plans may require multiple lists

  • This is an unordered list
  • It is useful for many things
    • Grocery lists
    • Plans to take over the world
      • Large plans may require multiple lists

1. Create an ordered list
    1. Use numbers
    1. Let the computer handle numbering
    1. Look super organized
1. Take over the world

  1. Create an ordered list
    1. Use numbers
    2. Let the computer handle numbering
    3. Look super organized
  2. Take over the world

Other Text Formatting

There are a few other handy text formatting tricks that don't really get their own section, but are nice to see.

Blockquoting is handy for inserting quotes from papers, documents, etc. Just prepend all of the lines with >.

> I was born not knowing and have had only a little time to
> change that here and there.
> \- Richard P. Feynman

I was born not knowing and have had only a little time to change that here and there. - Richard P. Feynman


The notebook environment also supports so called GitHub flavored markdown. You can tripple quote code blocks and get a nicely formatted output. Providing the langauge even provides syntax highlighting.


```python
import time 

for i in range(10, 0, -1):
    print(i)
    time.sleep(1)
print("Blast off!")
```

import time 

for i in range(10, 0, -1):
    print(i)
    time.sleep(1)
print("Blast off!")

Tables

Making tables is horrible in HTML. Markdown (multi-markdown actually) makes really good looking tables with simple text input.


| Date | Max Temp | Min Temp |
| ---- | -------- | -------- |
| 4/12 | 75       | 65       |
| 4/13 | 80       | 68       |
| 4/14 | 68       | 50       |

Date Max Temp Min Temp
4/12 75 65
4/13 80 68
4/14 68 50
Images

Inserting images in markdown is a one liner!

![alt text](/path/to/img.jpg "Title")

MetPy Logo

Equations

Notebooks are MathJax-aware, so using a subset of the $\LaTeX$ syntax, you can easily render complex equations in notebook cells. We don't have time to go into the details of the syntax, but you can find many tutorials on the topic. Showing a few examples will give you the idea though!

To put equations inline with text enclose them in $, to put them on separate lines enclose them in $$.

Let's start with a simple example, Newton's second law:

$$F = m a$$
$$F = m a$$

We can also typeset much more complicated equations with a little more syntax effort:

$$\left( \frac{Dv}{Dt} \right) = -2 \Omega u \text{sin}\phi - \frac{u^2}{a} \text{tan}\phi$$
$$\left( \frac{Dv}{Dt} \right) = -2 \Omega u \text{sin}\phi - \frac{u^2}{a} \text{tan}\phi$$
$$\frac{\partial\zeta}{\partial t} = - V \cdot \nabla(\zeta + f) - \omega \frac{\partial \zeta}{\partial p}
- (\zeta + f) \nabla \cdot V + k \cdot \left(\frac{\partial V}{\partial p} \times \nabla \omega \right)$$
$$\frac{\partial\zeta}{\partial t} = - V \cdot \nabla(\zeta + f) - \omega \frac{\partial \zeta}{\partial p} - (\zeta + f) \nabla \cdot V + k \cdot \left(\frac{\partial V}{\partial p} \times \nabla \omega \right)$$