Starting
Starting
Starting
Agenda
Introduction
Running Python
Python Programming
Data types
Control flows
Classes, functions, modules
Hands-on Exercises
Course Goals
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
Python vs. Java
Introduction
Running Python
Python Programming
Data types
Control flows
Classes, functions, modules
Hands-on Exercises
$ python
>>> execfile('script.py')
>>> x
[0,1,2]
Running Python Programs
Interactively
Suppose the file script.py 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]
Running Python Programs
Interactively
# Pretend that script.py 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 script.py 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 script.py into the terminal.
>>> from script import *
File naming conventions
Introduction
Running Python
Python Programming
Data types
Control flows
Classes, functions, modules
Hands-on Exercises
Strings
characters are strings of length 1
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
Reference semantics
+ - * / % (like C)
+= -= etc. (no ++ or --)
Assignment using =
but semantics are different!
a = 1
a = "foo" # OK
Can also use + to concatenate strings
Strings
"hello"+"world" "helloworld" # concatenation
"hello"*3 "hellohellohello" # repetition
"hello"[0] "h" # indexing
"hello"[-1] "o" # (from end)
"hello"[1:4] "ell" # slicing
len("hello") 5 # size
"hello" < "jello" 1 # comparison
"e" in "hello" 1 # search
New line: "escapes: \n "
Line continuation: triple quotes ’’’
Quotes: ‘single quotes’, "raw strings"
Simple Data Types
class Thingy:
"""This class stores an arbitrary object."""
def __init__(self, value):
constructor
"""Initialize a Thingy."""
self.value = value
method
def showme(self):
"""Print this object to stdout."""
print "value = %s" % self.value
Using a class (1)
t = Thingy(10) # calls __init__ method
while loops
a = 10
while a > 0:
print a
a -= 1
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]
Control flow (6)
Common while loop idiom:
f = open(filename, "r")
while True:
line = f.readline()
if not line:
break
# do something with line
Control flow (7): odds & ends
if a == 0:
pass # do nothing
else:
# whatever
Defining functions
def foo(x):
y = 10 * x + 2
return y
All variables are local unless
specified as global
Arguments passed by value
Executing functions
def foo(x):
y = 10 * x + 2
return y
import module
module.function()
Modules are namespaces
Can be used to organize variable names, i.e.
atom.position = atom.position - molecule.position
Modules
Access other code by importing modules
import math
print math.sqrt(2.0)
or:
from math import sqrt
print sqrt(2.0)
Modules
or:
from math import *
print sqrt(2.0)
[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.]]
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()
Eigenvalues
>>> from LinearAlgebra import *
>>> val = eigenvalues(c)
>>> val, vec = eigenvectors(c)
>>> print val
[1., 4., 1.]
>>> print vec
[[0.816, -0.408, -0.408],
[0.575, 0.577, 0.577],
[-0.324, -0.487, 0.811]]
also solve_linear_equations, singular_value_decomposition, etc.
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):
data.append((i,i*i))
>>> guess = (3,2,1)
>>> fit_params, fit_error =
leastSquaresFit(func,guess,data)
>>> print fit_params
[1.00,0.000,0.00]
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:
http://docs.python.org/library/
http://its2.unc.edu/dci/dci_components/shared_apps/packages/python_pa
ckages.html
http://pypi.python.org/pypi/
Command-line arguments
import sys
print len(sys.argv) # NOT argc
# Print all arguments:
print sys.argv
# Print all arguments but the program
# or module name:
print sys.argv[1:] # "array slice"
Catching Exceptions
#python code a.py
x = 0
try:
print 1/x
except ZeroDivisionError, message:
print "Can’t divide by zero:"
print message
>>>python a.py
Can't divide by zero:
integer division or modulo by zero
Try-Finally: Cleanup
f = open(file)
try:
process_file(f)
finally:
f.close() # always executed
print "OK" # executed on success only
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
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
References
Python Homepage
• http://www.python.org
Python Tutorial
• http://docs.python.org/tutorial/
Python Documentation
• http://www.python.org/doc
Python Library References
http://docs.python.org/release/2.5.2/lib/lib.html
Python Add-on Packages:
http://pypi.python.org/pypi
Questions & Comments
Please direct comments/questions about research computing to
E-mail: [email protected]
Please direct comments/questions pertaining to this presentation to
E-Mail: [email protected]