Module 3: Jupyter Notebook

Learning Objectives

By the end of this module, you will be able to:

  • Navigate the Jupyter Notebook interface confidently

  • Write Markdown and code cells effectively

  • Use keyboard shortcuts to speed up your workflow

  • Leverage magic commands for system integration

  • Create interactive widgets

  • Organise notebooks and export them to various formats


What is Jupyter Notebook?

Jupyter Notebook is an open-source web application that allows you to create and share documents containing live code, equations, visualisations, and narrative text. It is the de facto standard environment for data science with Python.

The name Jupyter is a reference to Julia, Python, and R — the three core languages it was originally designed for.

Installation

Jupyter is included in the Anaconda distribution. To install it separately:

pip install jupyter notebook
# OR
conda install jupyter

Starting the notebook server

jupyter notebook

This opens the notebook dashboard at http://localhost:8888.

Note

VS Code also includes built-in Jupyter support. You can open .ipynb files directly in VS Code without starting the notebook server, which is often more convenient for development workflows.

Notebook Interface

A notebook consists of a sequence of cells. There are two primary cell types:

Cell Type

Purpose

Code

Execute Python (or other kernel) code

Markdown

Write formatted text, equations, images

Cell modes

  • Command mode (blue border) — press Esc to enter

  • Edit mode (green border) — press Enter to enter

Markdown Cells

Markdown cells support MyST (Markedly Structured Text) formatting, which extends standard Markdown with features like admonitions and cross-references.

# Heading 1
## Heading 2
### Heading 3

**Bold text**, *italic text*, ~~strikethrough~~

- Bullet list
- Second item

1. Numbered list
2. Second item

[Link text](https://example.com)

`inline code`

```python
# Fenced code block
print("Hello")

Blockquote

Table

Header

Cell

Cell


### LaTeX equations

\[ \mu = \frac{1}{n} \sum_{i=1}^{n} x_i \]

```{tip}
Use `$` for inline math and `$$` for display math. Jupyter renders LaTeX via MathJax automatically.

Keyboard Shortcuts

Command mode (press Esc first)

Shortcut

Action

Enter

Enter edit mode

A

Insert cell above

B

Insert cell below

DD

Delete cell

M

Convert to Markdown cell

Y

Convert to Code cell

Shift + Enter

Run cell and select next

Ctrl + Enter

Run cell and stay

Alt + Enter

Run cell and insert below

I, I

Interrupt kernel

0, 0

Restart kernel

1–6

Set heading level (Markdown)

Edit mode

Shortcut

Action

Ctrl + /

Toggle comment

Tab

Code completion / indent

Shift + Tab

Show docstring

Ctrl + Shift + -

Split cell at cursor

Warning

Get comfortable with Shift + Enter — it is the most frequently used shortcut. Use DD carefully as deleted cells cannot be recovered.

Magic Commands

Magic commands are special Jupyter commands prefixed with % (line magic) or %% (cell magic).

Line magics (%)

%matplotlib inline        # Display plots inline
%timeit sum(range(1000))  # Time a statement
%whos                    # List all variables
%lsmagic                 # List all available magics
%pwd                     # Print working directory
%load_ext autoreload     # Auto-reload modules
%autoreload 2

Cell magics (%%)

%%timeit
s = 0
for i in range(10000):
    s += i ** 2

%%bash
echo "This runs in the system shell"
ls -la

%%writefile output.txt
This text is written to a file
from inside the notebook

Note

The %%writefile magic is extremely useful for exporting code cells to standalone Python scripts.

Interactive Widgets

Widgets bring interactivity to notebooks, allowing you to create sliders, dropdowns, and buttons.

import ipywidgets as widgets
from IPython.display import display

# Simple slider widget
slider = widgets.IntSlider(
    value=50,
    min=0,
    max=100,
    step=1,
    description="Value:",
)

display(slider)

# Interactive function
@widgets.interact(x=(0, 10, 0.5), y=(0, 10, 0.5))
def plot_interactive(x=5, y=3):
    print(f"x = {x}, y = {y}, sum = {x + y}")

Common widget types

widgets.FloatSlider(value=3.14, min=0, max=10, step=0.1)
widgets.Dropdown(options=["A", "B", "C"], value="A")
widgets.Checkbox(value=True, description="Enable")
widgets.Button(description="Click me")
widgets.Text(value="Type here", description="Input:")

Notebook Organisation

Best practices

  1. Use a clear naming convention: 01-data-loading.ipynb, 02-exploratory-analysis.ipynb

  2. Start with a title and description cell — explain what the notebook does

  3. Separate concerns — one notebook per analysis stage

  4. Keep output clean — clear unnecessary output before committing

  5. Use Markdown headings for navigation (they appear in the table of contents)

Collapsible sections (MyST)

+++ {"cell_type": "markdown", "collapsed": true}

## Optional Details

Hidden content that can be expanded.

Exporting Notebooks

Jupyter supports multiple export formats:

# Command line
jupyter nbconvert --to script notebook.ipynb           # Python script
jupyter nbconvert --to html notebook.ipynb             # HTML
jupyter nbconvert --to pdf notebook.ipynb              # PDF (requires LaTeX)
jupyter nbconvert --to markdown notebook.ipynb         # Markdown
jupyter nbconvert --to slides notebook.ipynb           # Reveal.js slides

Tip

Use nbconvert to strip output cells before sharing:

jupyter nbconvert --to notebook --ClearOutputPreprocessor.enabled=True notebook.ipynb

## Summary

- Jupyter Notebook combines code, text, and visualisations in one document
- Markdown cells support MyST formatting, LaTeX, and rich media
- Keyboard shortcuts dramatically improve workflow speed
- Magic commands extend the notebook's capabilities
- Widgets enable interactive data exploration
- Notebooks can be exported to Python scripts, HTML, PDF, and slides

## Exercises

1. Create a notebook with three cells: a Markdown heading, a bullet list, and a code cell that prints "Hello, Pandas!"
2. Use `%timeit` to compare the speed of a list comprehension vs. a `for` loop for squaring numbers 0–999
3. Create an interactive widget with a slider that filters a list of numbers and displays the filtered result
4. Export one of your notebooks to HTML and Python script using `nbconvert`

## Further Reading

- [Jupyter Documentation](https://docs.jupyter.org/)
- [MyST — Markedly Structured Text](https://myst-parser.readthedocs.io/)
- [ipywidgets Documentation](https://ipywidgets.readthedocs.io/)
- [nbconvert Documentation](https://nbconvert.readthedocs.io/)