2 min read

Python Jupyter Notebooks

Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. It is a standard tool in data science and machine learning.

Installation

pip install notebook

Starting the Notebook

To start the notebook server, run the following command in your terminal. This will open the dashboard in your default web browser.

jupyter notebook

Cell Types

Notebooks consist of a sequence of cells.

  • Code Cells: Contain code to be executed. The output is displayed immediately below the cell.
  • Markdown Cells: Contain text formatted using Markdown (like this note). Used for documentation and narrative.

Magic Commands

Magic commands are special commands that start with % (line magic) or %% (cell magic).

Common Magics

  • %timeit: Times the execution of a Python statement or expression.
  • %%time: Times the execution of the entire cell.
  • %who: Lists all variables in the global scope.
  • %matplotlib inline: Ensures matplotlib plots are displayed inline within the notebook.
  • !: Runs a shell command (e.g., !pip install pandas).
# Example of magic command
%timeit [x**2 for x in range(1000)]

Keyboard Shortcuts

There are two modes: Edit mode (press Enter to enable) and Command mode (press Esc to enable).

Command Mode (Esc)

  • A: Insert cell above.
  • B: Insert cell below.
  • M: Change cell to Markdown.
  • Y: Change cell to Code.
  • D, D (press D twice): Delete selected cell.
  • Shift + Enter: Run cell and select next.
  • Ctrl + Enter: Run cell and stay selected.

Kernel

The kernel is the computational engine that executes the code contained in a notebook document.

  • Interrupt: Stops the execution of the current cell.
  • Restart: Restarts the kernel and clears all variables.

Exporting

Notebooks (.ipynb) can be exported to various formats including HTML, PDF, and Python scripts (.py).

programming/python/python