Important

You can run this notebook in a live session Binder or view it on nbviewer or GitHub.

Hello Python and Jupyter

In this notebook you will:

  • Learn how to use a Jupyter notebook such as this one

  • Get a very quick tour of Python syntax and scientific libraries

  • Learn some IPython features that we will use in later tutorials

What is this?

This is Jupyter notebook running in a personal “container” just for you, stocked with example data, demos, and tutorials that you can run and modify. All of the software you’ll need is already installed and ready to use.

Run some Python code!

To run the code below:

  1. Click on the cell to select it.

  2. Press SHIFT+ENTER on your keyboard or press the Run button in the toolbar above (in the toolbar above!).

[1]:
1 + 1
[1]:
2

Notice that you can edit a cell and re-run it.

The notebook document mixes executable code and narrative content. It supports text, links, embedded videos, and even typeset math: \(\int_{-\infty}^\infty x\, d x = \frac{x^2}{2}\)

Whirlwind Tour of Python Syntax

Lists

[2]:
stuff = [4, 'a', 8.3, True]
[3]:
stuff[0]  # the first element
[3]:
4
[4]:
stuff[-1]  # the last element
[4]:
True

Dictionaries (Mappings)

[5]:
d = {'a': 1, 'b': 2}
[6]:
d
[6]:
{'a': 1, 'b': 2}
[7]:
d['b']
[7]:
2
[8]:
d['c'] = 3
[9]:
d
[9]:
{'a': 1, 'b': 2, 'c': 3}

Functions

[10]:
def f(a, b):
    return a + b

In IPython f? or ?f display information about f, such as its arguments.

[11]:
f?

If the function includes inline documentation (a “doc string”) then ? displays that as well.

[12]:
def f(a, b):
    "Add a and b."
    return a + b
[13]:
f?

Arguments can have default values.

[14]:
def f(a, b, c=1):
    return (a + b) * c
[15]:
f(1, 2)
[15]:
3
[16]:
f(1, 2, 3)
[16]:
9

Any argument can be passed by keyword. This is slower to type but clearer to read later.

[17]:
f(a=1, b=2, c=3)
[17]:
9

If using keywords, you don’t have to remember the argument order.

[18]:
f(c=3, a=1, b=2)
[18]:
9

Fast numerical computation using numpy

For numerical computing, a numpy array is more useful and performant than a plain list.

[19]:
import numpy as np

a = np.array([1, 2, 3, 4])
[20]:
a
[20]:
array([1, 2, 3, 4])
[21]:
np.mean(a)
[21]:
2.5
[22]:
np.sin(a)
[22]:
array([ 0.84147098,  0.90929743,  0.14112001, -0.7568025 ])

We’ll use the IPython %%timeit magic to measure the speed difference between built-in Python lists and numpy arrays.

[23]:
%%timeit

big = list(range(10000))  # setup line, not timed
sum(big)  # timed
224 µs ± 1.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
[24]:
%%timeit

big = np.arange(10000)  # setup line, not timed
np.sum(big)  # timed
18.3 µs ± 16.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Plotting using matplotlib

In an interactive setting, this will show a canvas that we can pan and zoom. (Keep reading for what we can do in a non-interactive setting, such as the static web page version of this tutorial.)

[25]:
# We just have to do this line once, before we do any plotting.
%matplotlib widget
import matplotlib.pyplot as plt

plt.figure()
[25]:
<Figure size 640x480 with 0 Axes>

We can plot some data like so. In an interactive setting, this will update the canvas above.

[26]:
plt.plot([1, 1, 2, 3, 5, 8])
[26]:
[<matplotlib.lines.Line2D at 0x7f9aab12a828>]

And we can show a noninteractive snapshot of the state of the figure at this point by display the figure itself.

[27]:
plt.gcf()
[27]:
_images/Hello_Python_and_Jupyter_44_0.png

Displaying plt.gcf() (or any Figure) shows a non-interactive snapshot of a figure. Displaying plt.gcf().canvas or any Canvas gives us another interactive, live-updating view of the figure.

Interrupting the IPython Kernel

Run this cell, and then click the square ‘stop’ button in the notebook toolbar to interrupt the infinite loop.

(This is equivalent to Ctrl+C in a terminal.)

[28]:
# This runs forever -- hit the square 'stop' button in Jupyter to interrupt
# The following is "commented out". Un-comment the lines below to run them.
# while True:
#     continue

“Magics”

The code entered here is interpreted by IPython, which extends Python by adding some conveniences that help you make the most out of using Python interactively. It was originally created by a physicist, Fernando Perez.

“Magics” are special IPython syntax. They are not part of the Python language, and they should not be used in scripts or libraries; they are meant for interactive use.

The %run magic executes a Python script.

[29]:
%run scripts/hello_world.py
hello world

When the script completes, any variables defined in that script will be dumepd into our namespace. For example (as we will see below), this script happens to define a variable named message. Now that we have %run the script, message is in our namespace.

[30]:
message
[30]:
'hello world'

This behavior can be confusing, in the sense that the reader has to do some digging to figure out where message was defined and what it is, but it has its uses. Throughout this tutorial, we will use the %run magic as a shorthand for running boilerplate configuration code and defining variables representing hardware.

The %load magic copies the contents of a file into a cell but does not run it.

[31]:
%load scripts/hello_world.py

Execute the cell a second time to actually run the code. Throughout this tutorial, we use the %load magic to load solutions to exercises.

System Shell Access

Any input line beginning with a ! character is passed verbatim (minus the !, of course) to the underlying operating system.

[32]:
!ls
Access Saved Data.ipynb
Anatomy of a Device.ipynb
conf.py
Epics Signal.ipynb
Export data to files with Suitcase.ipynb
Flyer Basics.ipynb
Hello Bluesky.ipynb
Hello Python and Jupyter.ipynb
Higher Dimensional Data.ipynb
index.rst
Let Us Do the Bookkeeping For You.ipynb
Live Nonlinear Fitting.ipynb
matplotlibrc
Multi-dimensional Coordinates.ipynb
my_exported_files
Powder Diffraction
Process Tabular Data with Pandas.ipynb
rsoxs_simulation_data
scripts
Slice and Interpolate Image Data.ipynb
solutions
static
_static
supervisor
Supplemental Data.ipynb
X-ray Absorption Fine Structure