Eberly College of Science Mathematics Department, Center for Interdisciplinary Mathematics
REU banner




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.

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.

Writting your first script

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.

Writting your first function

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 '------------------'


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.


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.