To get a python shell running int the terminal, use the command
(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
** 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 "Hello, World" >>> name = raw_input("What is your name? ") >>> print "Hello, %s. Nice to meet you."%name
In the two cases above,
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 >>> a_list >>> 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.
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.
From the standard terminal shell, documentation can be found using the command
$ pydoc topics list $ pydoc keywords if $ pydoc time
Inside the python interpretter, documentation on functions and variable types can be found using the function
>>> help(range) >>> x = 3 >>> help(x)
These commands are your friends. Use them early and often.
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).
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.
Open up "Canopy" (it's a little slow sometimes - be patient).
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.
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 '------------------'
Save your new script as "c2f.py". Be sure to keep track of which directory you are saving it to.
Make a prediction about what you think will happen when you run this script.
Click the "run" button to run the script. Does the output match your predictions?
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.
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 '------------------'
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.
To use one of the functions from the module, you put the modules name as a prefix, like
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
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.
Find all the roots of the cubic polynomial equation x**3 - 10x**2 + 31x - 30 = 0 using the function "numpy.roots()"
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()"
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).
Find the global minimum of the function f(x) = exp(2 x) - 3 x using "scipy.optimize.golden". Use calculus to check the solution.
Find the area under the curve 2 + sin(sin(x)+x) over the interval [0,10] using "scipy.integrate.quadrature".
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.