Introduction to Python Programming
Introduction
Running Python
Python Programming
• Data types
• Control flows
• Classes, functions, modules
Hands-on Exercises
The PPT/WORD format of this presentation is available here:
[Link]
/afs/isis/depts/its/public_html/divisions/rc/training/scientific/short_courses/
[Link] 2
Course Goals
[Link] 3
What is python?
[Link] 4
Timeline
[Link] 5
Language properties
Everything is an object
Modules, classes, functions
Exception handling
Dynamic typing, polymorphism
Static scoping
Operator overloading
Indentation for block structure
[Link] 6
High-level data types
[Link] 7
Why learn python?
[Link] 8
Why learn python? (cont.)
[Link] 9
Where to use python?
• Easier to learn
important for occasional users
• More readable code
improved code maintenance
• Fewer “magical” side effects
• More “safety” guarantees
• Better Java integration
• Less Unix bias
[Link] 11
Python vs. Java
Introduction
Running Python
Python Programming
• Data types
• Control flows
• Classes, functions, modules
Hands-on Exercises
The PPT/WORD format of this presentation is available here:
[Link]
/afs/isis/depts/its/public_html/divisions/rc/training/scientific/short_courses/
[Link] 13
Running Python Interactively
Start python by typing "python"
• /afs/isis/pkg/isis/bin/python
^D (control-D) exits
% python
>>> ^D
%
Comments start with ‘#’
>>> 2+2 #Comment on the same line as text
4
>>> 7/3 #Numbers are integers by default
2
>>> x = y = z = 0 #Multiple assigns at once
>>> z
0
[Link] 14
Running Python Programs
In general
% python ./[Link]
Can also create executable scripts
• Compose the code in an editor like vi/emacs
% vi ./[Link] # Python scripts with the suffix .py.
• Then you can just type the script name to execute
% python ./[Link]
The first line of the program tells the OS how to execute it:
#! /afs/isis/pkg/isis/bin/python
• Make the file executable:
% chmod +x ./[Link]
• Then you can just type the script name to execute
% ./[Link]
[Link] 15
Running Python Programs
Interactively
Suppose the file [Link] contains the following lines:
print 'Hello world'
x = [0,1,2]
Let's run this script in each of the ways described on the last slide:
python -i [Link]
Hello world
>>> x
[0,1,2]
$ python
>>> execfile('[Link]')
>>> x
[0,1,2]
[Link] 16
Running Python Programs
Interactively
Suppose the file [Link] contains the following lines:
print 'Hello world'
x = [0,1,2]
Let's run this script in each of the ways described on the last slide:
python
>>> import script # DO NOT add the .py suffix. Script is a module here
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
>>> script.x # to make use of x, we need to let Python know which
#module it came from, i.e. give Python its context
[0,1,2]
[Link] 17
Running Python Programs
Interactively
# Pretend that [Link] contains multiple stored quantities. To promote
x(and only x) to the top level context, type the following:
$ python
>>> from script import x
Hello world
>>> x
[0,1,2]
>>>
# To promote all quantities in [Link] to the top level context, type
from script import * into the interpreter. Of course, if that's what
you want, you might as well type python -i [Link] into the
terminal.
>>> from script import *
[Link] 18
File naming conventions
[Link] 19
Comments
[Link] 20
Agenda
Introduction
Running Python
Python Programming
• Data types
• Control flows
• Classes, functions, modules
Hands-on Exercises
The PPT/WORD format of this presentation is available here:
[Link]
/afs/isis/depts/its/public_html/divisions/rc/training/scientific/short_courses/
[Link] 21
Python Syntax
[Link] 22
Simple data types
Numbers
• Integer, floating-point, complex!
Strings
• characters are strings of length 1
[Link] 23
Numbers
[Link] 24
Strings and formatting
i = 10
d = 3.1415926
s = "I am a string!"
print “newline\n"
No need to declare
Need to assign (initialize)
use of uninitialized variable raises exception
Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
print greeting
Everything is a variable:
functions, modules, classes
[Link] 26
Reference semantics
[Link] 27
Simple data types:
operators
+ - * / % (like C)
+= -= etc. (no ++ or --)
Assignment using =
• but semantics are different!
a = 1
a = "foo" # OK
Can also use + to concatenate strings
[Link] 28
Strings
[Link] 29
Simple Data Types
[Link] 30
Methods in string
[Link] 31
Compound Data Type: List
List:
• A container that holds a number of other objects,
in a given order
• Defined in square brackets
a = [1, 2, 3, 4, 5]
print a[1] # number 2
some_list = []
some_list.append("foo")
some_list.append(12)
print len(some_list) # 2
[Link] 32
List
[Link] 33
More list operations
[Link] 34
Operations in List
[Link] 35
Nested List
List in a list
E.g.,
• >>> s = [1,2,3]
• >>> t = [‘begin’, s, ‘end’]
• >>> t
• [‘begin’, [1, 2, 3], ‘end’]
• >>> t[1][1]
•2
[Link] 36
Dictionaries
Dictionaries: curly brackets
• What is dictionary?
Refer value through key; “associative arrays”
• Like an array indexed by a string
• An unordered set of key: value pairs
• Values of any type; keys of almost any type
{"name":"Guido", "age":43, ("hello","world"):1,
42:"yes", "flag": ["red","white","blue"]}
d = { "foo" : 1, "bar" : 2 }
print d["bar"] # 2
some_dict = {}
some_dict["foo"] = "yow!"
print some_dict.keys() # ["foo"]
[Link] 37
Methods in Dictionary
keys()
values()
items()
has_key(key)
clear()
copy()
get(key[,x])
setdefault(key[,x])
update(D)
popitem()
[Link] 38
Dictionary details
[Link] 39
Tuples
What is a tuple?
• A tuple is an ordered collection which cannot
be modified once it has been created.
• In other words, it's a special array, a read-only array.
How to make a tuple? In round brackets
• E.g.,
>>> t = ()
>>> t = (1, 2, 3)
>>> t = (1, )
>>> t = 1,
>>> a = (1, 2, 3, 4, 5)
>>> print a[1] # 2
[Link] 40
Operations in Tuple
[Link] 41
List vs. Tuple
[Link] 43
Data Type Wrap Up
[Link] 44
Input
[Link] 45
File I/O
f = file("foo", "r")
line = [Link]()
print line,
[Link]()
# Can use [Link] as input;
# Can use [Link] as output.
[Link] 46
Files: Input
[Link] 47
Files: Output
[Link] 48
open() and file()
[Link] 49
OOP Terminology
[Link] 51
Defining a class
class Thingy:
[Link] = value
method
def showme(self):
[Link] 52
Using a class (1)
[Link] 53
Using a class (2)
[Link] 54
"Special" methods
[Link] 55
Control flow (1)
if, if/else, if/elif/else
if a == 0:
print "zero!"
elif a < 0:
print "negative!"
else:
print "positive!"
Notes:
• blocks delimited by indentation!
while loops
a = 10
while a > 0:
print a
a -= 1
[Link] 57
Control flow (4)
for loops
for a in range(10):
print a
a = [3, 1, 4, 1, 5, 9]
for i in range(len(a)):
print a[i]
[Link] 59
Control flow (6)
[Link] 60
Control flow (7): odds &
ends
def foo(x):
y = 10 * x + 2
return y
All variables are local unless
specified as global
Arguments passed by value
[Link] 62
Executing functions
def foo(x):
y = 10 * x + 2
return y
[Link] 63
Why use modules?
Code reuse
• Routines can be called multiple times within a
program
• Routines can be used from multiple programs
Namespace partitioning
• Group data together with functions used for that
data
Implementing shared services or data
• Can provide global data structure that is accessed by
multiple subprograms
[Link] 64
Modules
Modules are functions and variables defined in separate files
Items are imported using from or import
from module import function
function()
import module
[Link]()
Modules are namespaces
• Can be used to organize variable names, i.e.
[Link] = [Link] - [Link]
[Link] 65
Modules
print [Link](2.0)
or:
from math import sqrt
print sqrt(2.0)
[Link] 66
Modules
or:
from math import *
print sqrt(2.0)
[Link] 67
Example: NumPy Modules
[Link]
NumPy has many of the features of Matlab, in a free, multiplatform
program. It also allows you to do intensive computing operations in a simple
way
Numeric Module: Array Constructors
• ones, zeros, identity
• arrayrange
LinearAlgebra Module: Solvers
• Singular Value Decomposition
• Eigenvalue, Eigenvector
• Inverse
• Determinant
• Linear System Solver
[Link] 68
Arrays and Constructors
>>> a = ones((3,3),float)
>>> print a
[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]
>>> b = zeros((3,3),float)
>>> b = b + 2.*identity(3) #"+" is overloaded
>>> c = a + b
>>> print c
[[3., 1., 1.],
[1., 3., 1.],
[1., 1., 3.]]
[Link] 69
Overloaded operators
>>> b = 2.*ones((2,2),float) #overloaded
>>> print b
[[2.,2.],
[2.,2.]]
>>> b = b+1 # Addition of a scalar is
>>> print b # element-by-element
[[3.,3.],
[3.,3.]]
>>> c = 2.*b # Multiplication by a scalar is
>>> print c # element-by-element
[[6.,6.],
[6.,6.]]
[Link] 70
Array functions
>>> from LinearAlgebra import *
>>> a = zeros((3,3),float) + 2.*identity(3)
>>> print inverse(a)
[[0.5, 0., 0.],
[0., 0.5, 0.],
[0., 0., 0.5]]
>>> print determinant(inverse(a))
0.125
>>> print diagonal(a)
[0.5,0.5,0.5]
>>> print diagonal(a,1)
[0.,0.]
• transpose(a), argsort(), dot()
[Link] 71
Eigenvalues
[Link] 72
Least Squares Fitting
Part of Hinsen's Scientific Python module
>>> from LeastSquares import *
>>> def func(params,x): # y=ax^2+bx+c
return params[0]*x*x + params[1]*x +
params[2]
>>> data = []
>>> for i in range(10):
[Link]((i,i*i))
>>> guess = (3,2,1)
>>> fit_params, fit_error =
leastSquaresFit(func,guess,data)
>>> print fit_params
[1.00,0.000,0.00]
[Link] 73
FFT
>>> from FFT import *
>>> data = array((1,0,1,0,1,0,1,0))
>>> print fft(data).real
[4., 0., 0., 0., 4., 0., 0., 0.]]
Also note that the FFTW package ("fastest Fourier transform in the
West") has a python wrapper. See notes at the end
Python Standard Libraries/Modules:
• [Link]
• [Link]
python_packages.html
• [Link]
[Link] 74
Command-line arguments
import sys
print len([Link]) # NOT argc
# Print all arguments:
print [Link]
# Print all arguments but the program
# or module name:
print [Link][1:] # "array slice"
[Link] 75
Catching Exceptions
#python code [Link]
x = 0
try:
print 1/x
except ZeroDivisionError, message:
print "Can’t divide by zero:"
print message
>>>python [Link]
Can't divide by zero:
integer division or modulo by zero
[Link] 76
Try-Finally: Cleanup
f = open(file)
try:
process_file(f)
finally:
[Link]() # always executed
print "OK" # executed on success only
[Link] 77
Raising Exceptions
raise IndexError
raise IndexError("k out of range")
raise IndexError, "k out of range”
try:
something
except: # catch everything
print "Oops"
raise # reraise
[Link] 78
Python: Pros & Cons
Pros
• Free availability (like Perl, Python is open source).
• Stability (Python is in release 2.6 at this point and, as I noted earlier, is older
than Java).
• Very easy to learn and use
• Good support for objects, modules, and other reusability mechanisms.
• Easy integration with and extensibility using C and Java.
Cons
• Smaller pool of Python developers compared to other languages, such as Java
• Lack of true multiprocessor support
• Absence of a commercial support point, even for an Open Source project
(though this situation is changing)
• Software performance slow, not suitable for high performance applications
[Link] 79
References
• Python Homepage
• [Link]
• Python Tutorial
• [Link]
• Python Documentation
• [Link]
• Python Library References
[Link]
• Python Add-on Packages:
[Link]
[Link] 80
Questions & Comments
Please
Pleasedirect
directcomments/questions
comments/questionsabout
aboutresearch
researchcomputing
computingtoto
E-mail:
E-mail:research@[Link]
research@[Link]
Please
Pleasedirect
directcomments/questions
comments/questionspertaining
pertainingtotothis
thispresentation
presentationtoto
E-Mail:
E-Mail:shubin@[Link]
shubin@[Link]
[Link]
Hands-On Exercises
26 codes at /netscr/training/Python
Copy to your own /netscr/$USER
Read, understand, and then run them
Suggested order:
• hello, input, print, readwrite
• number, string_test, sort
• list, dictionary, tuple, function, class
• loop, fact, …
• calculator, guess, prime_number
• matrix, opt, leastsq









