Algorithms for Graphical Models (AGM)

Practical 01: Python programming


  1. Finding the information
  2. Getting started with the Python interpreter
  3. Hello world!
  4. Checking gPy works
  5. Python tutorial
  6. Python exercises

Finding the information

Good news! You do not need to memorise how Python works. Lots of documentation is available, reachable via a variety of routes. Sometimes Python HTML documentation is installed locally, but at time of writing this is not the case in our department. So instead make use of the online documentation for Python 2.6.6 (the version installed here). The documentation for the most recent version of Python is always available from the official Python site. Just look for the documentation links on the left hand side.

You can also get documentation directly from the Python interpreter. Just start up the Python interpreter by typing python at the command line. Then type help() and follow the instructions. Typing Control-d gets you out of the help system and another Control-d will stop the interpreter.


Getting started with the Python interpreter

To start the Python interpreter, just type python at the Unix command line. To finish with it just enter control-d.


Hello world!

Let's get this out of the way. The Python 'Hello world' program is a single line: print "Hello world!". Save this in a file called, say, hello.py Since the print statement is at the top-level, there should be no indentation. Run the program with: python hello.py

You can compare your Python "Hello world!" program to the same program written in a host of other languages at the Wikipedia.


Checking that gPy works

By following the instructions, ensure your PYTHONPATH is set so that your programs can find the gPy package. Now grab this program and check it works. You might also want to fetch the demo programs for the lectures so far, and check they work. (Some of these programs require input files, make sure you get these also.)


The Python tutorial

Well, the claim is "learn Python in an afternoon". Perhaps it's true for mornings too. Let's put this to the test. Just work your way through the online Python tutorial using the interpreter to try out the examples. On a first pass, you can skip Sections 1, 2, 3.1.3, 4.7, 6, 7, 8.4-8.7, 9.7-9.11. You will need to check out at least Sections 6 and 7 on a second pass.


Python exercises

I used to teach introductory Python and have a bunch of exercises. You can find them here.


Last modified: Fri Oct 28 09:41:42 BST 2011

Valid XHTML 1.1!