Interactive Coding with Jupyter Notebooks

Authors
Dr. Atle Rimehaug | Dr. Ole Bialas | Dr. Nicholas Del Grosso | Dr. Sangeetha Nandakumar

This is a Jupyter notebook, it combines text with code and computational outputs like images.

Section 1: Using Markdown to Write Text

Markdown cells render formatted text for documentation, using Markdown syntax. Markdown in Jupyter Notebooks is a great tool for formatting text, embedding images, and organizing information. In this section you are gonna learn the basics of writing markdown. When you create a markdown cell and enter text, press Esc or Shift+Enter to exit editing mode and see the rendered text. Double click on a rendered Markdown cell (like this one) to enter editing mode.

Code Description
# Text Format Text as a level 1 heading
## Text Format Text as a level 2 heading
*text* Italicise text
**text** Make text bold
1.item one
2.item two
Two items in an ordered list
- item one
- item two
Two items in an unordered list
$E=mc^2$ Render an equation
[click here](google.com) Create a hyperlink to google.com
```python
print("Hello!")
```
Render a Python code block
| Col 1 | Col2 |
| --- | --- |
| Row 1 | Row 1 |
| Row 2 | Row 2 |
Create a tabple with two column and two rows

Exercise: Create a level 2 heading.

Solution

Section 2: Level 2 Heading

Exercise : Create a level 6 heading.

Solution
Level 6 Heading

Exercise: Write something in bold.

Solution
This is Bold

Exercise: Write italicised text.

Solution
This is italic

Exercise: Make an unordered list of the programming laguages Python, R and Julia.

Solution
  • Python
  • R
  • Julia

Exercise: Make an ordered list of the days Mon, Tue and Wed.

Solution
  1. Mon
  2. Tue
  3. Wed

Exercise: Add a hyperlink to the Python documentation website, https://docs.python.org .

Solution

Exercise: Render the euqation a^2+b^2=c^2

Solution
a2+b2=c2a^2+b^2=c^2

Exercise: Render the text range(10) as a Python code block.

Solution
range(10)

Exercise: Make a Table with the columns Day and Lunch to list what you had for lunch the last 3 days.

Solution
Day Food
Sunday Chicken
Monday Soup
Tuesday Falaffel

Section 3: Creating and Executing Code Cells

In this section, we will focus on running code in Jupyter Notebooks using the Pixi kernel, exploring some of the available buttons and options for managing code cells, and installing packages directly from the notebook using Pixi commands. Before we can start, you must select a Kernel that Jupyter can use to run the code in this notebook. To do this, click on the Select Kernel button in the top right corner of VSCode

and select a Python environment - you can choose any of the environments you created in the previous sections! Alternatively, you can create one from scratch

with pixi:

pixi init
pixi add python pip

or with conda:

conda create -n my_env python pip

If you create a new environment, you may have to restart VSCode so it detects the new environment

Exercise: Execute the cell below by clicking on the arrow to left or by pressing Shift+Enter

import this

Exercise: Type 1+1 in the cell below and execute it.

Solution
1+1
2

Exercise: Create a new Python Code cell below, type 12*56 and execute the cell.

Exercise: Clear the outputs of the cell above by clicking on the three dots to the left of the output and selecting “Clear Cell Outputs” or by pressing Alt+Del.

Exercise: Clear the output of all cells by clicking the “Clear All Outputs” button. The code will remain unaffecxted by this.

Exercise: Execute the cell below to create the variable a and assign it the value 0. Then execute the next cell to add 1 to a and print it’s value. Run the cell multiple times and observe how the value changes.

a = 0
a+=1
a
4

Exercise: The three code cells below are in the wrong order - you’ll get an error when executing them from top to bottom. Find the order in which the cells have to be executed and then sort them.

k = j / 2
k + j
k = 4

Exercise: Restart the Jupyter kernel by using the “Restart” button in the top menu.

Note that this resets the state of the notebook which means that all of the variables you created before are wiped from memory (the code is still there though).

Exercise: Use the “Run all Cells” button to execute all cells in this notebook. Note that this will only work without error if you have correctly sorted the code cells in the exercise above.

Section 4: Terminal from Notebooks

We can even run terminal commands from notebooks by writing them in a code cell and prefacing them with !. This makes it possible to use tools like Conda and Pixi or execute Python scripts stored somewhere else. Let’s try it out!

Code Description
!ping -c 4 google.com Ping the website google.com four times
!whoami Print the current user
!pwd Print the present working directory
!python script.py Execute the Python program script.py
!pixi add pandas Install the pandas package into the current pixi environment
!conds install --name my_env pandas -y Install the pandas package into the conda environemnt my_env and say “yes” when asked to confirm the installation

Note that, while the examples chosen here are platform-independent, most terminal commands differ between Windows and Linux/MacOS.

Example: Ping the website wikipedia.com 3 times.

!ping -c 3 wikipedia.com
PING wikipedia.com (185.15.59.226) 56(84) bytes of data.
64 bytes from ncredir-lb.esams.wikimedia.org (185.15.59.226): icmp_seq=1 ttl=56 time=20.6 ms
64 bytes from ncredir-lb.esams.wikimedia.org (185.15.59.226): icmp_seq=2 ttl=56 time=21.5 ms
64 bytes from ncredir-lb.esams.wikimedia.org (185.15.59.226): icmp_seq=3 ttl=56 time=22.1 ms

--- wikipedia.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 1999ms
rtt min/avg/max/mdev = 20.551/21.390/22.135/0.650 ms

Exercise: Print the current user.

Solution
!whoami
olebi

Exercise: Print the present working directory

Solution
!pwd
/home/olebi/projects/new-learning-platform/new-learning-platform/notebooks/essential_tools/02_jupyter/01_jupyter_notebooks

Exercise: Copy the code in the cell below and save it to a new file called countdown.py. The file must be in the SAME FOLDER as this notebook. You may delete the cell after you are done copying. Then, execute the cell below to run that script.

# copy this to countdown.py
print("Starting Countdown ...")
for i in range(1, 4):
    print(i)
print("Takeoff!")
!python countdown.py
Starting Countdown ...
1
2
3
Takeoff!

Example Install numpy, into your current environment using pixi or conda (whichever one you are currently using).

# if you are using pixi
!pixi add numpy
# if you are using conda (assuming your environment is called "my_env")
!conda install --name my_env numpy -y

Exercise: Install matplotlib and ipywidgets into your current environment. You can either install them separately or in the same command by simply listing both packages, separated by a comma.

Solution
# if you are using pixi
!pixi add matplotlib ipywidgets
Solution
# if you are using conda (assuming your environment is called "my_env")
!conda install --name my_env matplotlib ipywidgets -y

Section 5: Demo: Interactive Widgets

We can also add interactive elements to a notebook, for example using the ipywidgets package. Run the cell below to create a widget that plots a sinewave with variable frequency and amplitude. Note that this only works if you installed the packages numpy, matplotlib and ipywidgets in the previous exercises.

import ipywidgets as widgets
import numpy as np
import matplotlib.pyplot as plt

# Create interactive plot with slider
def plot_sine(frequency=1.0, amplitude=1.0):
    x = np.linspace(0, 4*np.pi, 200)
    y = amplitude * np.sin(frequency * x)
    
    plt.figure(figsize=(10, 4))
    plt.plot(x, y)
    plt.ylim(-5, 5)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.title(f'y = {amplitude:.1f} * sin({frequency:.1f} * x)')
    plt.grid(True)
    plt.show()

# Create interactive sliders
widgets.interactive(plot_sine, 
                   frequency=(0.5, 5.0, 0.1), 
                   amplitude=(0.5, 5.0, 0.1))
interactive(children=(FloatSlider(value=1.0, description='frequency', max=5.0, min=0.5), FloatSlider(value=1.0…

Section 6: Demo: Running a Notebook as a Script

It is also possible to run a Jupyter notebook without opening it, just like we ran the script countdown.py in the previous section. This is useful if your analysis pipeline is spread out across multiple notebooks and you want to run everything in one go.

Replace the name notebook.ipynb in the cell below with the name of this notebook to execute every cell in it.

!jupyter nbconvert --to notebook --execute notebook.ipynb