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 oﬀers a Python distribution that is free for students and educators.Once down-

loaded,it oﬀers 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,deﬁne variables,and deﬁne new functions.

One such function is the type function is the type function which returns the type of any expression.For

example

in:type(1+1)

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

expression.

To deﬁne 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!"

in:s

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:

inequality:<>

reference equality:is

1

For example,

in:a = [1]//the list containing element 1

in:b = [1]

in:a is b

out:false

since a and b are referencing diﬀerent lists.

Lists.A list is a comma-delimited list of objects that are enclosed within brackets [].Note that the objects

can be of diﬀerent 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.

in:a[0]

out:1

int:a[4][2]

out:4

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 eﬀect 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.

2

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

in:copy.deepcopy(a)

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

1

:y

1

,...,x

n

:y

n

},where x

i

is a hashable

object,called the key,and y

i

is called the value associated with the key.For example,

in:d = {’a’:1,’b’:2,’c’:3}

in:d[’a’]

out:1

in:d.keys()

out:[’a’,’b’,’c’]

in:d.values()

out:[1,2,3]

in:d.items()

out:[(’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

a.read() 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

3

Modules.A module is a resource (usually a ﬁle with a.py 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

/home/tebert/551_book/source

The following steps are taken.

in:import sys

in:sys.path.append(’/home/tebert/551_book/source’)

Control Flow.//if blocks

if statement:

commands

elif:

commands

else:

commands

for loops

for var in set:

commands

else:

commands

while loops

while condition:

commands

else:

commands

4

functions

def name(args):

commands

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

else:

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.

in:min()

out:1

in:min(x=7)

out:2

in:min(x=5,y=8)

out:3

When using the for loop,the range() function proves useful.Its syntax is very similar to the slice operator:

range(start:stop:step)

5

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 deﬁned above yields the following.

in:map(min,[(1,2,3),(5,3,4),(7,9,4)])

out:[1,3,4]

Another useful function is filter() whose ﬁrst 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.

in:filter(isalpha,[’1’,’a’,’B’,’&’,’m’])

out:[’a’,’B’,’m’]

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 ﬁrst one hundred positive perfect squares.

6

Deﬁning Python Classes.The syntax for deﬁning a Python class is

class classname(superclass)

def __init__(self,args):

def functionname(self,args):

Example 4.Deﬁne 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)

in:p1.distance(p2)

out:1

7

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=ﬂoat),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

8

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 deﬁned as a random permutation of

the rows (columns) of a.

Example 6.Deﬁne 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.Deﬁne a 12×3 matrix a,and deﬁne 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.

9

Example 8.Show that,when ﬁrst 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

(x−y)

2

3

.

10

## Comments 0

Log in to post a comment