Introduction to the Jupyter Notebook¶

This document is a very brief introduction to programming Python in the Jupyter Notebook as a tool for solving numerical problems in Physical Science courses. It assumes very little knowledge of computer programming and focusses on how to use this tool to solve problems you find in physics and engineering courses.

Contents:

  • The Big Picture
  • Jupyter as a Calculator
  • Numerical Work
  • A Couple More Things
  • Get Started

Last modified: October 20 2024 by Archie Paulson (Madison College, WI)


The Big Picture¶

Python is a powerful, high-level programming language, used widely in diverse settings. It is heavily used at Google and NASA (among many others), and is one of the most popular of all programming languages. With many powerful and efficient libraries written for numerical computation, Python has become very popular in scientific computing. For example, numerical integration, linear algebra, Fourier transforms and much more are efficiently performed with the NumPy libraries, while Pandas performs data manipulation and analysis, and matplotlib offers a 2D plotting library to produce publication-quality graphs. (The online book Python for Data Analysis demonstrates all of these libraries.)

The Jupyter Notebook puts this coding environment in a "web-based application suitable for capturing the whole computation process: developing, documenting, and executing code, as well as communicating the results." The result is an environment resembling MATLAB or Mathematica. The project continues to improve under active development. All of its components are both free (as in freedom) and free (as in free beer).

Jupyter as a Calculator¶

Although Python is a powerful programming language, we introduce some of its basic features here by using the notebook as a calculator. To try it yourself, visit jupyter.org/try and click JupyterLab.

Type something to evaluate, and hit shift-enter to perform the computatation:

In [1]:
1+2+3
1 + 3 * 1000
Out[1]:
3001

All lines are executed, but only the last result is given in the Out line, unless you tell it to print. Standard order of operations are obeyed. Any text after a '#' is a comment that python ignores.

In [2]:
print (1+2+3)
print (1 + 3 * 1000)
print (1.6e-19)                    # scientific notation using 'e'
print ("the answer is", 10**2)     # this is how to raise to a power
9e9 * 1.6e-19 / 1e-3**2
6
3001
1.6e-19
the answer is 100
Out[2]:
0.00144

The last output can be re-used with the _ character.

In [3]:
_ *100
Out[3]:
0.14400000000000002

Numbers in Python are either integers or floating-point (decimal) values. The previous result shows the computer's very high but limited precision. This is a property of all computers and calculators but is often hidden from the user -- not here.

We start to use the power of coding when we use variables to store values. This is easy to do:

In [4]:
G = 6.67e-11
m1, m2, r = 5.97e24, 1.0, 6.37e6
G*m1*m2/r**2
Out[4]:
9.813440652193735
In [5]:
m2 = 15.5
F = G*m1*m2/r**2
print ('force of gravity for a mass of',m2,'kg is', F, 'Newtons')
force of gravity for a mass of 15.5 kg is 152.1083301090029 Newtons

The colored text (called syntax highlighting) helps identify the different components of your commands.

"I could do all that on my calculator," you may say. But consider some of the advantages of using the Notebook:

  • edit and refine with marginal extra effort: Did you make a simple mistake on your calculator? Then re-enter the entire problem, hoping you get it right the next time. Or, quickly edit and re-run your entry in the Notebook. Easily double check your answer before you commit to it. This ability becomes invaluable in problems with several steps.
  • save and share your results: Just save the notebook that holds your homework calculations (give it a name and control-S). Go back to it later without losing anything. If your peers need help you can show them your work and collaborate. If you get stuck and need help, show your instructor how you started the problem. You may include your own text comments in the notebook to study or review later, and remember why you did it that way. A future homework or project may have components similar to today's homework problems; you'll have a substantial head-start if you save your work now.
  • keep all significant figures: A common error in problem-solving is to round results in the middle of a long calculation -- this can lead to "round-off error", giving a final answer outside of the acceptable error tolerance. Instead let the computer do it and maintain its extremely high precision.
  • let the computer do the drudgery: That's what they are for. Spend your time and effort getting the concepts straight, not typing away at your calculator.
  • learn a powerful tool: Getting the hang of a programming language now will pay off in the future, when the problems become larger than a calculator can handle. Programming ability is a big plus in almost any field.

Numerical Work¶

The power of Python is really in the many libraries available to you. We will want the mathematical functionality of NumPy (numerical python) to do square roots and trig functions and to provide constants like $\pi$.

We must import the numpy libraries before we can use them. This can be done in more than one way; for our purposes the following is recommended:

In [6]:
from numpy import *
print ( pi, e, sqrt(2) )
print ( cos(pi), log(e), arccos(0.5)/pi )
3.141592653589793 2.718281828459045 1.4142135623730951
-1.0 1.0 0.33333333333333337

Note the trig functions use radians, and logs are natural logs.

Vectors are implemented with arrays, and their components are indexed as 0,1,2.

In [7]:
a = array( (10., 55, 60) )
print('vector a is',a)
print('it has components',a[0],a[1],'and', a[2])
vector a is [10. 55. 60.]
it has components 10.0 55.0 and 60.0

Let's add the two vectors shown below. We will find the direction and magnitude of $\vec{F} = \vec{f}_1 + \vec{f}_2$.

vectors

In [8]:
dtr = pi/180       # we will use this factor to convert degrees to radians
f1_magitude = 50.  # Newtons
theta1 = 45*dtr    # radians
f2_magitude = 25.  # Newtons
theta2 = -30*dtr   # radians

f1 = f1_magitude * array((cos(theta1),sin(theta1)))
f2 = f2_magitude * array((cos(theta2),sin(theta2)))

f1 + f2
Out[8]:
array([57.00597415, 22.85533906])

To show mathematical text like $\vec{F}$, write the LaTeX code for the mathematical objects between $ signs.

Let's find the magnitude and direction of this vector:

In [9]:
F = f1 + f2
F_mag = sqrt( F[0]**2 + F[1]**2 )
F_dir = arctan( F[1]/F[0] ) / dtr     # convert radians to degrees
print (f'magnitude is {F_mag:0.2f} N and direction is {F_dir:0.1f} degrees')
magnitude is 61.42 N and direction is 21.8 degrees

The print statement above illustrates a different way to format text, as detailed in the Python tutorial.

A Couple More Things¶

Everything you really need to get started is illustrated above. You may want to start playing around to see it in action. Consider editting this notebook (click the download link in the far upper-right corner) or starting a new one (see Get Started, below).

What follow are a few extras you might also want to consider.

Tips for Writing a Notebook¶

If you are viewing this document as a notebook, you will have noticed different types of cells appear: code (where the Python instructions are run), and text with some simple formatting (like this). You can specify the type of cell you want with the Notebook dropdown menu near the top. Text cells are called "markdown" cells -- markdown refers to a simple way to put links and formatting into your text.

The menus in the Notebook allow you to split the cell you're working in, delete a cell, copy and paste cells, et cetera. When you start working on notebooks you'll probably want to know some of the keyboard shortcuts to do these things -- see the Help menu in the Jupyter notebook for a complete list of them.

Procedural Programming¶

If there are several steps you perfrom over and over, consider writing a function to do them. For example, a function to find the magnitude of a vector could be:

In [10]:
def magnitude(vec):
    v2 = vec**2        # squares each component of array
    mag2 = sum(v2)     # adds up components of squared-array
    mag = sqrt(mag2)
    return mag
A = array((3,4,0))
B = array((cos(30*dtr),sin(30*dtr)))
print ('magnitude of A =', magnitude(A))
print ('magnitude of B =', magnitude(B))
magnitude of A = 5.0
magnitude of B = 1.0

Learn about functions, loops, "if" statements and more in the Python tutorial. You can eventually get sophisticated with the full object-oriented power of Python.

Making Graphs¶

Plotting data is accomplished with matplotlib. It must first be imported as follows:

In [11]:
import matplotlib.pyplot as plt

A simple plot is made by giving two arrays (the x and y data to be graphed) to the plot function. It is common here to use the linspace function to create the x-values we want to see. linspace requires an initial x, final x, and the number of x values to include. Here's an example showing two plots on a graph:

In [12]:
x = linspace(-3,3,1000)   # defines the plot domain
y = e**(-x**2)
plt.plot(x,y)
plt.plot(x,sin(x))
Out[12]:
[<matplotlib.lines.Line2D at 0x75df103cf0b0>]
No description has been provided for this image

You can control many aspects of the graph: colors, line widths, axes tick marks, labels, and much more. Working through a tutorial is a good way to learn these. Another good way is to browse the matplotlib gallery, find a presentation you like, copy the code and alter it to your needs.

Sharing Your Notebook¶

When you want to share a noteboook you have a few options. Before you do so make sure it's all working as you intended. You can double-check this as follows: restart the kernel (with the menu at the top of the Notebook) and Run All from the Kernel menu. Scan the final document for any errors, and save it (control-S) if it looks good.

The simplest way to share the notebook is to send your colleague the .ipynb file that you just saved. This method will only work if s/he can run the file with their own Jupyter application, in which case they would drag the file onto their Notebook dashboard, then run and edit it.

An easy way to share the notebook (read-only) is to save the .ipynb file on the web where it has a URL. Visit nbviewer.jupyter.org and paste this URL into the box there. The nbviewer will render the .ipynb file as a webpage which can then be shared broadly. The nbviewer page has an icon at the top that will allow visitors to download the .ipynb file if they like.

Another option is to make an html file from the notebook (choose "download as HTML" from the File menu). Then you can either send the html file to your audience or post it publically and direct them to its web address.

Get Started¶

You can try working with notebooks in a temporary test space at jupyter.org/try. Try to copy and paste some of the above cells as an example.

To get your own Notebook running, you might follow the instructions on this how-to page.