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. IDEs: PyCharm or Visual Studio Code

    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 support issues with IDEs.

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. Type Ctrl+Enter to run but not advance.

In [10]:
x = 2*x
print(x)
128

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 [12]:
%run hello.py
hello CS335

Create a plot using matplotlib

In [13]:
%matplotlib inline
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2.3, 3.5, 4.8, 20]
plt.plot(x, y)
plt.show()

Basic Data Types

Numerical and Logical Types

In [14]:
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=500000000000000000000000000000000000000000000000000000000000000 # Python 3 integers have arbitrary precision
print("4: X=",X)
1: X 5
2: X= 5.0
3: X= True
4: X= 500000000000000000000000000000000000000000000000000000000000000

Strings

In [15]:
X="This is a string" #Set X to a string object defined using double quotes
print(X)
This is a string
In [16]:
Y='So is this!' #Set X to a string object defined using single quotes
print(Y)
So is this!
In [17]:
print(X[0])
T
In [18]:
print(X[0:5] )
This 
In [19]:
print(X.split())
['This', 'is', 'a', 'string']
In [20]:
print(X + Y)
print(X + '. ' + Y)
This is a stringSo is this!
This is a string. So is this!

Containers

Tuples

In [21]:
X = (1,2,3,4,5)            #Define tuple
print(type(X))
<class 'tuple'>
In [22]:
print("X=", X)           #Print the tuple 
X= (1, 2, 3, 4, 5)
In [23]:
print("X[0]=", X[0])     #Print the first element of the tuple
X[0]= 1
In [24]:
print( X[4] )    #Print the last element of the tuple
print( X[-1] )   #Print the last element of the tuple
5
5
In [25]:
print(len(X)) #Pring length of tuple
5
In [26]:
X[0]=5                  #Set element of tuple ! ERROR (tuples are immutable)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-21595cb19964> in <module>
----> 1 X[0]=5                  #Set element of tuple ! ERROR (tuples are immutable)

TypeError: 'tuple' object does not support item assignment

Lists

In [27]:
X = [1,2,3,4,5]         #Define list
print(type(X))           #Show type of X
<class 'list'>
In [28]:
print(X)       #Print the list
[1, 2, 3, 4, 5]
In [29]:
print(X[0])     #Print the first element of the list
1
In [30]:
print(X[4])
print(X[-1])    #Print the last element of the list
5
5
In [31]:
print(len(X))
5
In [32]:
X[0] = 5                  #Change the list. 
print(X)
[5, 2, 3, 4, 5]
In [33]:
X.append(6)          # Append *one* item to list
print(X)
[5, 2, 3, 4, 5, 6]
In [34]:
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 [35]:
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 [36]:
X = [1, 2, 3, 4, 5]
Y=X*2           # concatenate two copies of X (think: X+X)
print(Y)
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

Dictionaries

In [37]:
X = {"Bob": 192731, "Mary": 281927, "Joe": 103124} #Define a dictionary of key-value pairs
print("type(X)",type(X))
type(X) <class 'dict'>
In [38]:
print("X=", X)                    #Print the dictionary
X= {'Bob': 192731, 'Mary': 281927, 'Joe': 103124}
In [39]:
print('X["Joe"]=', X["Joe"])      #Print the value for Joe
X["Joe"]= 103124
In [40]:
print('len(X)', len(X))           #Print the number of items
len(X) 3
In [41]:
print('X.keys()=',X.keys())       #Print the list of keys
X.keys()= dict_keys(['Bob', 'Mary', 'Joe'])
In [42]:
print('X.values()=',X.values())   #Print the list of values
X.values()= dict_values([192731, 281927, 103124])
In [43]:
X["Joe"]=772345                   #Change an element
print("X=", X)
X= {'Bob': 192731, 'Mary': 281927, 'Joe': 772345}
In [44]:
X["Alice"]=111111                 #Add a new element
print("X=", X) 
X= {'Bob': 192731, 'Mary': 281927, 'Joe': 772345, 'Alice': 111111}

Containers with Nesting and Mixed Elements

In [45]:
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 [46]:
#How can we get the second item in the tuple at the end of the list?
print(X[-1][1])
True

Assignment Dynamics

In [47]:
A = 5  #Assign the object "5" to the name A
B = A  #Assign the object that A refers to to the name B
print("A=",A,"B=",B )
A= 5 B= 5
In [48]:
B = 7               
print("A=",A,"B=",B)
A= 5 B= 7
In [49]:
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 [50]:
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 [52]:
A = [1,2,3,4,5]
B=A
A.append(6)
B.append(7)
print ("A=",A,"B=",B )
A= [1, 2, 3, 4, 5, 6, 7] B= [1, 2, 3, 4, 5, 6, 7]
In [53]:
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 [54]:
#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 [61]:
#Basic for loop using range()
A = [1, 2, 3, 4, 5]
for i in range(len(A)): 
    print(i, A[i])
0 1
1 2
2 3
3 4
4 5
In [62]:
#Basic while loop
x=5    
while(x > 0):
    print(x),
    x-=1
5
4
3
2
1

Mathematical and Logical Operators

In [63]:
print ("2**4=", 2**4 )  # Computing Powers
2**4= 16
In [64]:
print ("2/4=", 2/4 )    # "True division" of int by int

# Note: the / operator for ints was "floor division" 
# in Python 2.x, so would give a result of 0 for this example
2/4= 0.5
In [65]:
print ("2//4=", 2//4 )  # "Floor division"
2//4= 0
In [ ]:
print ("2/4.=", 2/4.)   # Division of int by float (True division)
In [ ]:
print ("2./4=", 2./4)   # Division of float by int
In [ ]:
print ("True or False=", True or False) #Logical or
In [ ]:
print ("True and False=", True and False) #Logical and
In [ ]:
print ("not(False)=", not(False)) #Logical not

Functions

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

print ("f(2)=",f(2))
f(2)= 4
In [67]:
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 [68]:
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 [69]:
print ("X.shape=", X.shape)
X.shape= (3, 2)
In [73]:
print ("X[0,2]=", X[0,1])
X[0,2]= 2
In [74]:
print ("X[0,:]=", X[0,:])
X[0,:]= [1 2]
In [75]:
Y = X[0,:]
print(Y.shape)
(2,)
In [76]:
print ("X[:,1]=", X[:,1])
X[:,1]= [2 4 6]
In [77]:
print ("2*X=\n", 2*X)
2*X=
 [[ 2  4]
 [ 6  8]
 [10 12]]
In [78]:
print ("3: 5+X=\n", 5+X)
3: 5+X=
 [[ 6  7]
 [ 8  9]
 [10 11]]
In [79]:
Y = np.array([[-1,1,-1]])
print ("Y=\n",Y)
Y=
 [[-1  1 -1]]
In [80]:
print ("6: Y.T=\n", Y.T)
6: Y.T=
 [[-1]
 [ 1]
 [-1]]
In [ ]:
print ("Y.dot(X)=\n", Y.dot(X))
In [ ]:
print ("np.dot(Y, X)=\n", np.dot(Y, X))
In [ ]:
print ("Y.T + X =\n", Y.T + X)