$.$.Homepage: ipython.org
Repository: github.com/ipython/ipython
Mailing list: ipython-dev@scipy.org
ipython-notebook / ipython3-notebook
ipython 1.2.1: Debian wheezy-backports, Ubuntu 14.04LTS
ipython 2.3.0: Debian jessie, Ubuntu 15.04
ipython 3.1.0: pypi.python.org
pip install "ipython[notebook]"
see also: ipython.org/install.html
SHIFT-ENTER, CTRL-ENTER: execute the selected cellALT-ENTER: execute the selected cell and open a new oneA: insert a new cell above the present cellB: insert a new cell below the present cellD,D: delete the selected cellM: define selected cell as markdown cellH: display all keyboard shortcuts
In [ ]:
for n in range(3):
print("The IPython notebook is great.")
Code cells are numbered in the sequence in which they are executed.
Magics can be used to insert and execute code not written in Python, e.g. HTML:
In [ ]:
%%html
<style>
div.text_cell_render h3 {
color: #c60;
}
</style>
Formatting can be down in markdown and HTML.
Examples:
codeMathematics is displayed with MathJax (www.mathjax.org) and requires either an internet connection or a local installation. Instructions for a local installation can be obtained as follows:
In [ ]:
from IPython.external import mathjax
mathjax?
In [ ]:
import numpy as np
np.tensordot?
Description including code (if available)
In [ ]:
np.tensordot??
Code completion with TAB
In [ ]:
np.ALLOW_THREADS
In [ ]:
2**3
In [ ]:
_-8
In [ ]:
__**2
In [ ]:
In, Out
In [ ]:
%lsmagic
Quick reference
In [ ]:
%quickref
Timing of code execution
In [ ]:
%timeit 2.5**100
In [ ]:
import math
In [ ]:
%%timeit
result = []
nmax = 100000
dx = 0.001
for n in range(nmax):
result.append(math.sin(n*dx))
In [ ]:
%%timeit
nmax = 100000
dx = 0.001
x = np.arange(nmax)*dx
result = np.sin(x)
IPython allows for the representation of objects in formats as different as
In [ ]:
from IPython.display import Image
Image("./images/ipython_logo.png")
In [ ]:
from IPython.display import HTML
HTML('<iframe src="http://www.ipython.org" width="700" height="500"></iframe>')
Even the embedding of audio and video files is possible.
In [ ]:
from IPython.display import YouTubeVideo
YouTubeVideo('F4rFuIb1Ie4')
Python allows for a textual representation of objects by means of the __repr__ method.
example:
In [ ]:
class MyObject(object):
def __init__(self, obj):
self.obj = obj
def __repr__(self):
return ">>> {0!r} / {0!s} <<<".format(self.obj)
x = MyObject('Python')
print(x)
A rich representation of objects is possible in the IPython notebook provided the corresponding methods are defined:
_repr_pretty__repr_html__repr_markdown__repr_latex_repr_svg__repr_json__repr_javascript__repr_png__repr_jpeg_Note: In contrast to __repr__ only one underscore is used.
In [ ]:
class RGBColor(object):
def __init__(self, r, g, b):
self.colordict = {"r": r, "g":g, "b": b}
def _repr_svg_(self):
return '''<svg height="50" width="50">
<rect width="50" height="50" fill="rgb({r},{g},{b})" />
</svg>'''.format(**self.colordict)
c = RGBColor(205, 128, 255)
c
In [ ]:
from fractions import Fraction
class MyFraction(Fraction):
def _repr_html_(self):
return "<sup>%s</sup>⁄<sub>%s</sub>" % (self.numerator,
self.denominator)
def _repr_latex_(self):
return r"$\frac{%s}{%s}$" % (self.numerator, self.denominator)
def __add__(a, b):
"""a + b"""
return MyFraction(a.numerator * b.denominator +
b.numerator * a.denominator,
a.denominator * b.denominator)
MyFraction(12, 345)+MyFraction(67, 89)
In [ ]:
from IPython.display import display_latex
display_latex(MyFraction(12, 345)+MyFraction(67, 89))
In [ ]:
from IPython.html.widgets import interact
In [ ]:
@interact(x=(0., 10.), y=(0, 10))
def power(y, x=2):
print(x**y)
In [ ]:
@interact(x=(0, 5),
text="Python is great!!!")
def f(text, x=0):
for _ in range(x):
print(text)
In [ ]:
from IPython.html import widgets
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# otherwise matplotlib graphs will be displayed in an external window
@interact(harmonics=widgets.IntSlider(min=1, max=10,
description='Number of harmonics',
padding='2ex'),
function=widgets.RadioButtons(options=("square",
"sawtooth",
"triangle"),
description='Function')
)
def f(harmonics, function):
params = {"square": {"sign":1, "stepsize": 2, "func": np.sin, "power": 1},
"sawtooth": {"sign": -1, "stepsize": 1, "func": np.sin, "power": 1},
"triangle": {"sign": 1, "stepsize": 2, "func": np.cos, "power": 2}
}
p = params[function]
xvals, nvals = np.ogrid[-2*np.pi:2*np.pi:100j, 1:harmonics+1:p["stepsize"]]
yvals = np.sum(p["sign"]**nvals*p["func"](nvals*xvals)/nvals**p["power"],
axis=1)
plt.plot(xvals, yvals)
See also the tutorial by Cyrille Rossant at https://github.com/rossant/euroscipy2014.
ipython notebook --to format notebook filename
Output formats:
reveal.jsStatic representation of notebooks: nbviewer.ipython.org