OverviewTeaching: 0 min
Exercises: 20 minQuestions
- What does a simple notebook with some analysis look like?
- How can keyboard shortcuts speed up my work?
- Get started with notebooks for analysis.
- Practice common keyboard shortcuts.
- Get a feeling for the importance of execution order
Let’s create our first real computational narrative in a Jupyter notebook (adapted from Python and R data analysis course at Aalto Science IT).
Imagine you are on a desert island and wish to compute pi. You have a computer with you with Python installed but no math libraries and no Wikipedia.
Here is one way of doing it - “throwing darts” by generating random points within a square area and checking whether the points fall within the unit circle.
Opening a webpage inside JupyterLab
If you would like to copy-paste content from this webpage into your Jupyter notebook, a cool way of doing it is to open this page inside an IFrame:
from IPython.display import IFrame IFrame(src="https://coderefinery.github.io/jupyter/", width='100%', height='500px')
Calculating pi using Monte Carlo methods
- Create a new notebook, name it, and add a heading.
- Document the relevant formulas in a new cell:
- square area: $s = (2 r)^2$ - circle area: $c = \pi r^2$ - $c/s = (\pi r^2) / (4 r^2) = \pi / 4$ - $\pi = 4 * c/s$
- Add an image to explain the concept:
- Initialize the number of points:
num_points = 1000
- “Throw darts”:
points =  hits = 0 for _ in range(num_points): x, y = random.random(), random.random() if x*x + y*y < 1.0: hits += 1 points.append((x, y, True)) else: points.append((x, y, False))
- Plot results:
%matplotlib inline from matplotlib import pyplot x, y, colors = zip(*points) pyplot.scatter(x, y, c=colors)
- Compute final estimate of pi:
fraction = hits / num_points 4 * fraction
What do we get from this?
Working with Git from JupyterLab
- Make sure that you have installed the Git extension and nbdime for JupyterLab.
- Initialize a Git repository from the top Git menu.
- Save the computing-pi notebook and use the left-hand Git menu to stage and commit it.
- Go to GitHub and create a new repository, e.g. jupyterlab-demo.
- Open a terminal inside JupyterLab and set the remote, e.g.
git remote add origin https://github.com/user/jupyterlab-demo.gitYou can use the option “Open Git Repository in Terminal” in the top level Git menu.
- The first push needs to be done via terminal (to set the upstream branch for our local master branch):
git push -u origin master
- Future pushes (and pulls) can be done from the left-hand Git menu.
- Make another change to the notebook and save it, and click the
gitbutton in the notebook menu bar (or the Diff button in the left-side Git menu).
Notebooks provide an intuitive way to perform interactive computational work.
Allows fast feedback in your test-code-refactor loop (see test-driven development).
Cells can be executed in any order, beware of out-of-order execution bugs!
Keyboard shortcuts can save you time and protect your wrists.