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 [2]:
a = 10
In [3]:
print(a)
10

Managing the IPython Kernel

Code is run in a separate process called the IPython Kernel. The Kernel can be interrupted or restarted. Try running the following cell and then hit the "Stop" button in the toolbar above.

In [4]:
import time
time.sleep(10)
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-4-d7b436e260d5> in <module>()
      1 import time
----> 2 time.sleep(10)

KeyboardInterrupt: 

If the Kernel dies you will be prompted to restart it. Here we call the low-level system libc.time routine with the wrong argument via ctypes to segfault the Python interpreter:

In [*]:
import sys
from ctypes import CDLL
# This will crash a Linux or Mac system; equivalent calls can be made on Windows
dll = 'dylib' if sys.platform == 'darwin' else 'so.6'
libc = CDLL("libc.%s" % dll) 
libc.time(-1)  # BOOM!!

All of the goodness of IPython works

Here are two system aliases:

In [1]:
pwd
Out[1]:
u'/Users/fangohr/hgdocs/teaching/python/notebook'
In [2]:
ls
IPythonNotebookIntroduction.ipynb
IPythonNotebookIntroduction.py
Matplotlib.ipynb
Matplotlib.py
Testing_12_testing_plus_pytest.ipynb
Untitled0.ipynb
animation.mp4
filename.png
filename.svg
inverse-function-through-rootfinding.ipynb
lab1.aux
lab1.html
lab1.idx
lab1.ipynb
lab1.log
lab1.out
lab1.pdf
lab1.pdf.orig
lab1.py
lab1.tex
lab1_files/
lab2.ipynb
lab2.py
lab2.tmp
lab3.ipynb
lab4.ipynb
lab5.ipynb
lab6.ipynb
lab7.ipynb
lab8.ipynb
mydata.txt
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 [3]:
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 [4]:
import numpy
numpy.random.
  File "<ipython-input-4-28daab75050a>", line 2
    numpy.random.
                 ^
SyntaxError: invalid syntax

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

In []:
numpy.random.rand(

Adding ? opens the docstring in the pager below:

In [5]:
magic?

Exceptions are formatted nicely:

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

ZeroDivisionError: integer division or modulo 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 = 1
>>> 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 [10]:
%load http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/integral_demo.py

Creating a file on the fly

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

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

and can see the file on the file system:

In [15]:
!ls -l helloworld.py
-rw-r--r--  1 fangohr  staff  20 20 Sep 13:25 helloworld.py

and execute the file using the python interpreter:

In [16]:
!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

https://github.com/ipython/ipython/tree/master/examples/notebooks#a-collection-of-notebooks-for-using-ipython-effectively