Let's get started...
Create a new notebook...
The notebook is built up from separate editable areas, or cells.
A new notebook contains a single code cell.
Add a line of code and execute it by:
shift-return
In [ ]:
print('hello world')
To select a cell, click on it. The selected cell will be surrounded by a box with the left hand side highlighted.
Move the selection focus to the cell above/below using the keyboard up/down arrow keys.
Additionally select adjacent cells using SHIFT-UP ARROW
or SHIFT-DOWN ARROW
.
Add a new cell to the notebook by:
Insert -> Insert Cell Above
or ESC-A
Insert -> Insert Cell Below
or ESC-B
Delete a cell by selecting it and:
Edit -> Delete cells
or ESC-X
Undelete the last deleted cell:
Edit -> Undo Delete cells
or ESC-Z
Each cell has a cell history associated with it. Use CMD-Z
to step back through previous cell contents.
Reorder cells by:
Edit -> Move Cell Up
or Edit -> Move Cell Down
Edit - >Cut
or Edit->Paste Cells Above
or Edit->Paste Cells Below
Cut selected cells
then Paste selected cells
You can also copy selected cells from the toolbar, Edit -> Copy Cells
or ESC-C
.
If a cell is overlong, you can split it at the cursor point: Edit -> Split Cell
You can merge two cells that are next two each other. Select one cell and then Edit -> Merge Cell Above
or Edit -> Merge Cell Below
.
The cell type (markdown, code, etc) of the merged cell will be the same as the originally selected cell.
In [ ]:
a=1
b=2
a+b
In [ ]:
print(a)
In [ ]:
#Run this cell multiple times
a=a+1
a
In [ ]:
import numpy as np
np.pi
As well as code cells, we can have cells that contain narrative text.
Change the cell type using the drop down list in the toolbar, or by using the ESC-M
keyboard shortcut.
To "open" or select a markdown cell for editing, double click the cell.
View the rendered markdown by running the cell:
SHIFT-RETURN
keyboard shortcut.Prefix a heading with one or more # signs, followed by a space.
Emphasise a word or phrase by wrapping it (no spaces!) with a single * on either side.
Strongly emphasise a word or phrase by wrapping it (no spaces!) with two underscores, __, either side.
Create an unnumbered list by prefixing each list item with a -, followed by a space, with each list item on a separate line:
Create a number list by prefixing each list item with a number, followed by a ., followed by a space, with each list item on a separate line:
Add sublists by indenting sublisted items with a space:
Add a link using the following pattern: [link text](URL_or_relative_path)
For example, [Data Carpentry](https://datacarpentry.org)
gives the clickable link: Data Carpentry.
Add an image using the following pattern: ![image alt text](URL_or_path)
For example, ![Jupyter logo](./jupyter-logo.png)
embeds the following image:
Mathematical expessions can be rendered inline by wrapping a LaTeX expression (no spaces) with a $ either side.
For example, $e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$
is rendered as the inline $e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$ expression.
Wrapping the expression with $$
either side forces it to be rendered on a new line in the centre of the cell: $$e^x=\sum_{i=0}^\infty \frac{1}{i!}x^i$$
In [ ]:
!ls
In [ ]:
ls -l
As well as running code in the kernel, code cells can be used in a couple of other ways.
!pwd
!cd
IPython has a notion of cell magics, commands prefixed by a % or %% that run a particular command or wrap content of the cell in some way before executing it.
%matplotlib inline
: enable the inline display of matplotlib generated graphics%whos
: display a list of variables and their values as set in the kernel%env
: display a list of environment variables and their current values in the host environment.
In [ ]:
import pandas as pd
pd.DataFrame({'col1':[1,2],'col2':['x','y']})
In [ ]:
%matplotlib inline
import matplotlib.pyplot as plt
# Create 1000 evenly-spaced values from 0 to 2 pi
x = np.linspace(0, 2*np.pi, 1000)
#Plot a sine wave over those values
y = np.sin(x)
plt.plot(x, y)
#You can prevent the display of object details returned from the plot by:
## - adding a semi-colon (;) at the end of the final statement
If you reate a function that accepts one or more parameters, you may be able to use it as the basis of an automatically generated application.
For example, suppose we have a function that will plot a sine wave over the range 0..2 pi for a specified frequency, passed into the function as a parameter:
In [ ]:
#If no frequency value is specified, use the default setting: f=1
def sinplot(f=1):
#Define a range of x values
x = np.linspace(0, 2*np.pi, 1000)
#Plot a sine wave with the specified frequency over that range
y = np.sin(f*x)
#Plot the chart
plt.plot(x, y)
plt.show()
sinplot(f=3)
In [ ]:
from ipywidgets import interact
interact(sinplot, f=5)
In [ ]:
interact(sinplot, f=(0,20));
In [ ]:
interact(sinplot, f=(0,20,5));
HTML code an also be included in a markdown cell. Adding an empty anchor tag allows you to create named anchor links that can act as deeplinks into particular parts of the notebook:
<a name='navigation'></a>
Create a complementary relative link to that section in the same notebook:
[Relative link to "Navigation" section](#navigation)
Create a link to a similarly anchor named section in different notebook:
[Deeplink into another notebook](http://example.com/example.ipynb#navigation)
To reference lines of code more exactly, toggle line numbering off and on within a cell using: ESC-L
One of the aims of using notebooks is to produce an executable document that can be rerun to reproduce the results.
To run cells from scratch (i.e. from a fresh kernel), Kernel -> Restart and Clear Output
and then run the cells you want.
To run all the cells in the notebook from scratch: Kernel -> Restart and Run All
Code cells that are running (or queued for running) display an asterisk in the cell In []
indicator.
To stop execution of a running cell (and prevent queued cells from executing):
Kernel -> Interrupt
If the notebook is still hanging, you may need to restart the kernel: Kernel -> Restart