Introduction to IPython in the Jupyter Notebook

This document is a very brief introduction to using IPython 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 textbook problems.


Last modified November, 2018 by Archie Paulson (Madison College, WI)

The Big Picture

Python is a powerful, high-level programming language, used very 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 quite popular in scientific computing. For example, numerical integration, linear algebra, Fourier tranforms 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.

IPython harnesses all this power in a convenient interactive terminal interface, and the Jupyter Notebook wraps it all 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).

IPython 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 and choose "Python 3" from the "New" dropdown menu (see Get Started, below).

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

In [1]:
1 + 3 * 1000

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 does not get executed.

In [3]:
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
the answer is 100

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

In [4]:
_ *100

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

We start to use the power of programming 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
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

Notice how the Notebook shows the input text in colors (called syntax highlighting) to 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. Include your own text comments in the notebook to study or review later; 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 may pay off big in the future, when the problems become larger than a calculator can handle. Programming ability is a big plus on a resume.

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 [5]:
from numpy import *
print ( pi, e, sqrt(2) )
print ( cos(pi), log(e), arccos(0.5)/pi )
3.141592653589793 2.718281828459045 1.41421356237
-1.0 1.0 0.333333333333

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

Vectors in this context are called arrays, and their components are indexed as 0,1,2.

In [6]:
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$.

In [9]:
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
array([ 57.00597415,  22.85533906])

Note: to show an image like you see above you can write html code (as above). 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 [11]:
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 ('magnitude is {:0.2f} N and direction is {:0.1f} degrees'.format(F_mag,F_dir))
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 (available here) 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 [14]:
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 activated and imported as follows:

In [11]:
%matplotlib inline
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 make 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)
[<matplotlib.lines.Line2D at 0x802e6d8>]

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 Cell 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 she can run the file with her own Notebook server, in which case she would drag the file onto her 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 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. For this method to work you need to have access to a webserver to host the .ipynb file -- you might be interested in getting an account with a free web hosting service (I have used 000webhost for small projects).

Another option is to make an html file from the notebook. Then you can either send the html file to your audience or post it publically and direct them to its web address. You can obtain the html version in the File menu, choosing to "download as" html.

Get Started

You can try working with notebooks in a temporary test space at Find the "New" dropdown menu at the right and select "Python 3" for a blank notebook. Try to copy and paste some of the above cells as an example. Note that this site is best for just trying jupyter; all work is deleted after 10 minutes of inactivity.

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