### Overview

Teaching: 0 min
Exercises: 20 min
Questions
• What does a simple notebook with some analysis look like?
• How can keyboard shortcuts speed up my work?
Objectives
• Get started with notebooks for analysis.
• Practice common keyboard shortcuts.
• Get a feeling for the importance of execution order

# Creating a computational narrative

Let’s create our first real computational narrative in a Jupyter notebook.

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.

## Calculating $\pi$ using Monte Carlo methods

2. Document the relevant formulas in a new cell:
 - square area = $(2 r)^2$
- circle area = $\pi r^2$
- circle / square = $\pi r^2 / 4 r^2$ = $\pi / 4$
- $\pi = (circle/square) * 4$

3. Add an image to explain the concept:
![Darts](https://coderefinery.github.io/jupyter/img/darts.svg)

4. Import random module:
import random

5. Initialize variables:
N = 1000
points = []

6. “Throw darts”:
hits = 0
for i in range(N):
x, y = random.random(), random.random()
if x**2 + y**2 < 1:
hits += 1
points.append((x,y, True))
else:
points.append((x,y, False))

7. Plot results:
%matplotlib inline
from matplotlib import pyplot
x, y, colors = zip(*points)
pyplot.scatter(x, y, c=colors)

8. Compute final estimate of $\pi$:
fraction = hits / N
4 * fraction


What do we get from this?

• With code separate from everything else, you might just send one number or a plot to your supervisor for checking.
• With a notebook as a narratives, you send everything in a consistent story.
• A reader may still just read the introduction and conclusion, but they can easily see more - and try changes themselves - if they want.

### Key points

• 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.