# Python

## History

• python is a 5th generation language created by Guido van Rossum in the 90's.
• Python became popular for scientific computing around 2000.
• a interpretted language that was more flexible and freer than Matlab and more fun to write than C and Fortran.
• A large collection of modules for various tasks
• A useful set of built-in data types (lists, dicts, strings)
• Being able to easily return multiple results from a function (unlike C)
• At that time, however, python lacked the right powertools for working with matrices. That was fixed with the release of numpy in 2006.

## References

### Python's interpretter

To get a python shell running int the terminal, use the command

$python (I'm using the "$" symbol to represent the regular shell prompt -- don't type it, just the "python")

Like any command-line shell, python's interpretter evaluates instructions you enter at the >>> prompt. In this case, the instructions expressed in the python language. Type the following commands into the python prompt and observe the results.

First, python does simple arithmetic like a calculator...

>>> 2+3
>>> 2*3
>>> 2**3
>>> 7^2

Note that ** is used for exponentiation in python, while ^ is used for bit-wise negation (a boolean operation -- if you don't know what it is, do not worry, you do not need to know).

Python uses variables to store things in memory.

>>> x = 13
>>> y = x - 5
>>> print y

Here, we have also introduced the command print, which is one of about 30 reserved words that makes up the python language. Really, it's true, the whole language has only 30 words! Here is a slightly more complicated example of how pring can be used with strings and inputs.

>>> print "Hello, World"
>>> name = raw_input("What is your name? ")
>>> print "Hello, %s.  Nice to meet you."%name

In the two cases above, x, y, and name are "variables". Variables in pythong are "dynamically typed", which means they can store many different things, and you just have to remember what kinds of things those are. Python has a few basic variable types built in, and a simple class system for creating more of your own.

• Python has lists for sequences of objects

>>> a_list = range(7)
>>> a_list
>>> a_list[0]
>>> a_list[1]
>>> a_list[-1]
>>> a_list[1:3]
• Python has dictionaries (called dict's) for paing items.

>>> a_dict = dict()
>>> a_dict['red'] = 'apple'
>>> a_dict['blue'] = 'sky'
>>> a_dict['red']
• Integers are different from floating-point numbers!

>>> u = 3
>>> v = 3.
>>> type(u)
>>> type(v)
>>> u/2
>>> v/2
• You can also format how things are output using the "print" command.

>>> print "the number %d is only one number"%u

"print" works allot like "printf" in C. "print" is especially useful because it always outputs, even when you are not interactively using the interpretter.

### Getting help

One of the big improvements of python over preceeding languages was the use of in-line documentation of code. This can be accessed in two easy ways.

1. From the standard terminal shell, documentation can be found using the command pydoc.

$pydoc topics list$ pydoc keywords if
$pydoc time 2. Inside the python interpretter, documentation on functions and variable types can be found using the function help(). >>> help(range) >>> x = 3 >>> help(x) These commands are your friends. Use them early and often. ### Better python tools - ipython and Canopy In practice, people don't use "python" for interactive work -- just to run their programs. If you put a bunch of python commands in a file "mycmds.py" and do $ python mycmds.py

those commands will be run, and you'll see any outputs from print commands.

For interactive work, we usually use a tool with more bells and whistles. The most commonly used interprettor for interactive work is ipython. It colorizes input, tracks input and output for future reference, allows customization, and a bunch of other useful things. (Ipython uses a different prompt from ">>>". I'll keep using ">>>" from here on, just to signify python input, but you can type the commands into any python interprettor).

Recently, Enthought has pulled together a nice GUI called Canopy for interactive scientific computing with python. Canopy is free to students at university like you, and is what we'll mostly use.

Because it is tedious to write out lengthy instructions every time you want to program a task, we usually save our commands to a file called a "script". Below is a simple program that prints a table for converting between Celcius and Farenheit.

1. Open up "Canopy" (it's a little slow sometimes - be patient).

2. Go to an "Editor" window. There will be several sub-windows. On the left is a file browser. On the top is an editor window. On the bottom is a command line interprettor window. Up top there is a button to "run" your code.

3. Enter the following code into the editor window. This is what we call a script.

print '------------------'
C = -20
dC = 5
while C <= 40:
F = (9.0/5)*C + 32
print C, F
C = C + dC
print '------------------'

1. Save your new script as "c2f.py". Be sure to keep track of which directory you are saving it to.

2. Make a prediction about what you think will happen when you run this script.

3. Click the "run" button to run the script. Does the output match your predictions?

4. You can also run your script from the terminal without having to use Canopy. In a new terminal window, "cd" to the directory where you saved "c2f.py" and do

\$ python c2f.py

The output you get should be the same as what you saw in Canopy.

5. Switch back to Canopy.

In most modern computer languages, functions are used regularly. A function in python is a piece of code that takes 1 or more arguments, and returns 1 or more results. Functions begin with the keyword def and finish with the keyword return followed by whichever variables you want to return. Try the following script, which I call "c2fv2.py"

def CtoCF(C):
F = (9.0/5)*C + 32
return C, F

print '------------------'
C = -20
dC = 5
while C <= 40:
print CtoCF(C)
C = C + dC
print '------------------'

## Background

• In python, libraries of useful functions are called "modules". You can load a module into your python interpretter or shell script with the command "import", like...

>>> import math

You can use help to see the contents of the module you have imported.

>>> help(math)

To use one of the functions from the module, you put the modules name as a prefix, like

>>> math.exp(0.)

Import submodules the same way, but with a "." used to separate names.

>>> import scipy.integrate

Function names can also be imported directly into the working namespace, although this can be dangerous and is discouraged.

>>> from math import exp
>>> exp(0.), exp(1.)
• Python calls vectors and matrices "arrays", You can create a vector with "array([1.,2.,3.])", and a matrix with "array([[1,2],[-2,3]])".

• Matrix multiplication with arrays works a little different than you might expect. If A is an array and you type "A*A", this does element-wise multiplication (known as the Haddamard or Matlab product). To do a matrix product, youhave to use "A.dot(A)".

• Variables can point to generic objects, be they integers, floats, strings, list, or even functions. This last case is particular useful as it allows us to create and pass functions around to other functions. "def" is the usual way to create functions (see above), but for short functions, there's a sweet trick called lambda-forms, in honor of Alonzo Church's Lambda calculus.

>>> f = lambda x : x**2
>>> f(1)
>>> f(2)
>>> map(f, range(10))
• _ for last output

## Pre-packaged numerical methods

So, we human beings have been doing calculations for a while now, and have developed some good algorithms to answer a variety of useful questions. Fortunately, we can take advantage of all of this hard work without having to recreate the wheel ourselves. In this section, you'll get a taste for answering some common math questions with python, scipy, numpy, and sympy.

Record your answers to these questions as you go, LaTex them up, and send them to me in a PDF file before Friday. Remember to include a header with name and date.

1. Find all the roots of the cubic polynomial equation x**3 - 10x**2 + 31x - 30 = 0 using the function "numpy.roots()"

2. Find the uniq solution of the system of linear equations 10 = 11 x - 5 y, -16 = 3 x - 7 y - 6 z, -12 = 14 x - 6 y + 3 z by converting the equations to matrix-vector form and using "solve()"

3. Find the uniq solution of the transcendental equation exp(x) + 2 x = 0 using the bisection algorithm in "scipy.optimize.bisect()" and "scipy.optimize.ridder()" (note that they give slightly different answers).

4. Find the global minimum of the function f(x) = exp(2 x) - 3 x using "scipy.optimize.golden". Use calculus to check the solution.

5. Find the area under the curve 2 + sin(sin(x)+x) over the interval [0,10] using "scipy.integrate.quadrature".

6. Find the slope and y-intercept of line that minimizes the square error of going through the four points (0,0), (9,9), (5,7), (6,5) by setting up the matrix system and using "numpy.linalg.lstsq". Store your answers in "m" and "b" respectively.

## Plotting

Python also has a useful set of plotting tools. For a simple example, let's plot your solution to the least-squares problem, allong with the data. (use the m and b we stored above.)

>>> x = linspace(0,10,100)
>>> y = m*x + b
>>> x_data = [0,9,5,6]
>>> y_data = [0,9,7,5]
>>> plot(x_data, y_data, 'ro', x, y, 'k-')

Then add title, x label, and y label to your plot. Save your figure to a jpeg image file with the "savefig" command.