Introduction to Computational Analysis




Pay Notebook Creator: Roy Hyunjin Han0
Set Container: Numerical CPU with TINY Memory for 10 Minutes 0
Total0

IPython is for interactive Python

Interact in a browser

See a list of keyboard shortcuts.

In [ ]:
# Press ESC h

Execute code.

In [ ]:
# Press SHIFT-ENTER to execute the current cell and go to the next cell
[x * 2 for x in range(5)]
In [ ]:
# Press SHIFT-ENTER to execute the current cell and go to the next cell
x = 0
x
In [ ]:
# Press CTRL-ENTER to execute the current cell in place
x += 1
x
In [ ]:
# Press ALT-ENTER to execute the current cell and insert a new code cell below
from collections import defaultdict
d = defaultdict(int)
for x in 'blueberries':
    d[x] += 1
for k in sorted(d, key=lambda k: -d[k]):
    print('%s %s' % (k, d[k]))

Insert code blocks.

In [ ]:
# Press CTRL-m a to insert a code cell above
# Press CTRL-m b to insert a code cell below

Use TAB completion.

In [ ]:
import IPython
# Press CTRL-ENTER to run the cell
# Press ENTER to start edit mode
# Type IP<TAB>.<TAB> to see options
# Type IP<TAB>.v<TAB> to autocomplete

Get help.

In [ ]:
# Type zip and press SHIFT-TAB to see a tip
In [ ]:
# Type zip? and press CTRL-ENTER to see documentation
# Press ESC to exit
In [ ]:
# Type IPython?? and press CTRL-ENTER to see source code
# Press ESC to exit

Split blocks.

In [ ]:
# Place your cursor below this line and press SHIFT-CTRL--

# Wheee!

Use shell command magic with TAB completion.

In [ ]:
ls datasets
In [ ]:
files = !ls  # Store shell output in a variable
len(files)
In [ ]:
# First type %cd /tmp<CTRL-ENTER>
%cd /tmp
In [ ]:
# Then type cd -<CTRL-ENTER>
%cd -

Copy and paste code and IPython will parse it intelligently.

>>> def f(x, y):
...     print(x + y)
>>> f(1, 2)
In [ ]:
# Paste the above code here and press CTRL-ENTER

Examine variables in your session namespace.

In [ ]:
# Press SHIFT-ENTER
x = 1
In [ ]:
whos

Compare execution speed.

In [ ]:
timeit 10 ** 10
In [ ]:
timeit pow(10, 10)

Write mathematical expressions in LaTeX thanks to MathJax.

$\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)$

Surround text with quotes, parentheses and brackets

In [ ]:
# Select this text and press " to surround the text with quotes
# Select this text and press ( to surround the text with parentheses
# Select this text and press [ to surround the text with brackets

Interact in a terminal

Start IPython in a terminal.

ipython
ipython --pylab   # Plot interactively without calling pylab.show()

Expand variables in shell commands.

x = 'Documents'
%ls ~/$x

Use the underscore.

1 + 1
_          # Press ENTER to use the previous result
_ + 1      # Press ENTER to use the previous result

Complete lines using your command history.

           # Press UP or DOWN to cycle through previous commands
x          # Press CTRL-p or CTRL-n to see previous commands starting with the letter x
           # Press CTRL-r and type the letter o to recall previous commands containing the letter o

Use other commands from readline.

import os  # Press CTRL-u to clear text before the cursor
import os  # Press CTRL-k to clear text after the cursor

Edit a block of commands using your favorite editor.

edit
edit example.py
run example

Examine your command history.

hist               # Look at your session command history
hist -g            # Look at your global command history.
hist -g join       # Search global command history for the keyword join
recall 1           # Recall command for editing from history slot number one
rerun 1            # Rerun command from history slot number one

Use other magic commands.

import os
reload(os)         # Reload a previously imported module in case its contents have changed
/reload os         # reload(os)           Add parentheses
; print hi there   # print('hi there')    Add parentheses, quotes
, print hi there   # print('hi', 'there') Add parentheses, quotes, commas

def f(x):
    print x + 1
f(None)
pdb                # Toggle automatic debugging
f(None)
                   # Press CTRL-d to exit the debugger

For more readline commands, please see Jan Tomka's sheet.

For more IPython commands, please see the IPython documentation.

Interact inside a program

Drop into an IPython prompt to examine variables.

In [ ]:
def f(text):
    word_count = len(text.split())
    # import IPython; IPython.embed()
    return '%s words' % word_count

f('one two three')
# Uncomment the line above
# Press CTRL-ENTER to run this cell
# Type whos and press ENTER
# Type exit and press ENTER

Drop into a debugger (command-line users should take advantage of PuDB).

In [ ]:
def f(x):
    # from IPython.core import debugger; debugger.set_trace()
    x = x * 2
    x = x + 1
    return x

f(1)
# Uncomment the line above
# Press CTRL-ENTER to run this cell
# Type n and press ENTER
# Type q and press ENTER

Debug post mortem.

In [ ]:
def f(x):
    return x / 0
    
# f(1)
# Uncomment the line above
# Press SHIFT-ENTER to run this cell and move to the next cell
# See ZeroDivisionError
# Uncomment the next cell
# Press CTRL-ENTER to run the next cell to examine the exception
# Type u and press ENTER
# Type q and press ENTER
In [ ]:
# debug

To automatically drop into a debugger on an exception, toggle pdb.

In [ ]:
# pdb
In [ ]:
import this
In [ ]:
from IPython.lib.display import YouTubeVideo
YouTubeVideo('iwVvqwLDsJo')