Running Python

  1. Normal

    $ python foo.py
    
  2. Interactive

    $ python
    
  3. iPython (recommended)

    $ ipython
    
  4. Jupyter / iPython notebook (also recommended)

     $ jupyter notebook

    This is similar to iPython but browser based. It has some very cool features. For development, I have a slight preference for the simpler command-line iPython.

  5. PyCharm IDE

    You are on your own to figure this out. It may be very nice once setup, but you also may have some startup costs to configure it to work nicely with anaconda, matplotlib, etc. I will not be able to support PyCharm issues.

A typical setup

Windows open:

  • Favorite text editor, e.g. sublime (write programs)
  • Terminal running iPython (type commands)
  • Pop up figures with matplotlib

This mimics MATLAB or R desktop environments.

Plan

  • Example session
  • iPython
  • %run foo.py
  • Some pitfalls of coding interactively

Simple iPython notebook session

Running a cell

A cell is a block of code. Click the cell below and press the "play" button above or type Shift+Enter. The code will run, print output, and then advance to the next cell.

In [10]:
x = 1
print x
1

Running code in another file

Create a file in the same directory called hello.py with this line

print 'hello world'

Now you can run it from jupyter:

In [11]:
% run hello.py
hello world

Create a plot using matplotlib

In [12]:
% matplotlib inline
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2.3, 3.5, 4.8, 5.75]
plt.plot(x, y)
Out[12]:
[<matplotlib.lines.Line2D at 0x10cb27d90>]

Basic Data Types

Numerical and Logical Types

In [4]:
X=5 #Set X to integer object equal to 5
print "1: X",X

X=5.0 #Set X to float object equal to 5.0
print "2: X=",X

X=True #Set X to boolean True
print "3: X=",X

X=50000000000000000000L #Set X to long integer object equal to 5
print "4: X=",X
1: X 5
2: X= 5.0
3: X= True
4: X= 50000000000000000000

Strings

In [1]:
X="This is a string" #Set X to a string object defined using double quotes
print X
This is a string
In [2]:
Y='So is this!' #Set X to a string object defined using single quotes
print Y
So is this!
In [3]:
print X[0]
T
In [4]:
print X[0:5] 
This 
In [5]:
print X.split()
['This', 'is', 'a', 'string']
In [6]:
print X + Y
print X + '. ' + Y
This is a stringSo is this!
This is a string. So is this!

Containers

Tuples

In [7]:
X = (1,2,3,4,5)            #Define tuple
print type(X)
<type 'tuple'>
In [9]:
print "X=", X           #Print the tuple 
X= (1, 2, 3, 4, 5)
In [10]:
print "X[0]=", X[0]     #Print the first element of the tuple
X[0]= 1
In [8]:
print X[4]     #Print the last element of the tuple
print X[-1]    #Print the last element of the tuple
5
5
In [9]:
print len(X) #Pring length of tuple
5
In [12]:
X[0]=5                  #Set element of tuple ! ERROR
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-df8d83c387c5> in <module>()
----> 1 X[0]=5                  #Set element of tuple ! ERROR

TypeError: 'tuple' object does not support item assignment

Lists

In [29]:
X = [1,2,3,4,5]         #Define list
print type(X)           #Show type of X
<type 'list'>
In [30]:
print X           #Print the list
[1, 2, 3, 4, 5]
In [31]:
print X[0]     #Print the first element of the list
1
In [32]:
print X[4]
print X[-1]    #Print the last element of the list
5
5
In [33]:
print len(X)
5
In [34]:
X[0] = 5                  #Change the list. 
print  X         
[5, 2, 3, 4, 5]
In [27]:
X.append(6)
print X
[5, 2, 3, 4, 5, 6, [7, 8], [7, 8], 6]
In [37]:
X = [1, 2, 3, 4, 5, 6]
X.extend([7, 8]) # add elements 7, 8 to end of X
print X
[1, 2, 3, 4, 5, 6, 7, 8]
In [39]:
Y = X + [7,8]   # concatenate and retern a new list
print X
print Y
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 7, 8]
In [41]:
X = [1, 2, 3, 4, 5]
Y=X*2           # concatenate two copies of X
print Y
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

Dictionaries

In [23]:
X = {"Bob": 192731, "Mary": 281927, "Joe": 103124} #Define a dictionary of key-value pairs
print "type(X)",type(X)
type(X) <type 'dict'>
In [24]:
print "X=", X                    #Print the dictionary
X= {'Bob': 192731, 'Mary': 281927, 'Joe': 103124}
In [25]:
print 'X["Joe"]=', X["Joe"]      #Print the value for Joe
X["Joe"]= 103124
In [26]:
print 'len(X)', len(X)           #Print the number of items
len(X) 3
In [27]:
print 'X.keys()=',X.keys()       #Print the list of keys
X.keys()= ['Bob', 'Mary', 'Joe']
In [28]:
print 'X.values()=',X.values()   #Print the list of values
X.values()= [192731, 281927, 103124]
In [29]:
X["Joe"]=772345                   #Change an element
print "X=", X 
X= {'Bob': 192731, 'Mary': 281927, 'Joe': 772345}
In [30]:
X["Alice"]=111111                 #Add a new element
print "X=", X 
X= {'Bob': 192731, 'Mary': 281927, 'Alice': 111111, 'Joe': 772345}

Containers with Nesting and Mixed Elements

In [42]:
X = [1,"Foo",False,[1,2,3],(1,True)] #Lists can contain mixed types!
print "X=", X                        #Print the list
X= [1, 'Foo', False, [1, 2, 3], (1, True)]
In [43]:
#How can we get the second item in the tuple at the end of the list?
print X[-1][1]
True

Assignment Dynamics

In [34]:
A = 5  #Assign the object "5" to the name A
B = A  #Assign the object that A referes to to the name B
print "A=",A,"B=",B 
A= 5 B= 5
In [35]:
B = 7               
print "A=",A,"B=",B 
A= 5 B= 7
In [36]:
A = [1,2,3,4,5]
B = A
print "A=",A,"B=",B 
A= [1, 2, 3, 4, 5] B= [1, 2, 3, 4, 5]
In [37]:
A = [1,2,3,4,5]
B = A
B = [5,4,3,2,1]        
print "A=",A,"B=",B  
A= [1, 2, 3, 4, 5] B= [5, 4, 3, 2, 1]
In [38]:
A = [1,2,3,4,5]
B=A
A.append(6)
print "A=",A,"B=",B 
A= [1, 2, 3, 4, 5, 6] B= [1, 2, 3, 4, 5, 6]
In [39]:
A = [1,2,3,4,5]
B = A
B[0]=-1
print "A=",A,"B=",B
A= [-1, 2, 3, 4, 5] B= [-1, 2, 3, 4, 5]

Basic Control Flow

If-Elif-Else

In [40]:
#Basic If-Elif-Else
X=5
if(X<0):
    print("X is negative")
elif(X==0):
    print("X is zero")
else:
    print("X is positive")
X is positive

For and While

In [41]:
#Basic for loop using range()
for i in range(10): 
    print(i),
print    
0 1 2 3 4 5 6 7 8 9
In [42]:
#Basic while loop
x=5    
while(x > 0):
    print(x),
    x-=1
5 4 3 2 1

Mathematical and Logical Operators

In [43]:
print "2**4=", 2**4   #Computing Powers
2**4= 16
In [44]:
print "2/4=", 2/4     #Division of int by int
2/4= 0
In [45]:
print "2/4.=", 2/4.   #Division of int by float
2/4.= 0.5
In [46]:
print "2./4=", 2./4   #Division of float by int
2./4= 0.5
In [47]:
print "True or False=", True or False #Logical or
True or False= True
In [48]:
print "True and False=", True and False #Logical and
True and False= False
In [49]:
print "not(False)=", not(False) #Logical not
not(False)= True

Functions

In [50]:
def f(a):             #Define a basic function of 1-argument
    return a**2

print "f(2)=",f(2)
f(2)= 4
In [51]:
def g(h,a,b):         #Define a function of 3-arguments where h is a function and a and b are numbers
    return h(a)+h(b)

print "g(f,2,3)=",g(f,2,3)
g(f,2,3)= 13

NumPy Arrays

In [52]:
import numpy as np
X = np.array([[1,2],[3,4],[5,6]])
print "X=\n",X
X=
[[1 2]
 [3 4]
 [5 6]]
In [53]:
print "X.shape=", X.shape
X.shape= (3, 2)
In [54]:
print "X[0,:]=", X[0,:]
X[0,:]= [1 2]
In [55]:
print "X[:,1]=", X[:,1]
X[:,1]= [2 4 6]
In [56]:
print "2*X=\n", 2*X
2*X=
[[ 2  4]
 [ 6  8]
 [10 12]]
In [57]:
print "3: 5+X=\n", 5+X
3: 5+X=
[[ 6  7]
 [ 8  9]
 [10 11]]
In [61]:
Y = np.array([[-1,1,-1]])
print "Y=\n",Y
Y=
[[-1  1 -1]]
In [62]:
print "6: Y.T=\n", Y.T
6: Y.T=
[[-1]
 [ 1]
 [-1]]
In [63]:
print "Y.dot(X)=\n", Y.dot(X)
Y.dot(X)=
[[-3 -4]]
In [65]:
print "np.dot(Y, X)=\n", np.dot(Y, X)
np.dot(Y, X)=
[[-3 -4]]
In [66]:
print "Y.T + X =\n", Y.T + X
Y.T + X =
[[0 1]
 [4 5]
 [4 5]]
In [ ]: