Practial 0: Taking control of a jupyter notebook#

This notebook is designed to introduce you to the basics of Jupyter Notebooks. You should proceed through it line by line and step by step, experimenting with each code cell as you go. Follow the instructions to understand how to create, edit, and run cells, and learn how to use Markdown for formatting. By actively engaging with the examples and modifying the code, you will gain a solid foundation in using Jupyter Notebooks for interactive computing and documentation.

Introduction to Jupyter Notebooks#

A Jupyter Notebook is an open-source web application that allows users to create and share documents containing live code, equations, visualizations, and narrative text. It is an interactive tool widely used in data science, research, education, and software development, offering a versatile environment where users can experiment, explore, and present their work.

Key Features#

  1. Live Code Execution:

    • Jupyter Notebooks support live code in multiple programming languages, including Python, R, Julia, and more. Users can run code cells interactively, making it easy to test and iterate on their work.

  2. Rich Text and Markdown Support:

    • Users can write and format text using Markdown, allowing for the inclusion of headings, lists, links, and more. This feature is useful for adding explanations, instructions, and comments directly within the notebook.

  3. Data Visualization:

    • Jupyter Notebooks support various plotting libraries like Matplotlib, Seaborn, and Plotly. Users can create and display graphs, charts, and other visualizations to analyze and interpret data.

  4. Interactive Widgets:

    • Jupyter Notebooks can include interactive widgets that allow users to manipulate parameters and see real-time updates in visualizations and outputs. This interactivity enhances the exploratory data analysis experience.

  5. Documentation and Collaboration:

    • Notebooks can be easily shared and published, making them ideal for collaborative projects. They are commonly used for sharing research findings, creating tutorials, and documenting workflows.

  6. Extensibility:

    • Jupyter Notebooks support extensions and can be integrated with various tools and services, such as GitHub for version control, Binder for live sharing, and JupyterHub for multi-user environments.

Practical Session Introduction#

In this practical session, we will explore the basics of Jupyter Notebooks. We’ll start by setting up a notebook environment and familiarizing ourselves with the interface. We will cover how to write and execute code and document our work using Markdown. By the end of this session, you will have a solid understanding of how to use Jupyter Notebooks to develop, document, and share your projects effectively.

Let’s dive in and experience the power and flexibility of Jupyter Notebooks in action!

Keyboard Shortcuts Practice#

Taking a few minutes to learn certain Jupyter Notebook keyboard shortcuts has helped me be a more efficient Python developer. Below are the keyboard shortcuts I’ve found most useful.

Note: these keyboard shortcuts are for Jupyter version 4.1.0 and Mac OSX. For Mac OSX users, you can replace Ctrl by cmd for and option for Alt for Windows or Linux. Or, you can use the H keyboard shortcut in Windows or Linux to confirm the appropriate keyboard shortcuts for those operating systems.

Command vs. Edit Modes#

But first…something key to be aware of: Jupyter Notebooks have two different keyboard input modes:

  1. Command mode - binds the keyboard to notebook level actions. Indicated by a grey cell border with a blue left margin.

  2. Edit mode - when you’re typing in a cell. Indicated by a green cell border with a green left margin.

Experiment with switching between command and edit modes in this cell. Hint: If you’re in command mode, press Enter to enter edit mode. If you’re in edit mode, press Esc to enter command mode.

Command Mode#

Let’s practice the command mode first.

To start, select the next cell and press Shift + Enter to run that cell and select the next cell

print("You just ran the cell and selected the next cell")
You just ran the cell and selected the next cell

With the next cell selected, press Ctrl + Enter to run the cell and keep the same cell selected

print("You just ran the cell and the focus stayed in that cell")
You just ran the cell and the focus stayed in that cell

With the next cell selected, press Alt + Enter to run the cell and insert a new cell below

print("You just ran the cell and inserted a new cell below it")
You just ran the cell and inserted a new cell below it

Ctrl + S save and checkpoint.


Press A to insert a new cell above this one.


Then, press B to insert a new cell below.


Copy the next cell with C and then paste it with V

print("copy me")
copy me

Delete the cell below by selecting it and press D D (i.e., hit the D button twice)

print("delete me")
delete me

Merge the following two cells by selecting the first one and then press Shift + M

First select the cells to merge by pressing Shift + or

print("click me and then merge me with the next cell")
click me and then merge me with the next cell
print("merge me with the cell above")
merge me with the cell above

Undo the previous option using span Esc + Z


Experiment with changing the following cells to code and markdown modes

Y change the cell type to Code

M change the cell type to Markdown

```
print("I should be in Markdown mode. Type `M` to change me to markdown. Then type `shift` + `enter` to see the proper markup")
```
  Cell In [8], line 1
    ```
    ^
SyntaxError: invalid syntax

print(“I should be code. Select me and then type Y to change me to code mode”)


Select the entire text in the next cell and press Ctrl + / to toggle comment lines

print("this")
print("is")
print("a big")
print("block of")
print("text to comment")

Run the next cell to import numpy and then put your cursor next to the np. in the following cell. Then, press Tab to see what code completions are available

import numpy as np
np.

Use Ctrl + Shift + - split the following cell between the two functions

def func1():
    print("I'm func1. Separate me from func2")
def func2():
    print("I'm ")    

Insert Image#

from IPython.display import Image
Image("images\logo-python.png") 

Markdown#

For each sub-section: The first cell is code representation and next cell is the output representation in Markdown.

Headers#

# Heading 1    
## Heading 2    
### Heading 3
#### Heading 4
##### Heading 5
###### Heading 6

Alternatively, for H1 and H2, an underline-ish style:

Alt-H1
======

Alt-H2
------

Heading 1#

Heading 2#

Heading 3#

Heading 4#

Heading 5#
Heading 6#

Alternatively, for H1 and H2, an underline-ish style:

Alt-H1#

Alt-H2#

Emphasis#

Emphasis, aka italics, with *asterisks* or _underscores_.

Strong emphasis, aka bold, with **asterisks** or __underscores__.

Combined emphasis with **asterisks and _underscores_**.

Strikethrough uses two tildes. ~~Scratch this.~~

Emphasis, aka italics, with asterisks or underscores.

Strong emphasis, aka bold, with asterisks or underscores.

Combined emphasis with asterisks and underscores.

Strikethrough uses two tildes. ~~Scratch this.~~

Colors#

Use this code: Text Not all markdown code works within a font tag, so review your colored text carefully!

Front color is blue

Front color is red

Front color is yellow

Lists#

  1. First ordered list item

  2. Another item

  • Unordered sub-list.

  1. Actual numbers don’t matter, just that it’s a number

  2. Ordered sub-list

  3. And another item.

    Some text that should be aligned with the above item.

  • Unordered list can use asterisks

  • Or minuses

  • Or pluses

  1. Today’s

  2. date is:

    • Monday

    • 16th January 1991

      • hello! how are

      • how are you?

        • Hope doing well

  • Item A

  • Item B

  • Item C

Blockquotes#

Blockquotes are very handy in email to emulate reply text. This line is part of the same quote. This line is also part of the same quote.

This line too.

Quote break.

This is a very long line that will still be quoted properly when it wraps. Oh boy let’s keep writing to make sure this is long enough to actually wrap for everyone. Oh, you can put Markdown into a blockquote.

Inline HTML#

You can also use raw HTML in your Markdown, and it’ll mostly work pretty well.

Definition list
Is something people use sometimes.
Markdown in HTML
Does *not* work **very** well. Use HTML tags.

Horizontal Rule#

Three or more…


Hyphens


Asterisks


Underscores

Line Breaks#

My basic recommendation for learning how line breaks work is to experiment and discover – hit once (i.e., insert one newline), then hit it twice (i.e., insert two newlines), see what happens. You’ll soon learn to get what you want. “Markdown Toggle” is your friend.

Here are some things to try out:

Here’s a line for us to start with.

This line is separated from the one above by two newlines, so it will be a separate paragraph.

This line is also a separate paragraph, but… This line is only separated by a single newline, so it’s a separate line in the same paragraph.

Code and Syntax Highlighting#

Code blocks are part of the Markdown spec, but syntax highlighting isn’t. However, many renderers – like Github’s and Markdown Here – support syntax highlighting. Markdown Here supports highlighting for dozens of languages (and not-really-languages, like diffs and HTTP headers).

Inline code has back-ticks around it.

Blocks of code are either fenced by lines with three back-ticks ```, or are indented with four spaces. I recommend only using the fenced code blocks – they’re easier and only they support syntax highlighting.

var s = "JavaScript syntax highlighting";
alert(s);
s = "Python syntax highlighting"
print s
No language indicated, so no syntax highlighting. 
But let's throw in a <b>tag</b>.

Tables#

Tables aren’t part of the core Markdown spec, but they are part of GFM and Markdown Here supports them. They are an easy way of adding tables to your email – a task that would otherwise require copy-pasting from another application.

Colons can be used to align columns.

Tables

Are

Cool

col 3 is

right-aligned

$1900

col 2 is

centered

$12

col 1 is

left-aligned

$1

The outer pipes | are optional, and you don’t need to make the raw Markdown line up prettily. You can also use inline Markdown.

Markdown

Less

Pretty

Still

renders

nicely

1

2

3

Table - rowspan#

column 1 column 2 column 3
row 1 - column 1 row 1 - column 2 row 1 & 2 - column 3
row 2 - column 1 row 2 - column 2

Table - colspan#

column 1 column 2 column 3
row 1 - column 1 row 1 - column 2 & 3
row 2 - column 1 row 2 - column 2 row 2 - column 3

Images#

Images - Representation#

Title Image: description

myImage Image: description

Hi-Five

space-1.jpg

Space

Random Unsplash Image

Image Align - Middle (default)#

Image align to Center. .

Image Align - Left#

Image align to leftleft face.

Image Align - Right#

right Image align to right.

YouTube Videos#

They can’t be added directly but you can add an image with a link to the video like this:

IMAGE ALT TEXT HERE

Or, in pure Markdown, but losing the image sizing and border:

Example:

IMAGE ALT TEXT HERE

TeX Mathematical Formulae in Jupyter Notebooks#

A full description of TeX math symbols is beyond the scope of this cheatsheet. Here’s a good reference, and you can try stuff out on CodeCogs. You can also play with formula in the Markdown Here options page. Jupyter Notebooks support rendering LaTeX mathematical expressions using MathJax. You can include mathematical formulae in both inline and block formats.

Here are some examples to try out:

Inline Examples#

Inline formulae can be included within a line of text using single dollar signs $ ... $.

1. Basic Arithmetic and Symbols#

The area of a circle is given by \(A = \pi r^2\).

2. Fractions#

The formula for the average is \(\bar{x} = \frac{\sum_{i=1}^{n} x_i}{n}.\)

3. Exponents and Subscripts#

The equation of motion is \(s = ut + \frac{1}{2}at^2\).

4. Roots#

The square root of \(a\) is written as \(\sqrt{a}\), and the cubic root is \(\sqrt[3]{a}\).

5. Trigonometric Functions#

The identity \(\sin^2 \theta + \cos^2 \theta = 1\) holds for all angles \(\theta\).

Block Examples#

Block formulae are displayed separately from the text using double dollar signs $$ ... $$.

1. Quadratic Formula#

\[ ax^2 + bx + c = 0 \]

The solutions are given by: $\( x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \)$

2. Sum and Product Notation#

Sum of the first \(n\) natural numbers: $\( \sum_{i=1}^{n} i = \frac{n(n + 1)}{2} \)\( Product of the first \)n\( natural numbers: \)\( n! = \prod_{i=1}^{n} i \)$

3. Integral and Derivative#

The definite integral of a function \(f(x)\) from \(a\) to \(b\) is: $\( \int_{a}^{b} f(x) \, dx \)\( The derivative of \)f(x)\( with respect to \)x\( is: \)\( \frac{d}{dx}f(x) \)$

4. Matrix Representation#

A \(2 \times 2\) matrix: $\( \begin{pmatrix} a & b \\ c & d \end{pmatrix} \)$

5. Vectors and Dot Product#

A vector in three-dimensional space: $\( \vec{v} = \begin{pmatrix} v_1 \\ v_2 \\ v_3 \end{pmatrix} \)\( The dot product of \)\vec{a}\( and \)\vec{b}\(: \)\( \vec{a} \cdot \vec{b} = a_1b_1 + a_2b_2 + a_3b_3 \)$

6. Probability and Statistics#

The probability of an event \(E\) is given by: $\( P(E) = \frac{\text{Number of favorable outcomes}}{\text{Total number of outcomes}} \)$

The expected value \(E(X)\) of a random variable \(X\) is: $\( E(X) = \sum_{i} x_i P(x_i) \)$

\[ E(X) = \sum_{i} x_i P(x_i) \]

7. Differential Equations#

The general solution of a first-order linear differential equation: $\( \frac{dy}{dx} + P(x)y = Q(x) \)\( is given by: \)\( y = e^{-\int P(x) \, dx} \left( \int Q(x) e^{\int P(x) \, dx} \, dx + C \right) \)$

8. Limits#

The limit of \(f(x)\) as \(x\) approaches \(a\) is: $\( \lim_{x \to a} f(x) \)$

<img src="https://latex.codecogs.com/svg.latex?\Large&space;x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}" title="\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}" />
  Cell In [4], line 1
    <img src="https://latex.codecogs.com/svg.latex?\Large&space;x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}" title="\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}" />
    ^
SyntaxError: invalid syntax
![\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}](https://latex.codecogs.com/svg.latex?\Large&space;x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}) 
/bin/bash: -c: line 1: syntax error near unexpected token `('
/bin/bash: -c: line 1: `[\Large x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}](https://latex.codecogs.com/svg.latex?\Large&space;x=\frac{-b\pm\sqrt{b^2-4ac}}{2a})'

arge x=rac{-bmqrt{b^2-4ac}}{2a}

![\Large x=a_0+\frac{1}{a_1+\frac{1}{a_2+\frac{1}{a_3+a_4}}}](https://latex.codecogs.com/svg.latex?\Large&space;x=a_0+\frac{1}{a_1+\frac{1}{a_2+\frac{1}{a_3+a_4}}})
/bin/bash: -c: line 1: syntax error near unexpected token `('
/bin/bash: -c: line 1: `[\Large x=a_0+\frac{1}{a_1+\frac{1}{a_2+\frac{1}{a_3+a_4}}}](https://latex.codecogs.com/svg.latex?\Large&space;x=a_0+\frac{1}{a_1+\frac{1}{a_2+\frac{1}{a_3+a_4}}})'

arge x=a_0+rac{1}{a_1+rac{1}{a_2+rac{1}{a_3+a_4}}}

![\Large \forall x \in X, \quad \exists y \leq \epsilon](https://latex.codecogs.com/svg.latex?\Large&space;\forall{x}\in{X},\quad\exists{y}\leq\epsilon)
/bin/bash: -c: line 1: syntax error near unexpected token `('
/bin/bash: -c: line 1: `[\Large \forall x \in X, \quad \exists y \leq \epsilon](https://latex.codecogs.com/svg.latex?\Large&space;\forall{x}\in{X},\quad\exists{y}\leq\epsilon)'

arge orall x n X, uad xists y eq psilon

Here is a simple script to convert the equation into html: https://jsfiddle.net/8ndx694g/. You can explore it.