<span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">This lecture</span> by <a xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName" rel="cc:attributionURL">Aron Ahmadia and David Ketcheson</a> is licensed under a Creative Commons Attribution 4.0 International License. All code examples are also licensed under the MIT license.
NOTE: Some changes have been applied to make this notebook compliant with Python 3
This is a gentle introduction to the IPython Notebook aimed at lecturers who wish to incorporate it in their teaching, written in an IPython Notebook. This presentation adapts material from the IPython official documentation.
An IPython Notebook is a:
[A] Interactive environment for writing and running code
[B] Weave of code, data, prose, equations, analysis, and visualization
[C] Tool for prototyping new code and analysis
[D] Reproducible workflow for scientific research
[E] All of the above
The IPython Notebook consists of an ordered list of cells.
There are four important cell types:
We briefly introduce how Code Cells work here. We will return to the other three cell types later.
In [1]:
# This is a code cell made up of Python comments
# We can execute it by clicking on it with the mouse
# then clicking the "Run Cell" button
In [2]:
# A comment is a pretty boring piece of code
# This code cell generates "Hello, World" when executed
print("Hello, World")
In [3]:
# Code cells can also generate graphical output
%matplotlib inline
import matplotlib
matplotlib.pyplot.hist([0, 1, 2, 2, 3, 3, 3, 4, 4, 4, 10]);
Starting with IPython 2.0, the IPython Notebook has a modal user interface. This means that the keyboard does different things depending on which mode the Notebook is in. There are two modes: edit mode and command mode.
Edit mode is indicated by a green cell border and a prompt showing in the editor area:
When a cell is in edit mode, you can type into the cell, like a normal text editor.
Command mode is indicated by a grey cell border:
When you are in command mode, you are able to edit the notebook as a whole, but not type into individual cells. Most importantly, in command mode, the keyboard is mapped to a set of shortcuts that let you perform notebook and cell actions efficiently. For example, if you are in command mode and you press c
, you will copy the current cell - no modifier is needed.
All navigation and actions in the Notebook are available using the mouse through the menubar and toolbar, which are both above the main Notebook area:
The first idea of mouse based navigation is that cells can be selected by clicking on them. The currently selected cell gets a grey or green border depending on whether the notebook is in edit or command mode. If you click inside a cell's editor area, you will enter edit mode. If you click on the prompt or output area of a cell you will enter command mode.
If you are running this notebook in a live session (not on http://nbviewer.ipython.org) try selecting different cells and going between edit and command mode. Try typing into a cell.
The second idea of mouse based navigation is that cell actions usually apply to the currently selected cell. Thus if you want to run the code in a cell, you would select it and click the "Play" button in the toolbar or the "Cell:Run" menu item. Similarly, to copy a cell you would select it and click the "Copy" button in the toolbar or the "Edit:Copy" menu item. With this simple pattern, you should be able to do most everything you need with the mouse.
Markdown and heading cells have one other state that can be modified with the mouse. These cells can either be rendered or unrendered. When they are rendered, you will see a nice formatted representation of the cell's contents. When they are unrendered, you will see the raw text source of the cell. To render the selected cell with the mouse, click the "Play" button in the toolbar or the "Cell:Run" menu item. To unrender the selected cell, double click on the cell.
The modal user interface of the IPython Notebook has been optimized for efficient keyboard usage. This is made possible by having two different sets of keyboard shortcuts: one set that is active in edit mode and another in command mode.
The most important keyboard shortcuts are enter
, which enters edit mode, and esc
, which enters command mode.
In edit mode, most of the keyboard is dedicated to typing into the cell's editor. Thus, in edit mode there are relatively few shortcuts:
In command mode, the entire keyboard is available for shortcuts:
Here the rough order in which the IPython Developers recommend learning the command mode shortcuts:
enter
, shift-enter
, up/k
, down/j
s
y
, m
, 1-6
, t
a
, b
, ctrl+k
, ctrl+j
x
, c
, v
, d
, z
, shift+=
i
, 0
I personally (& humbly) suggest learning h
first!
So far, we have learned the basics of using IPython Notebooks.
For simple demonstrations, the typical user doesn't need to understand how the computations are being handled, but to successfully write and present computational notebooks, you will need to understand how the notebook architecture works.
A live notebook is composed of an interactive web page (the front end), a running IPython session (the kernel or back end), and a web server responsible for handling communication between the two (the, err..., middle-end)
A static notebook, as for example seen on NBViewer, is a static view of the notebook's content. The default format is HTML, but a notebook can also be output in PDF or other formats.
The centerpiece of an IPython Notebook is the "kernel", the IPython instance responsible for executing all code. Your IPython kernel maintains its state between executed cells.
In [4]:
x = 0
print(x)
In [5]:
x += 1
print(x)
There are two important actions for interacting with the kernel. The first is to interrupt it. This is the same as sending a Control-C from the command line. The second is to restart it. This completely terminates the kernel and starts it anew. None of the kernel state is saved across a restart.
Text can be added to IPython Notebooks using Markdown cells. Markdown is a popular markup language that is a superset of HTML. Its specification can be found here:
You can make text italic or bold or monospace
To me programming is more than an important practical art. It is also a gigantic undertaking in the foundations of knowledge. -- Rear Admiral Grace Hopper
This is a code snippet:
def f(x):
"""a docstring"""
return x**2
This is an example of a Python function
You can also use triple-backticks to denote code blocks. This also allows you to choose the appropriate syntax highlighter.
if (i=0; i<n; i++) {
printf("hello %d\n", i);
x += 4;
}
Time (s) | Audience Interest |
---|---|
0 | High |
1 | Medium |
5 |
In [6]:
from IPython.display import YouTubeVideo
YouTubeVideo('vW_DRAJ0dtc')
Out[6]:
Be Bold!
Courtesy of MathJax, you can beautifully render mathematical expressions, both inline: $e^{i\pi} + 1 = 0$, and displayed:
$$e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$$You can also use a number of equation environments, such as align
:
A full list of available TeX and LaTeX commands is maintained by Dr. Carol Burns.
$ $
, or \( \)
$$ $$
or \[ \]
\begin
and \end
\newcommand
and \def
are supported, within areas MathJax processes (such as in a \[ \]
block)By default, a notebook downloaded to a new computer is untrusted
More information on notebook security is in the IPython Notebook documentation
IPython kernels execute a superset of the Python language. The extension functions, commonly referred to as magics, come in two variants.
%matplotlib inline
, which embeds all matplotlib plot output as images in the notebook itself.
In [7]:
%matplotlib inline
In [8]:
%whos
%%timeit
to be useful for exploring code performance.
In [9]:
%%timeit
import numpy as np
np.sum(np.random.rand(1000))
In [10]:
%%python2
i = 10**60
print type(i)
IPython supports one final trick, the ability to interact directly with your shell by using the !
operator.
In [11]:
!ls
In [12]:
x = !ls
In [13]:
print(x)
The IPython Notebook is stored using canonicalized JSON for ease of use with version control systems.
There are two things to be aware of:
By default, IPython embeds all content and saves kernel execution numbers. You may want to get in the habit of clearing all cells before committing.
As of IPython 2.0, all notebooks are signed on save. This increases the chances of a commit collision during merge, forcing a manual resolution. Either signature can be safely deleted in this situation.