Transcription

Introduction to PythonHeavily based on presentations byMatt Huenerfauth (Penn State)Guido van Rossum (Google)Richard P. Muller (Caltech).Monday, October 19, 2009

Python Open source general-purpose language.Object Oriented, Procedural, FunctionalEasy to interface with C/ObjC/Java/FortranEasy-ish to interface with C (via SWIG)Great interactive environment Downloads: http://www.python.org Documentation: http://www.python.org/doc/ Free book: http://www.diveintopython.orgMonday, October 19, 2009

2.5.x / 2.6.x / 3.x ? “Current” version is 2.6.x “Mainstream” version is 2.5.x The new kid on the block is 3.xYou probably want 2.5.x unless you are starting fromscratch. Then maybe 3.xMonday, October 19, 2009

Technical IssuesInstalling & Running PythonMonday, October 19, 2009

Binaries Python comes pre-installed with Mac OS X andLinux. Windows binaries from http://python.org/ You might not have to do anything!Monday, October 19, 2009

The Python Interpreter Interactive interface to Python% pythonPython 2.5 (r25:51908, May 25 2007, 16:14:04)[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2Type "help", "copyright", "credits" or "license" for more information. Python interpreter evaluates inputs: 3*(7 2)27 Python prompts with ‘ ’. To exit Python: CTRL-DMonday, October 19, 2009

Running Programs on UNIX% python filename.pyYou could make the *.py file executable and add thefollowing #!/usr/bin/env python to the top to make itrunnable.Monday, October 19, 2009

Batteries Included Large collection of proven modules included in thestandard onday, October 19, 2009

numpy Offers Matlab-ish capabilities within Python Fast array operations 2D arrays, multi-D arrays, linear algebra etc. Downloads: http://numpy.scipy.org/ Tutorial: http://www.scipy.org/Tentative NumPy TutorialMonday, October 19, 2009

matplotlib High quality plotting library.#!/usr/bin/env pythonimport numpy as npimport matplotlib.mlab as mlabimport matplotlib.pyplot as pltmu, sigma 100, 15x mu sigma*np.random.randn(10000)# the histogram of the datan, bins, patches plt.hist(x, 50, normed 1, facecolor 'green',alpha 0.75)# add a 'best fit' liney mlab.normpdf( bins, mu, sigma)l plt.plot(bins, y, 'r--', linewidth .title(r' \mathrm{Histogram\ of\ IQ:}\ \mu 100,\ \sigma 15 ')plt.axis([40, 160, 0, 0.03])plt.grid(True)plt.show() Downloads: http://matplotlib.sourceforge.net/Monday, October 19, 2009

PyFITS FITS I/O made simple: import pyfits hdulist pyfits.open(’input.fits’) hdulist.info()Filename: test1.fitsNo. Name Type Cards Dimensions Format0 PRIMARY PrimaryHDU 220 () Int161 SCI ImageHDU 61 (800, 800) Float322 SCI ImageHDU 61 (800, 800) Float323 SCI ImageHDU 61 (800, 800) Float324 SCI ImageHDU 61 (800, 800) Float32 hdulist[0].header[’targname’]’NGC121’ scidata hdulist[1].data scidata.shape(800, 800) scidata.dtype.name ’float32’ scidata[30:40,10:20] scidata[1,4] 999 Downloads: http://www.stsci.edu/resources/software hardware/pyfitsMonday, October 19, 2009

pyds9 / python-sao Interaction with DS9 Display Python 1-D and 2-D arrays in DS9 Display FITS files in DS9 Downloads: Ask Eric Mandel :-) Downloads: http://code.google.com/p/python-sao/Monday, October 19, 2009

Wrappers for Astronomical Packages CasaPy (Casa)PYGILDAS (GILDAS)ParselTongue (AIPS)PyRAF (IRAF)PyMIDAS (MIDAS)PyIMSL (IMSL)Monday, October 19, 2009

Custom Distributions Python(x,y): http://www.pythonxy.com/ Python(x,y) is a free scientific and engineering developmentsoftware for numerical computations, data analysis and datavisualization Sage: http://www.sagemath.org/ Sage is a free open-source mathematics software systemlicensed under the GPL. It combines the power of many existingopen-source packages into a common Python-based interface.Monday, October 19, 2009

Extra Astronomy Links iPython (better shell, distributed computing):http://ipython.scipy.org/ SciPy (collection of science tools): http://www.scipy.org/ Python Astronomy Modules: http://astlib.sourceforge.net/ Python Astronomer Wiki: ?page python AstroPy: y.html Python for Astronomers: http://www.iac.es/sieinvens/siepedia/pmwiki.php?n HOWTOs.EmpezandoPythonMonday, October 19, 2009

The BasicsMonday, October 19, 2009

A Code Samplex 34 - 23# A comment.y “Hello”# Another one.z 3.45if z 3.45 or y “Hello”:x x 1y y “ World”print xprint yMonday, October 19, 2009# String concat.

Enough to Understand the Code Assignment uses and comparison uses . For numbers - * / % are as expected. Special use of for string concatenation. Special use of % for string formatting (as with printf in C) Logical operators are words (and, or, not)not symbols The basic printing command is print. The first assignment to a variable creates it. Variable types don’t need to be declared. Python figures out the variable types on its own.Monday, October 19, 2009

Basic Datatypes Integers (default for numbers)z 5 / 2# Answer is 2, integer division. Floatsx 3.456 Strings Can use “” or ‘’ to specify.“abc” ‘abc’ (Same thing.) Unmatched can occur within the string.“matt’s” Use triple double-quotes for multi-line strings or strings than contain both ‘and “ inside of them:“““a‘b“c”””Monday, October 19, 2009

WhitespaceWhitespace is meaningful in Python: especiallyindentation and placement of newlines. Use a newline to end a line of code. Use \ when must go to next line prematurely. No braces { } to mark blocks of code in Python Use consistent indentation instead. The first line with less indentation is outside of the block. The first line with more indentation starts a nested block Often a colon appears at the start of a new block.(E.g. for function and class definitions.)Monday, October 19, 2009

Comments Start comments with # – the rest of line is ignored. Can include a “documentation string” as the first line of anynew function or class that you define. The development environment, debugger, and other tools useit: it’s good style to include one.def my function(x, y):“““This is the docstring. Thisfunction does blah blah blah.”””# The code would go here.Monday, October 19, 2009

Assignment Binding a variable in Python means setting a name to hold areference to some object. Assignment creates references, not copies Names in Python do not have an intrinsic type. Objects havetypes. Python determines the type of the reference automatically based on thedata object assigned to it. You create a name the first time it appears on the left side ofan assignment expression:!x 3 A reference is deleted via garbage collection after any namesbound to it have passed out of scope.Monday, October 19, 2009

Accessing Non-Existent Names If you try to access a name before it’s been properly created(by placing it on the left side of an assignment), you’ll get anerror. yTraceback (most recent call last):File " pyshell#16 ", line 1, in -toplevelyNameError: name ‘y' is not defined y 3 y3Monday, October 19, 2009

Multiple Assignment You can also assign to multiple names at the same time. x, y 2, 3 x2 y3Monday, October 19, 2009

Naming Rules Names are case sensitive and cannot start with a number.They can contain letters, numbers, and underscores.bobBobbob2 bobbob 2BoB There are some reserved words:and, assert, break, class, continue, def, del, elif,else, except, exec, finally, for, from, global, if,import, in, is, lambda, not, or, pass, print, raise,return, try, whileMonday, October 19, 2009

Understanding Reference Semantics inPythonMonday, October 19, 2009

Understanding Reference Semantics Assignment manipulates references—x y does not make a copy of the object y references—x y makes x reference the object y references Very useful; but beware! Example: a [1, 2, 3] b a a.append(4) print b[1, 2, 3, 4]Why?Monday, October 19, 2009# a now references the list [1, 2, 3]# b now references what a references# this changes the list a references# if we print what b references,# SURPRISE! It has changed

Understanding Reference Semantics II There is a lot going on when we type: x 3First, an integer 3 is created and stored in memoryA name x is createdAn reference to the memory location storing the 3 is thenassigned to the name xSo: When we say that the value of x is 3we mean that x now refers to the integer 3Name: xRef: address1 Type: IntegerData: 3name listMonday, October 19, 2009memory

Understanding Reference Semantics III The data 3 we created is of type integer. In Python, thedatatypes integer, float, and string (and tuple) are“immutable.” This doesn’t mean we can’t change the value of x, i.e. changewhat x refers to For example, we could increment x: x 3 x x 1 print x4Monday, October 19, 2009

Understanding Reference Semantics IV If we increment x, then what’s really happening is:1. The reference of name x is looked up. x x 12. The value at that reference is retrieved.Name: xRef: address1 Monday, October 19, 2009Type: IntegerData: 3

Understanding Reference Semantics IV If we increment x, then what’s really happening is:1. The reference of name x is looked up. x x 12. The value at that reference is retrieved.3. The 3 1 calculation occurs, producing a new data element 4 which isassigned to a fresh memory location with a new reference.Name: xRef: address1 Type: IntegerData: 3Type: IntegerData: 4Monday, October 19, 2009

Understanding Reference Semantics IV If we increment x, then what’s really happening is:1. The reference of name x is looked up. x x 12. The value at that reference is retrieved.3. The 3 1 calculation occurs, producing a new data element 4 which isassigned to a fresh memory location with a new reference.4. The name x is changed to point to this new reference.Name: xRef: address1 Type: IntegerData: 3Type: IntegerData: 4Monday, October 19, 2009

Understanding Reference Semantics IV If we increment x, then what’s really happening is:1. The reference of name x is looked up. x x 12. The value at that reference is retrieved.3. The 3 1 calculation occurs, producing a new data element 4 which isassigned to a fresh memory location with a new reference.4. The name x is changed to point to this new reference.5. The old data 3 is garbage collected if no name still refers to it.Name: xRef: address1 Type: IntegerData: 4Monday, October 19, 2009

Assignment 1 So, for simple built-in datatypes (integers, floats, strings),assignment behaves as you would expect: 3Monday, October 19, 2009x 3y xy 4print x####Creates 3, nameCreates name y,Creates ref forNo effect on x,x refers to 3refers to 3.4. Changes y.still ref 3.

Assignment 1 So, for simple built-in datatypes (integers, floats, strings),assignment behaves as you would expect: 3x 3y xy 4print x####Creates 3, nameCreates name y,Creates ref forNo effect on x,Name: xRef: address1 Monday, October 19, 2009x refers to 3refers to 3.4. Changes y.still ref 3.Type: IntegerData: 3

Assignment 1 So, for simple built-in datatypes (integers, floats, strings),assignment behaves as you would expect: 3x 3y xy 4print x####Creates 3, nameCreates name y,Creates ref forNo effect on x,Name: xRef: address1 Name: yRef: address1 Monday, October 19, 2009x refers to 3refers to 3.4. Changes y.still ref 3.Type: IntegerData: 3

Assignment 1 So, for simple built-in datatypes (integers, floats, strings),assignment behaves as you would expect: 3x 3y xy 4print x####Creates 3, nameCreates name y,Creates ref forNo effect on x,Name: xRef: address1 Name: yRef: address1 Monday, October 19, 2009x refers to 3refers to 3.4. Changes y.still ref 3.Type: IntegerData: 3Type: IntegerData: 4

Assignment 1 So, for simple built-in datatypes (integers, floats, strings),assignment behaves as you would expect: 3x 3y xy 4print x####Creates 3, nameCreates name y,Creates ref forNo effect on x,Name: xRef: address1 Name: yRef: address2 Monday, October 19, 2009x refers to 3refers to 3.4. Changes y.still ref 3.Type: IntegerData: 3Type: IntegerData: 4

Assignment 1 So, for simple built-in datatypes (integers, floats, strings),assignment behaves as you would expect: 3x 3y xy 4print x####Creates 3, nameCreates name y,Creates ref forNo effect on x,Name: xRef: address1 Name: yRef: address2 Monday, October 19, 2009x refers to 3refers to 3.4. Changes y.still ref 3.Type: IntegerData: 3Type: IntegerData: 4

Assignment 2 For other data types (lists, dictionaries, user-defined types), assignmentworks differently. These datatypes are “mutable.”When we change these data, we do it in place.We don’t copy them into a new memory address each time.If we type y x and then modify y, both x and y are changed.immutable 3x 3y xy 4print xMonday, October 19, 2009mutablex some mutable objecty xmake a change to ylook at xx will be changed as well

Why? Changing a Shared Lista [1, 2, 3]a123123123 4ab abaa.append(4)bMonday, October 19, 2009

Our surprising example surprising no more. So now, here’s our code: a [1, 2, 3] b a a.append(4) print b[1, 2, 3, 4]Monday, October 19, 2009# a now references the list [1, 2, 3]# b now references what a references# this changes the list a references# if we print what b references,# SURPRISE! It has changed

Sequence types:Tuples, Lists, and StringsMonday, October 19, 2009

Sequence Types1. Tuple A simple immutable ordered sequence of items Items can be of mixed types, including collection types2. Strings Immutable Conceptually very much li