Python Pres
Python Pres
Python Pres
computing
Steve Byrnes
16 March 2012
Terminology
• Python is a general-purpose programming language
– From NASA to YouTube…
• Python “package”/ “module” / “library” is what you
download (or write) to get additional functions and
definitions. Examples:
– NumPy for fast array computations and manipulations and
linear algebra.
– SciPy for optimization, image-processing, interpolation,
numerical integration, etc.
– Matplotlib for making graphs.
• “Python distribution” is a way to download Python and
various packages, either a la carte or all at once.
– There’s a standard one, “Cpython”, at python.org. Others
include EnThought, SAGE, Python(x,y), PortablePython, …
Terminology
• “Python 2” and “Python 3” are different versions,
not compatible with each other. NumPy only
exists in Python 2 [so far], so use that.
• “Integrated development environment” (IDE) is a
program for writing programs: Text-editor,
debugger, etc.
– e.g. “Spyder”
– Python IDEs are often, themselves, written in Python,
i.e. they are Python packages.
Spyder, an IDE
Installation
• As with everything open-
source, installation is one of
the most confusing parts for
beginners (at least, it was
for me.)
• http://sjbyrnes.com/?page_
id=67
• Watch out Mac OS X users:
NumPy is incompatible with
your built-in Python.
Nice things about Python (vs MATLAB)
• Lots of little things…
– You don’t have to end every command with a
semicolon
– If you want to write a function, it doesn’t need to
be in its own file, where the filename is the same
as the function name.
– etc. etc.…
• Free
Nice things about Python (vs MATLAB)
• MATLAB becomes increasingly useless as you get
farther away from matrices. Python is equally
good at everything.
– Someday maybe I’ll want to…
• turn something into a stand-alone program with a GUI
• pull data out of a pdf
• interface with hardware and instruments
• draw a 3D picture
• write a script to reorganize files on my computer
• put some interactive feature on my website
• …
– Python always has a professional-quality module for
it!
NumPy
In: myfunction1(10)
Out: 15
In: myfunction2(10)
Out: 16
In: from numpy import * In: import numpy In: import numpy as np
In Spyder, “from numpy import *” is run automatically every time you open
the program. So you can use cos, pi, etc., in the console. But inside a module, you
still have to import these functions yourself.
Modules
• The functions you usually want for plotting are
in the module matplotlib.pyplot [a
“submodule” of matplotlib]. Again, in the Spyder console,
In: from matplotlib.pyplot import * you don’t need the first line,
because Spyder runs it
In: plot([1,2,4]) automatically every time you
open the program.
In the file 4
testscript.py…
In: run testscript.py
a += 1
5
print a
In: run testscript.py
6
NumPy arrays versus Python lists
• Python lists: Very general
– a = [1,2]
– b = [[1,2],[3,4]]
– c = [[1,2, ’duh’],[3,[4]]]
• NumPy arrays:
– x = array([1,2])
– y = array([[1,2],[3,4]])
– All rows must have same length, etc.
– All entries must have same data-type, e.g. all real or all complex.
• Always use NumPy arrays when you’re doing something with
the data:
– Math – Matrix addition, dot-product, conjugation…
– Manipulating elements of the array – Reshaping, rearranging,
combining, pulling out a sub-array, etc.
Warning: Integer division
In: 7/3 Integer division is rounded down (towards
Out: 2
negative infinity).
In: 7./3
Out: 2.3333333
This unfortunate default gets fixed in Python 3.
In: 7/3. In the meantime, start every module and
Out: 2.3333333 console session with:
In: a In: a
Out: array([[100,2],[3,4]]) Out: array([[1,2],[3,4]])
Warning: Arrays in functions
FIXED
def messwitharray(a):
a[0] = 57 def messwitharray(a_temp):
return a[1]+a[2] a = a_temp.copy()
a[0] = 57
In: a = array([1,2,3]) return a[1]+a[2]
In: a
Out: array([57,2,3]) The behavior makes sense if you think of
“a” as NOT a list of numbers but INSTEAD
Solution: Put a2=a.copy() at as a description of where I should look, in
the start of the function, then the computer’s RAM, to find a certain list
you can freely mess around with of numbers.
a2.
When in doubt, copy()!!
#define an array
a = array([[1,2],[3,4],[5,6]])
#run a function
d = f(b.copy(), c.copy())
import numpy as np
My favorite: Return a
def polar(z): “Python dictionary”. Code
phi = np.angle(z) is easier to understand
abs_val = abs(z) and less prone to error.
return {’angle’:phi, ’abs’:abs_val}
[Even fancier options:
results = polar(4+8j)
t = results[’angle’] Return an “object” in a
r = results[’abs’] custom “class”; return a
“named tuple”]
Python programming: if
Python programming: for, range