This notebook was put together by [Jake Vanderplas](http://www.vanderplas.com) for UW's [Astro 599](http://www.astro.washington.edu/users/vanderplas/Astr599/) course. Source and license info is on [GitHub](https://github.com/jakevdp/2013_fall_ASTR599/).
The basic IPython client: at the terminal, simply type ipython
:
$ ipython
Python 2.7.4 (default, Apr 19 2013, 18:28:01)
Type "copyright", "credits" or "license" for more information.
IPython 1.0.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: print "hello world"
hello world
When executing code in IPython, all valid Python syntax works as-is, but IPython provides a number of features designed to make the interactive experience more fluid and efficient.
In the notebook, to run a cell of code, hit Shift-Enter
. This executes the cell and puts the cursor in the next cell below, or makes a new one if you are at the end. Alternately, you can use:
Alt-Enter
to force the creation of a new cell unconditionally (useful when inserting new content in the middle of an existing notebook).Control-Enter
executes the cell and keeps the cursor in the same cell, useful for quick experimentation of snippets that you don't need to keep permanently.
In [1]:
print "Hello"
In [2]:
?
In [3]:
import collections
collections.namedtuple?
In [4]:
collections.Counter??
In [5]:
*int*?
An IPython quick reference card:
In [6]:
%quickref
Tab completion, especially for attributes, is a convenient way to explore the structure of any object you’re dealing with. Simply type object_name.<TAB>
to view the object’s attributes. Besides Python objects and keywords, tab completion also works on file and directory names.
In [7]:
collections.
In [8]:
2+10
Out[8]:
In [9]:
_+10
Out[9]:
In [10]:
10+20;
In [11]:
_
Out[11]:
In [12]:
_10 == Out[10]
In [13]:
Out
Out[13]:
And the last three have shorthands for convenience:
In [14]:
print 'last output:', _
print 'next one :', __
print 'and next :', ___
In [15]:
In[11]
Out[15]:
In [16]:
_i
Out[16]:
In [17]:
_ii
Out[17]:
In [18]:
print 'last input:', _i
print 'next one :', _ii
print 'and next :', _iii
In [19]:
%history
In [20]:
!pwd
In [21]:
files = !ls
print "My current directory's files:"
print files
In [22]:
!echo $files
In [23]:
!echo {files[0].upper()}
The IPyhton 'magic' functions are a set of commands, invoked by prepending one or two %
signs to their name, that live in a namespace separate from your normal Python variables and provide a more command-like interface. They take flags with --
and arguments without quotes, parentheses or commas. The motivation behind this system is two-fold:
To provide an orthogonal namespace for controlling IPython itself and exposing other system-oriented functionality.
To expose a calling mode that requires minimal verbosity and typing while working interactively. Thus the inspiration taken from the classic Unix shell style for commands.
In [24]:
%magic
Line vs cell magics:
In [25]:
%timeit range(10)
In [26]:
%%timeit
range(10)
range(100)
Line magics can be used even inside code blocks:
In [27]:
for i in range(5):
size = i*100
print 'size:',size,
%timeit range(size)
Magics can do anything they want with their input, so it doesn't have to be valid Python:
In [28]:
%%bash
echo "My shell is:" $SHELL
echo "My memory status is:"
free
Another interesting cell magic: create any file you want locally from the notebook:
In [29]:
%%file test.txt
This is a test file!
It can contain anything I want...
more...
In [30]:
!cat test.txt
Let's see what other magics are currently defined in the system:
In [31]:
%lsmagic
Out[31]:
Not only can you input normal Python code, you can even paste straight from a Python or IPython shell session:
In [32]:
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print b
... a, b = b, a+b
In [33]:
In [1]: for i in range(10):
...: print i,
...:
In [34]:
%%file mod.py
def f(x):
return 1.0/(x-1)
def g(y):
return f(y+1)
Now let's call the function g
with an argument that would produce an error:
In [35]:
import mod
mod.g(0)
In [ ]:
%xmode plain
mod.g(0)
In [ ]:
In [ ]:
%xmode verbose
mod.g(0)
The default %xmode
is "context", which shows additional context but not all local variables. Let's restore that one for the rest of our session.
In [ ]:
%xmode context
Since 1.0 the IPython notebook web application support raw_input
which for example allow us to invoke the %debug
magic in the notebook:
In [ ]:
mod.g(0)
In [ ]:
%debug
Don't foget to exit your debugging session. Raw input can of course be use to ask for user input:
In [ ]:
enjoy = raw_input('Are you enjoying this tutorial ?')
print 'enjoy is :', enjoy
This imports numpy as np
and matplotlib's plotting routines as plt
, plus setting lots of other stuff for you to work interactivel very easily:
In [ ]:
%pylab inline
In [ ]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import gcf
In [ ]:
x = np.linspace(0, 2*np.pi, 300)
y = np.sin(x**2)
plt.plot(x, y)
plt.title("A little chirp")
f = gcf() # let's keep the figure object around for later...
.ipynb
) on your file systemIf you cd to a Notebook directory and type:
ipython notebook
you will see the Notebooks in that directory in the dashboard
In [ ]:
from IPython.nbformat import current
with open('03_IPython_intro.ipynb') as f:
nb = current.read(f, 'json')
In [ ]:
nb.worksheets[0].cells[0:5]
IPython Notebooks can also be exported to .py
files (see "File:Download As" menu item). You can tell the Notebook server to always save these .py
files alongside the .ipynb
files by starting the Notebook as:
ipython notebook --script
You can import Notebooks from the main Dashboard or simply by copying a Notebook into the Notebook directory.
Find a Notebook shared from the IPython Notebook Gallery and Download it via http://nbviewer.ipython.org. Then import it into your running Notebook server using the Dashboard.
If you have time, download and explore this notebook, which will introduce you to the use of markdown cells in the notebook.