iPython Notebook Introduction

Some of these topics compiled from a course created by Jake Vanderplas at UW. See https://github.com/jakevdp/2013_fall_ASTR599/

The complete documentation for the iPython notebook: http://ipython.org/ipython-doc/dev/notebook/index.html


This tour can be done interactively with the students and the notebook provided for reference.


Introduction

iPython: interactive Python

iPython Notebook: A platform for writing/documenting iPython code


Review the File menu and the toolbar, basic navigation.

  • Shift-Enter: run cell and move to new cell below.
  • Control-Enter: run cell and stay in the cell.

Get help with ?


In [ ]:
?

Enter code in code cells and run it with Shift-Enter:


In [ ]:
print "Hello"

In [ ]:
a = 10

In [ ]:
print a

In [ ]:
for i in range(a): print i

Markdown

To format text and equations in notebooks, we use the Markdown syntax. Look in the Help menu for more info. This webpage was generated from an iPython notebook using Markdown. Here are a few resources:

Accessing the underlying operating system

Note: the commands below work on Linux or Macs, but may behave differently on Windows, as the underlying OS is different. IPython's ability to access the OS is still the same, it's just the syntax that varies per OS.


In [ ]:
!pwd

In [ ]:
files = !ls
print "My current directory's files:"
print files

In [ ]:
!echo $files

In [ ]:
!echo {files[0].upper()}

Magic Functions


In [ ]:
%magic

In [ ]:
%timeit range(10)

In [ ]:
%%timeit
range(10)
range(100)

Can be used inside code blocks:


In [ ]:
for i in range(5):
    size = i*100
    print 'size:',size, 
    %timeit range(size)

Run bash shell commands:


In [ ]:
%%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 [ ]:
%%file test.txt
This is a test file!
It can contain anything I want...

more...

In [ ]:
!cat test.txt

In [ ]:
mystring = !cat test.txt

In [ ]:
print mystring

To see what other magics are available:


In [ ]:
%lsmagic

Error reporting and interpretation


In [ ]:
def f(x):
    return 1.0/(x-1)

def g(y):
    return f(y+1)

In [ ]:
g(0)

Raw input:


In [ ]:
enjoy = raw_input('Are you enjoying this tutorial ?')
print 'enjoy is :', enjoy

Modules

Modules are organized units of code which contain functions, classes, statements, and other definitions.

Any file ending in .py is treated as a module. Let's create one and then import it.

Variables in modules have their own scope: using a name in one module will not affect variables of that name in another module.


In [ ]:
%%file mymodule.py
# A simple demonstration module

def add_numbers(x, y):
    """add x and y"""
    return x + y

def subtract_numbers(x, y):
    """subtract y from x"""
    return x - y

Modules are accessed using import module_name (with no .py)


In [ ]:
from mymodule import *

In [ ]:
print '1 + 2 =',add_numbers(1, 2)

In [ ]:
print '1 + 2 =', mymodule.add_numbers(1, 2)
print '5 - 3 =', mymodule.subtract_numbers(5, 3)

Several ways to import modules:

As a separate namespace:


In [ ]:
import mymodule
mymodule.add_numbers(1, 2)

Import a single function or name:


In [ ]:
from mymodule import add_numbers
add_numbers(1, 2)

Rename module or contents:


In [ ]:
from mymodule import add_numbers as silly_function
silly_function(1, 2)

In [ ]:
import mymodule as mm
mm.add_numbers(1,2)

A few built-in modules

  • sys: exposes interactions with the system (environment, file I/O, etc.)
  • os: exposes platform-specific operations (file statistics, directories, paths, etc.)
  • math: exposes basic mathematical functions and constants (but we will use numpy for most math)

All built-in modules are listed at http://docs.python.org/2/py-modindex.html

A few others we will use extensively:

  • numpy: numerical python library for vectorized arrays
  • scipy: scientific libraries for python
  • matplotlib: plotting and graphing library
  • ipythonblocks: a separate little module that makes programming logic visual

In [ ]:
import sys
import os

print "You are using Python version", sys.version
print 40 * '-'
print "Current working directory is:"
print os.getcwd()
print 40 * '-'
print "Files in the current directory:"
for f in os.listdir(os.getcwd()):
    print f

Plotting in the notebook

We'll be doing a lot of this and we'll have a longer lesson on Matplotlib in a week or so, but in the meantime...


In [ ]:
%matplotlib inline

In [ ]:
import numpy as np
import matplotlib.pyplot as plt

In [ ]:
x = np.linspace(0, 2*np.pi, 300)
y = np.sin(x**2)
plt.plot(x, y)
plt.title("A little chirp");

Python Glossary of Programming Terms

InterpretedNo need for a compiling stage
Object-orientedObjects: complex data structures with attributes and methods
High-levelAbstraction from the way the machine actually executes
DynamicVariables can change meaning on-the-fly
Built-inFewer external requirements
Data structuresWays of storing/manipulating data
Script/GlueCode that controls other programs
TypingThe kind of variable (int, string, float)
SyntaxGrammar which defines the language
Libraryreusable collection of code

All content is under a modified MIT License, and can be freely used and adapted. See the full license text here.