If you have installed IPython correctly, you should be able to type ipython
in your command prompt and see something like this:
IPython 4.0.1 -- 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]:
With that, you're ready to follow along.
The IPython notebook is a browser-based graphical interface to the IPython shell, and builds on it a rich set of dynamic display capabilities. As well as executing Python/IPython statements, the notebook allows the user to include formatted text, static and dynamic visualizations, mathematical equations, javascript widgets, and much more. Furthermore, these documents can be saved in a way that lets other people open them and execute the code on their own systems.
Though the IPython notebook is viewed and edited through your web browser window, it must connect to a running Python process in order to execute code. This process (known as a "kernel") can be started by running the following command in your system shell:
$ ipython notebook
This command will launch a local web server which will be visible to your browser. It immediately spits out a log showing what it is doing; that log will look something like this:
$ ipython notebook
[NotebookApp] Using existing profile dir: '/home/jake/.ipython/profile_default'
[NotebookApp] Serving notebooks from local directory: /home/jake/notebooks/
[NotebookApp] The IPython Notebook is running at: http://localhost:8888/
[NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation)
At the command, your default browser should automatically open and navigate to the listed local URL;
the exact address will depend on your system.
If the browser does not open automatically, you can open a window and copy this address (here http://localhost:8888/
) manually.
In [1]:
1 + 1
Out[1]:
In [2]:
_ * 100
Out[2]:
In [3]:
_ + __
Out[3]:
In [4]:
_ + __ ** ___
Out[4]:
Beyond three underscores, you can use underscore followed by a number to indicate the result of a particular line number:
In [8]:
_3
Out[8]:
More useful often is the Out
array, which stores all previous results:
In [9]:
Out[3]
Out[9]:
In [10]:
Out
Out[10]:
Similarly, you can access the In
array to see the code history:
In [11]:
In[2]
Out[11]:
In [12]:
In
Out[12]:
To see all history at once, use the %history
magic command (more on magic commands below):
In [13]:
%history
It works for variables that you have defined:
In [21]:
my_variable = 4
In [22]: my<TAB>
will be completed to
In [22]: my_variable
This also works for strings which represent filenames, or pandas columns, etc.
It works for importing packages:
In [25]: import num<TAB>
will be completed to
In [25]: import numpy
It works for finding attributes of packages and other objects:
In [25]: numpy.ran<TAB>
will be completed to
In [25]: numpy.random
After tab completion, I think the next most useful feature of the notebook is the help functionality.
One question mark after any valid object gives you access to its documentation string:
In [ ]:
numpy.random?
In [33]:
def myfunc(x):
return x ** 2
In [34]:
myfunc?
Two question marks gives you access to its source code (if the object is implemented in Python):
In [ ]:
myfunc??
In addition, you can use a single question mark with asterisks to do a wildcard match:
In [38]:
numpy.*exp*?
If you are curious about the call signature for a funciton, you can type shift tab
within the open-closed parentheses to see its argument list:
Hitting shift tab
multiple times will give you progressively more information about the function:
Using a combination of these, you can quickly remind yourself of how to use various funcitons without ever leaving the terminal/notebook.
Depending on your operating system and browser, many of the navigation and text-entry shortcuts will work in the notebook as well. In addition, the notebook has many of its own shortcuts.
First, though, we must mention that the notebook has two "modes" of operation: command mode and edit mode.
ctrl m
). For example, in command mode, the up and down arrows will navigate from cell to cell.To get a listing of all available shortcuts, enter command mode and press "h"
IPython extends the functionality of Python with so-called "magic" commands: these are marked with a %
sign.
We saw one of these above; the %history
command.
Magic commands come in two flavors: line magics start with one percent sign, and cell magics start with two percent signs.
We'll go through a few examples of magic commands here, but first, using what you've seen above, how do you think you might get a list of all available magic commands? How do you think you might get help on any particular command?
In [41]:
%timeit?
In [43]:
import numpy as np
x = np.random.rand(1000000)
%timeit x.sum()
In [44]:
L = list(x)
%timeit sum(L)
In [52]:
%%timeit
y = x + 1
z = y ** 2
q = z.sum()
In [19]:
%%file myscript.py
def foo(x):
return x ** 2
z = foo(12)
print(foo(14))
In [20]:
%run myscript.py
In [21]:
z
Out[21]:
In [22]:
foo(2)
Out[22]:
%matplotlib
You can use the %matplotlib
function to specify the matplotlib backend you would like to use.
For example:
%matplotlib
by itself uses the default system backend%matplotlib inline
creates inline, static figures (great for publication and/or sharing)%matplotlib notebook
creates inline, interactive figures (though in my experience it can be a bit unstable)
In [24]:
%matplotlib inline
In [25]:
import numpy as np
import matplotlib.pyplot as plt
plt.plot(np.random.rand(100));
%magic
function will tell you all about magic commands%lsmagic
function will list all available magic commands?
can be used to get documentation!
In [6]:
%lsmagic
In [ ]:
%magic
In [27]:
%debug?
IPython is meant to be an all-purpose scientific computing environment, and access to the shell is critical. Any command that starts with an exclamation point will be passed to the shell.
Note that because windows has a different kind of shell than Linux/OSX, shell commands will be different from operating system to operating system.
All the commands you have learned previously will work here:
In [ ]:
!ls
In [ ]:
!pwd
You can even seamlessly pass values to and from the Python interpreter. For example, we can store the result of a directory listing:
In [29]:
contents = !ls
In [30]:
contents
Out[30]:
We can inject Python variables into a shell command with {}
:
In [32]:
!cat {contents[4]}
In [37]:
for filename in contents:
if filename.endswith('.py'):
print(filename)
!head -10 {filename}
With these tools, you should never have to switch from IPython to a terminal to run a command.
One incredibly useful feature of the notebook is the interactivity provided by the ipywidgets
package. You'll have to install this using, e.g.
$ conda install ipywidgets
You can find a full set of documentation notebooks here. We're going to walk through a quick demonstration of the functionality in WidgetsDemo.ipynb