Running Code in the IPython Notebook

Based on this notebook with very minor changes.


First and foremost, the IPython Notebook is an interactive environment for writing and running Python code.

Code cells allow you to enter and run Python code

Run a code cell using Shift-Enter or pressing the "Play" button in the toolbar above:

In [16]:
a = 10
In [17]:
print(a)
10

All of the goodness of IPython works

Here are two system aliases:

In [18]:
pwd
Out[18]:
'/Users/fangohr/hg/teaching-python/notebook'
In [19]:
ls
IPython-beyond-plain-Python-Fernando-Perez.ipynb
IPythonNotebookIntroduction.html
IPythonNotebookIntroduction.ipynb
Makefile
Matplotlib.ipynb
Testing-intro.ipynb
helloworld.py
inverse-function-through-rootfinding.ipynb
lab1.ipynb
lab1.pdf
lab2.ipynb
lab3.ipynb
lab4.ipynb
lab5.ipynb
lab6.ipynb
lab7.ipynb
lab8.ipynb
same-or-differents-object.ipynb
speed-map-vs-for-loop.ipynb
update-web.sh

Any command line program can be run using ! with string interpolation from Python variables:

In [20]:
message = 'The IPython notebook is great!'
# note: the echo command does not run on Windows, it's a unix command.
!echo $message
The IPython notebook is great!

Tab completion works:

In [21]:
import numpy
In [ ]:
numpy.

Shift-Tab completion after ( brings up a tooltip with the docstring:

In [ ]:
numpy.random.rand(

Adding ? opens the docstring in the pager below:

In [23]:
magic?

Exceptions are formatted nicely:

In [5]:
x = 1
y = 4
z = y/(1-x)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-5-dc39888fd1d2> in <module>()
      1 x = 1
      2 y = 4
----> 3 z = y/(1-x)

ZeroDivisionError: division by zero

Working with external code

There are a number of ways of getting external code into code cells.

Pasting code with >>> prompts works as expected:

In [7]:
>>> the_world_is_flat = True
>>> if the_world_is_flat:
...     print("Be careful not to fall off!")
Be careful not to fall off!

The %load magic lets you load code from URLs or local files:

In [8]:
%load?
In [9]:
%matplotlib inline
In [ ]:
%load http://matplotlib.org/mpl_examples/statistics/histogram_demo_features.py

Creating a file on the fly

Using the %%file magic, we can directly create a file

In [13]:
%%file helloworld.py
print("Hello World")
Writing helloworld.py

and can see the file on the file system:

In [14]:
!ls -l helloworld.py
-rw-r--r--  1 fangohr  staff  20 16 Sep 14:43 helloworld.py

and execute the file using the python interpreter:

In [15]:
!python helloworld.py
Hello World

Type markdown for text and latex

For example, if $x=\alpha$ then $x^2 = \alpha^2$. Furthermore $$ \int\limits_a^b f(x) \mathrm{d} x = \Gamma.$$

Further reading

In [ ]: