Getting Started with Jupyter Notebook

Overview
  • Teaching: 25
  • Exercises: 15
  • Questions:
    • How do I use JupyterLab/Notebook to run Python?
    • How do I write, run, and document code in notebooks?
  • Objectives:
    • Launch the JupyterLab server.
    • Create a new Python script.
    • Create a Jupyter notebook.
    • Shutdown the JupyterLab server.
    • Understand the difference between a Python script and a Jupyter notebook.
    • Create Markdown cells in a notebook.
    • Create and run Python cells in a notebook.

To run Python, we are going to use Jupyter Notebooks via JupyterLab for the remainder of this workshop. Jupyter notebooks are common in data science and visualization and serve as a convenient common-denominator experience for running Python code interactively where we can easily view and share the results of our Python code.

There are other ways of editing, managing, and running code. Software developers often use an integrated development environment (IDE) like PyCharm or Visual Studio Code, or text editors like Vim or Emacs, to create and edit their Python programs. After editing and saving your Python programs you can execute those programs within the IDE itself or directly on the command line. In contrast, Jupyter notebooks let us execute and view the results of our Python code immediately within the notebook.

JupyterLab has several other handy features:

Each notebook contains one or more cells that contain code, text, or images.

Getting Started with JupyterLab

JupyterLab is an application server with a web user interface from Project Jupyter that enables one to work with documents and activities such as Jupyter notebooks, text editors, terminals, and even custom components in a flexible, integrated, and extensible manner. JupyterLab requires a reasonably up-to-date browser (ideally a current version of Chrome, Safari, or Firefox); Internet Explorer versions 9 and below are not supported.

JupyterLab is included as part of the Anaconda Python distribution. If you have not already installed the Anaconda Python distribution, see the setup instructions for installation instructions.

In this lesson we will run JupyterLab locally on our own machines so it will not require an internet connection besides the initial connection to download and install Anaconda and JupyterLab

  • Start the JupyterLab server on your machine
  • Use a web browser to open a special localhost URL that connects to your JupyterLab server
  • The JupyterLab server does the work and the web browser renders the result
  • Type code into the browser and see the results after your JupyterLab server has finished executing your code
JupyterLab? What about Jupyter notebooks?

JupyterLab is the next stage in the evolution of the Jupyter Notebook. If you have prior experience working with Jupyter notebooks, then you will have a good idea of what to expect from JupyterLab.

Experienced users of Jupyter notebooks interested in a more detailed discussion of the similarities and differences between the JupyterLab and Jupyter notebook user interfaces can find more information in the JupyterLab user interface documentation.

Starting JupyterLab

You can start the JupyterLab server through the command line or through an application called Anaconda Navigator. Anaconda Navigator is included as part of the Anaconda Python distribution.

macOS - Command Line

To start the JupyterLab server you will need to access the command line through the Terminal. There are two ways to open Terminal on Mac.

  1. In your Applications folder, open Utilities and double-click on Terminal
  2. Press Command + spacebar to launch Spotlight. Type Terminal and then double-click the search result or hit Return

After you have launched Terminal, type the command to launch the JupyterLab server.

$ jupyter lab

Windows Users - Command Line

To start the JupyterLab server you will need to access the Anaconda Prompt.

Press Windows Logo Key and search for Anaconda Prompt, click the result or press enter.

After you have launched the Anaconda Prompt, type the command:

$ jupyter lab

Anaconda Navigator

To start a JupyterLab server from Anaconda Navigator you must first start Anaconda Navigator (click for detailed instructions on macOS, Windows, and Linux). You can search for Anaconda Navigator via Spotlight on macOS (Command + spacebar), the Windows search function (Windows Logo Key) or opening a terminal shell and executing the anaconda-navigator executable from the command line.

After you have launched Anaconda Navigator, click the Launch button under JupyterLab. You may need to scroll down to find it.

Here is a screenshot of an Anaconda Navigator page similar to the one that should open on either macOS or Windows.

Anaconda Navigator landing page

And here is a screenshot of a JupyterLab landing page that should be similar to the one that opens in your default web browser after starting the JupyterLab server on either macOS or Windows.

JupyterLab landing page

The JupyterLab Interface

JupyterLab has many features found in traditional integrated development environments (IDEs) but is focused on providing flexible building blocks for interactive, exploratory computing.

The JupyterLab Interface consists of the Menu Bar, a collapsable Left Side Bar, and the Main Work Area which contains tabs of documents and activities.

Main Work Area

The main work area in JupyterLab enables you to arrange documents (notebooks, text files, etc.) and other activities (terminals, code consoles, etc.) into panels of tabs that can be resized or subdivided. A screenshot of the default Main Work Area is provided below.

If you do not see the Launcher tab, click the blue plus sign under the “File” and “Edit” menus and it will appear.

JupyterLab Main Work Area

Drag a tab to the center of a tab panel to move the tab to the panel. Subdivide a tab panel by dragging a tab to the left, right, top, or bottom of the panel. The work area has a single current activity. The tab for the current activity is marked with a colored top border (blue by default).

Creating a Python script

  • To start writing a new Python program click the Text File icon under the Other header in the Launcher tab of the Main Work Area.
    • You can also create a new plain text file by selecting the New -> Text File from the File menu in the Menu Bar.
  • To convert this plain text file to a Python program, select the Save File As action from the File menu in the Menu Bar and give your new text file a name that ends with the .py extension.
    • The .py extension lets everyone (including the operating system) know that this text file is a Python program.
    • This is convention, not a requirement.

Creating a Jupyter Notebook

To open a new notebook click the Python 3 icon under the Notebook header in the Launcher tab in the main work area. You can also create a new notebook by selecting New -> Notebook from the File menu in the Menu Bar.

Additional notes on Jupyter notebooks.

  • Notebook files have the extension .ipynb to distinguish them from plain-text Python programs.
  • Notebooks can be exported as Python scripts that can be run from the command line.

Below is a screenshot of a Jupyter notebook running inside JupyterLab. If you are interested in more details, then see the official notebook documentation.

Example Jupyter Notebook

How It’s Stored
  • The notebook file is stored in a format called JSON.
  • Just like a webpage, what’s saved looks different from what you see in your browser.
  • But this format allows Jupyter to mix source code, text, and images, all in one file.
Code vs. Text

Jupyter mixes code and text in different types of blocks, called cells. We often use the term “code” to mean “the source code of software written in a language such as Python”. A “code cell” in a Notebook is a cell that contains software; a “text cell” is one that contains ordinary prose written for human beings.

The Notebook has Command and Edit modes.

If you press Esc and Enter alternately, the outer border of your code cell will change from gray to blue.

  1. Edit mode (blue cell border): Type code or text into a cell. Enter edit mode by pressing Enter or clicking inside a cell. This mode changes the content of cells.

  2. Command mode (grey cell border): Use keyboard shortcuts to manage cells. Enter command mode by pressing Esc. Command mode allows you to edit notebook-level features.

When in Command mode,

  • The b key will make a new cell below the currently selected cell.
  • The a key will make one above.
  • The x key will delete the current cell.
  • The D+ D will delete selected cells
  • The z key will undo your last cell operation (which could be a deletion, creation, etc).
  • All actions can be done using the menus, but there are lots of keyboard shortcuts to speed things up.

To view all shortcuts, go to Help → Keyboard Shortcuts, or press H in command mode.

Command Vs. Edit
  • In the Jupyter notebook page are you currently in Command or Edit mode?
  • Switch between the modes.
  • Use the shortcuts to generate a new cell.
  • Use the shortcuts to delete a cell.
  • Use the shortcuts to undo the last cell operation you performed.
  • Command mode has a grey border and Edit mode has a blue border.
  • Use Esc and Enter to switch between modes.
  • You need to be in Command mode (Press Esc if your cell is blue). Type b or a.
  • You need to be in Command mode (Press Esc if your cell is blue). Type x.
  • You need to be in Command mode (Press Esc if your cell is blue). Type z.

Use the keyboard and mouse to select and edit cells.

  • Pressing the Enter key turns the border blue and engages Edit mode, which allows you to type within the cell.
  • Because we want to be able to write many lines of code in a single cell, pressing the Enter key when in Edit mode (blue) moves the cursor to the next line in the cell just like in a text editor.
  • We need some other way to tell the Notebook we want to run what’s in the cell.
  • Pressing Shift+Enter together will execute the contents of the cell.
  • Notice that the Enter and Shift keys on the right of the keyboard are right next to each other.

Running and Managing Cells

  • Run a cell: Shift + Enter

  • Run selected cells: Ctrl + Enter (Mac: Cmd + Return)

  • Save notebook: Ctrl + S (Mac: Cmd + S)

The Notebook will turn Markdown into pretty-printed documentation.

Notebooks can also render Markdown.

  • A simple plain-text format for writing lists, links, and other things that might go into a web page.
  • Equivalently, a subset of HTML that looks like what you’d send in an old-fashioned email.

Notebooks contain different cell types:

  • Code cells: For writing and running Python code.
  • Markdown cells: For formatted text, headings, lists, etc.
  • Raw cells: For unformatted text.

Change cell type using the drop-down menu in the toolbar.

  • Turn the current cell into a Markdown cell by entering the Command mode (Esc/gray) and press the M key.
  • In [ ]: will disappear to show it is no longer a code cell and you will be able to write in Markdown.
  • Turn the current cell into a Code cell by entering the Command mode (Esc/gray) and press the y key.

Markdown does most of what HTML does.

Showing some markdown syntax and its rendered output.
Markdown code Rendered output
*   Use asterisks
*   to create
*   bullet lists.

  • Use asterisks
  • to create
  • bullet lists.
1.   Use numbers
1.   to create
1.   bullet lists.

  1. Use numbers
  2. to create
  3. numbered lists.
*  You can use indents
  *  To create sublists
  *  of the same type
*  Or sublists
  1. Of different
  1. types

  • You can use indents
    • To create sublists
    • of the same type
  • Or sublists
    1. Of different
    2. types
# A Level-1 Heading

A Level-1 Heading

## A Level-2 Heading (etc.)

A Level-2 Heading (etc.)

Line breaks
don't matter.

But blank lines
create new paragraphs.

Line breaks don’t matter.

But blank lines create new paragraphs.

[Links](http://software-carpentry.org)
are created with `[...](...)`.
Or use [named links][data-carp].

[data-carp]: http://datacarpentry.org

Links are created with [...](...). Or use [named links][data_carpentry].

Creating Lists in Markdown

Create a nested list in a Markdown cell in a notebook that looks like this:

  1. Get funding.
  2. Do work.
  • Design experiment.
  • Collect data.
  • Analyze.
  1. Write up.
  2. Publish.

This challenge integrates both the numbered list and bullet list. Note that the bullet list is indented 2 spaces so that it is inline with the items of the numbered list.

1.  Get funding.
2.  Do work.
    *   Design experiment.
    *   Collect data.
    *   Analyze.
3.  Write up.
4.  Publish.
More Math

What is displayed when a Python cell in a notebook that contains several calculations is executed? For example, what happens when this cell is executed?

7 * 3
2 + 1

Python returns the output of the last calculation.

3
Change an Existing Cell from Code to Markdown

What happens if you write some Python in a code cell and then you switch it to a Markdown cell? For example, put the following in a code cell:

x = 6 * 7 + 12
print(x)

And then run it with Shift+Enter to be sure that it works as a code cell. Now go back to the cell and use Esc then m to switch the cell to Markdown and “run” it with Shift+Enter. What happened and how might this be useful?

The Python code gets treated like Markdown text. The lines appear as if they are part of one contiguous paragraph. This could be useful to temporarily turn on and off cells in notebooks that get used for multiple purposes.

x = 6 * 7 + 12 print(x)

Closing JupyterLab

  • From the Menu Bar select the “File” menu and then choose “Shut Down” at the bottom of the dropdown menu. You will be prompted to confirm that you wish to shutdown the JupyterLab server (don’t forget to save your work!). Click “Shut Down” to shutdown the JupyterLab server.
  • To restart the JupyterLab server you will need to re-run the following command from a shell.
$ jupyter lab
Closing JupyterLab

Practice closing and restarting the JupyterLab server.

Key Points
  • Jupyter Notebook provides an interactive environment for Python programming
  • Code cells execute Python code, Markdown cells contain formatted text
  • Keyboard shortcuts improve efficiency when working with notebooks
  • Edit mode is for typing content, Command mode is for cell operations
  • Save your work frequently using Ctrl+S (Cmd+S on Mac)
  • The Notebook will turn Markdown into pretty-printed documentation.
  • Markdown does most of what HTML does.

Next →