Python Tutorial

adventurescoldSoftware and s/w Development

Nov 7, 2013 (3 years and 5 months ago)


Python Tutorial
Python represents an interpreted general-purpose programming language that draws from object-oriented,
imperative,and functional programming.One aspect of python that makes it attractive is its comprehensive
libraries and packages.In this course,the NumPy and SciPy packages will prove most important.
The company Enthought offers a Python distribution that is free for students and educators.Once down-
loaded,it offers the command-line interpreter ipython that can be used to run the programs needed for this
course.When working in ipython,one can call existing functions,define variables,and define new functions.
One such function is the type function is the type function which returns the type of any expression.For
out:<type ’int’>
where the syntax following in:is typed on the command line,and,after pressing enter,the syntax following
out:is what is returned by the interpreter.In this case,the output indicates that 1 + 1 is an integer
To define a variable within the ipython,simply provide its name,followed by =,followed by an expression
whose value the variable will be set to.For example,
in:s ="Hello"+"World!"
out:’Hello World!’
assigns variable s to the string “Hello World!”.Then s is provided as input,which yields its value as output.
Notice here that strings in python can be written with either single or double quotes.
Boolean Operators:True,False,not,and,or
Bitwise Operators:
not:~ and:& or:| xor:^
Some unusual relational operators:
reference equality:is
For example,
in:a = [1]//the list containing element 1
in:b = [1]
in:a is b
since a and b are referencing different lists.
Lists.A list is a comma-delimited list of objects that are enclosed within brackets [].Note that the objects
can be of different types.For example,
in:a = [1,3.2,’hello’,[2,3,4]]
is a list,where the last element of the list is also a list.Brackets are also used to access particular elements
of a list.
Python also makes use of the slice operator,which has three components:start:stop:step.In general,
a[x:y:z] is the sublist of a that is equal to [a[x],a[x + z],a[x + 2z],...,a[x + mz],where m ≥ 0 is the
greatest integer for which mz < y.
Note that if x is omitted,then one starts at the beginning of the list.Similarly,if y is omitted,then the
sublist is taken to the end of the list.Finally,if z is omitted,then the step size is set to 1.Also,::−1 has
the effect of reversing the list.
Example 1.Given the list a = [1,2,...,100].Use the slice operator to obtain the sublist of a consisting
of i) integers [40,...,50],ii) all even integers of a,and iii) all multiples of 3 that do not exceed 60.
List copying.Given list a,a shallow copy of a is obtained using a[:].The copy is shallow,since the
resulting list is a new list,yet still has the same references to the object elements of a.To obtain a deep
copy,one must use the deepcopy() function from python’s copy package.
in:import copy
We note in passing that the access and slice operators also work for strings and tuples (see below),as do
the following sequence operators.Let s and t be sequenced objects (e.g.,a lists,tuples,or strings).Let x
and i be objects,and n be a nonnegative integer.Then
x in s true if x is a member of s
s + t concatenation of s with t
s*n s concatenated with itself n times
len(s) length of s
min(s) minimum element of s
max(s) maximal element of s
s.index(i) first index where i occurs in s
s.count(i) number of times i occurs in s
Tuples.A tuple is a list that is read-only,and uses parentheses as delimiters instead of brackets.
Dictionaries.A dictionary is a list of pairs of the form {x
},where x
is a hashable
object,called the key,and y
is called the value associated with the key.For example,
in:d = {’a’:1,’b’:2,’c’:3}
File I/O.
a = open(’filename’) open the file with the given name
a = open(’filename’,’x’) open with permission x,where x in {a,w,r}
a.close() close file a read all of file a
a.readline() read next line
a.readlines() read in all lines that returned in a list
a.write(string) write the given text string to the file
Modules.A module is a resource (usually a file with extension) that contains resources,such as
functions,classes,and commands.
import m import module m
from m import r import resource r from module m
from m import * import all resources from module m
m.r apply resource r
reload(m) reload module m
To import a module,it must be located in a directory that is listed in path which is a list resource in the
sys module.For example,to import python modules that are located in
The following steps are taken.
in:import sys
Control Flow.//if blocks
if statement:
for loops
for var in set:
while loops
while condition:
def name(args):
return value
Example 2.Implement a Python function that returns the minimum of three real inputs.
def min(x,y,z):
#Below is official python documentation
""""computes the minimum of three inputs"""
#This is a python comment.
if x <= y:
if x <= z:
m = x
m = z
elif y <= z:
m = y
m = z
return m
Note:changing the function heading to
def min(x=1,y=2,z=3):
establishes default values that are used in case of missing arguments.The following examples illustrate this.
When using the for loop,the range() function proves useful.Its syntax is very similar to the slice operator:
For example range(5) yields the list [0,1,2,3,4].While range(10:-5:-2) produces [10,8,6,4,2,0,−2,−4].
The map function.The map() function takes two arguments:a function and a list of function inputs in
the form of tuples.It then returns a list of the function outputs that correspond to the inputs.For example,
using the min() function defined above yields the following.
Another useful function is filter() whose first argument is a Boolean function,and whose second argument
is a list of inputs to the function.It then returns a sublist of all inputs that caused the Boolean to evaluate
to true.Consider the following example.
For both of the above functions,if one prefers to use an expression instead of a designated function,then
the lambda command proves useful.The syntax for the lambda command is
lambda x:expr
where expr is an expression (that normally contains x).Thus,lambda may be thought of as a function
whose input is x,and whose corresponding output is expr.
Example 3.Use map,range,and lambda to create a list of the first one hundred positive perfect squares.
Defining Python Classes.The syntax for defining a Python class is
class classname(superclass)
def __init__(self,args):
def functionname(self,args):
Example 4.Define the point class that represents a two-dimensional cartesian point.Add two methods:
(length()) for computing the length of the point when viewed as a vector,and (distance(p)) for computing
the distance from another point.
class point
def __init__(self,x,y):
self.x = x
self.y = y
def length(self):
return math.sqrt(self.x**2 + self.y**2)
def distance(self,p):
return math.sqrt((self.x-p.x)**2+(self.y-p.y)**2)
The following creates point objects and computes their distance from each other.
in:p1 = point.point(2,4)
in:p2 = point.point(2,5)
Arrays.Arrays is the basic data structure that is used for numerical work.It can be of any dimension,
and its elements must all be of the same type:either Boolean (dtype=bool),integer (dtype=int),real
(dtype=float),or complex (dtype=complex).Arrays can be constructed using lists.
in:a = array([3,-1,2])
in:a2 = array([[1,0,0],[0,1,0],[0,0,1]])
Methods for Array Creation.The following functions can be used for creating arrays.
arange(n) creates the array [0,1,...,n-1]
arange(i,j,k) [i,i+k,i+2k,...,i+mk],mk < j,(m+1)k >= j
ones(n) 1-dimensional array of size n [1.,1.,...,1.]
ones((m,n)) m by n integer matrix of ones
zeros similar to ones
eye(n) identity matrix of size n
eye(m,n) identity matrix with extra columns (rows)
padded with zeros
linspace(i,j,k) array starting at i,ending at j,and having
k equal-spaced elements
r_[] row concatenation
c_[] column concatenation
More Array Functions.
ndim(a) number of dimensions of a
size(a) number of elements of a
shape(a) returns a tuple that gives the dimensions of a
reshape(a,t) returns the reshaping of a according to tuple t.
Using -1 in a component of t means"as many as needed"
ravel(a) returns flattened 1d version of a
transpose(a) matrix transpose
a[::-1] reverse the elements of each dimension
a.min(),a.max() minimum and maximum elements of a
a.sum() sum of all elements of a
a.sum(axis=0) returns an array of column sums
a.sum(axis=1) returns an array of row sums
a+b a-b matrix addition/subtraction
a*b a/b element-wise mult./division
c*A A/c scalar multiplication/division
dot(a,b) matrix multiplication
pow(a,n) returns a with elements raised to nth power
pow(n,a) computes number raised to matrix elements
where(condition(a)) returns an array of all indices for which
condition(a) is true
where(cond(a),i,j) returns an array with same dimensions as a
with i in entries where cond(a) is true,and j in other entries
Example 5.Given matrix a,write code that allows for matrix b to be defined as a random permutation of
the rows (columns) of a.
Example 6.Define a 4 ×3 matrix a using random integers,and from that create a new boolean matrix b
which has a 1 wherever a is positive,and a zero otherwise.
Example 7.Define a 12×3 matrix a,and define 4×3 matrices b,c,and d,where b consists of rows 0,3,6,9
of a,c consists of rows 1,4,7,10 of a,and d consists of rows 2,5,8,11 of a.
Example 8.Show that,when first reversing the rows of the identify matrix,followed by reversing the
elements of each row,then the original matrix results.
Example 9.Given two n-dimensional arrays x and y,compute exp