University of Southampton logo

Python

Introduction to Python

Python is an interpreted, interactive, object-oriented programming language. It is often compared to Tcl, Perl, Scheme or Java.

Python combines remarkable power with very clear syntax. It has modules, classes, exceptions, very high level dynamic data types, and dynamic typing. There are interfaces to many system calls and libraries, as well as to various windowing systems (X11, Motif, Tk, Mac, MFC). New built-in modules are easily written in C or C++. Python is also usable as an extension language for applications that need a programmable interface.

The Python implementation is portable: it runs on many brands of UNIX, on Windows, DOS, OS/2, Mac, Amiga... If your favourite system isn't listed here, it may still be supported, if there's a C compiler for it. Ask around on comp.lang.python -- or just try compiling Python yourself.

The Python implementation is copyrighted but freely usable and distributable, even for commercial use.

Getting Python

If it's not already available on your system - most Linux distributions come with Python - then it can be obtained from http://www.python.org/.

Installation is straightforward and there are further instructions on the Python website mentioned above.

First steps

First, one should open a Python command interpreter. This can be found from the Start Menu on Windows systems, or by typing python at a Linux command prompt.

 
Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> 

The >>> is the Python prompt, which appears during an interactive session such as this. Let's try some simple commands.

 
>>> print "Fish and chips" 
Fish and chips 
>>> 

As you can see, passing the print command to Python and then something within double quotes (") will cause Python to output this to the screen. After the command has finished, we are returned to the >>> prompt. The print command also works with number and sums.

 
>>> print 3 
3 
>>> print 3+4 
7 

We don't need the double quotes here, as Python is interpreting these as numbers (specifically, integers) rather than strings. Try putting quotes around these examples and see what happens. Look at this example and try and work out what's going on.

 
>>> a=3 
>>> b=4 
>>> print a+b 
7 
>>> print a, "+", b, "is", a+b 
3 + 4 is 7 

We're assigning the value 3 to the variable a and the value 4 to the variable b. We can print these as before, and the net result is the same as that before. Look at the last statement. We can mix up strings and variable names (and numbers, but we didn't do that here). Using a comma (,) to separate these statements adds a space in between for clarity. Let's have a look at lists.

Lists

 
>>> a=[1,2,3] 
>>> print a 
[1, 2, 3] 
>>> print a[1] 
2 
>>> print a[2] 
3 

Lists are analogous to arrays in C or matrices in Matlab; indeed the input syntax is similar to that of Matlab with respect to this. If a list is assigned to some variable (a, for example), then the whole list can be accessed as a (as in print a) and items can be accessed through a[n] where n is the number of the list item you wish to access. Look closely at the example - a[1] holds the value 2. This is because Python, like C, starts counting from zero rather than from one. The 0th element of the list, a[0], in this case is the number one. The last element of a list can be accessed by using negative numbers, e.g. a[-1]. This number can be anything, as it counts back from the end of the list.

Note that lists are not limited to just storing numbers; anything can be stored in these - strings and objects spring to mind - and any combination of these can be stored. Note also that lists can be stored as elements of a list (!).

 
>>> a = [5, 2, 3, 7, "fish", 5, 6, ["chips", "peas"], 9] 
>>> print a 
[5, 2, 3, 7, 'fish', 5, 6, ['chips', 'peas'], 9] 
>>> print a[0] 
5 
>>> print a[-1] 
9 
>>> print a[7] 
['chips', 'peas'] 
>>> print a[7][0] 
chips 
>>> print a[7][1] 
peas 

Note that any variable or indeed object can be added to a list.

 
>>> some_number = 42 
>>> b = [4, 3, some_number, 23] 
>>> print b 
[4, 3, 42, 23] 

Lists can be parts of other lists in a similar way.

 
>>> c = [a, some_number, b, 9, 8] 
>>> print c 
[[5, 2, 3, 7, 'fish', 5, 6, ['chips', 'peas'],  
  9], 42, [4, 3, 42, 23], 9, 8] 

Ranges

Ranges are handy for generating a sequence of numbers as a list

 
>>> range(10) 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
>>> range(2, 10) 
[2, 3, 4, 5, 6, 7, 8, 9] 
>>> range(-3, 3) 
[-3, -2, -1, 0, 1, 2] 

range(10) returns a list of numbers starting from zero counting up to (but not including, as in C) ten in steps of one. range(2, 10) will do the same, only starting from two instead of zero. range(-3, 3) starts from -3 and ends at 2 (not 3) in steps of one. The step size can be altered.

 
>>> range(0, 10, 2) 
[0, 2, 4, 6, 8] 
>>> range(10, 2, -1) 
[10, 9, 8, 7, 6, 5, 4, 3] 
>>> range(-5, 7, 3) 
[-5, -2, 1, 4] 

The third argument to the range function alters the step size. Making the step size negative will result in a list that counts down.

For

The for statement behaves differently to most languages; instead it is more of a 'for each' loop. You pass Python a list to iterate over.

 
>>> for n in [1, 2, 3]: 
        print n, "times two is", n*2 
1 times two is 2 
2 times two is 4 
3 times two is 6 

Note that there are no explicit delimiters in Python - its equivalent of C's curly braces({, }) is indentation, i.e. whitespace. This obliges you to write 'pretty' code, and it also helps you track loops and functions.

 
>>> x = [3, 5, 7] 
>>> for n in x: 
        print "In n =", n 
        for fish in range(n): 
             print fish, "squared is", fish*fish 
        print "Out of n =", n 
 
In n = 3 
0 squared is 0 
1 squared is 1 
2 squared is 4 
Out of n = 3 
In n = 5 
0 squared is 0 
1 squared is 1 
2 squared is 4 
3 squared is 9 
4 squared is 16 
Out of n = 5 
In n = 7 
0 squared is 0 
1 squared is 1 
2 squared is 4 
3 squared is 9 
4 squared is 16 
5 squared is 25 
6 squared is 36 
Out of n = 7 

A little bit complicated, but hopefully it is reasonably self-explanatory, on account of the indentation :) We create a list x. For each element n in the list x, we print some information, then create another list based on the current element n - in this case it's a simple range, similar to the one we just covered. We create another for loop, and this time call the current element fish (because life's complicated enough). We then print some more information to the user and return the results of fish*fish. By moving back a few spaces so the code is lined up with the for statement, we can perform more functions within the first loop, but outside the second.

Functions

Functions and methods within Python are created through the def command. These are extremely useful when you might otherwise repeat the same piece of code. A typical simple function might appear thus:

 
def square(x): 
    return x*x  # note, one can also use x**2 for x squared, 
                # x**3 for x cubed, x**4 for x^4 and so on... 

This function takes one input (x) and returns x^2 to whatever called it. So if your code contains the above function, you might access it in the following ways:

 
print square(9) # prints 81 (9*9) 
a=5 
print square(a) # prints 25 (5*5) 
b=square(3)     # assigns the value 9 to b (3*3) 
c=square(b)     # assigns the value 81 to c (b*b)  

Functions can be called from within functions:

 
def to_the_power_of_four(x):       
    return square(x) * square(x) # gets x^2^2 (i.e. x^4) 

A note about comments: If a hash (#) sign is used in the code body (i.e. not part of a print statement) then whatever follows it is a comment. A comment is ignored by the Python interpreter and it is considered good practise to use them to make the code more readable by a human - especially useful when one creates larger pieces of code.

A function does not necessarily need to return a value, nor does it need to receive a value. Look at these two functions:

 
def say_hello(name): 
    print "Hello", name 

def give_me_a_number(): return 1234

Import

With Python, one can extend functionality by importing libraries or source code. This is broadly comparable to the #include in C and the source command in Tcl. There are two ways of importing code. The first, and most recommended from a programmatical point of view, is to use import some_library, where some_library is the name of that which you want to source. Methods and functions within this are accessed through the general syntax of library_name.method_name so if you wanted to access the method or function garlicbread in the library pizzeria:

 
import pizzeria 
pizzeria.garlicbread() 

The second way is to import the whole library into your current namespace. This would allow you to access the methods from that library without prepending the library name. This is done through from some_library import * (note that the * could be any individual method name if you just wanted one):

 
from pizzeria import * 
garlicbread() 

The pizzeria library in this method could be a Python file created on another occasion. If I had the file pizzeria.py in my current working directory (or my path) then I would import it as above, i.e. import pizzeria (note no .py extension is required) or from pizzeria import *. There are many libraries built-in to Python which contain useful methods.

A real world example of this is if one wishes to perform a square root operation. The function (sqrt) lives in the Python math library.

 
import math 
x = 2.0 
root_x = math.sqrt(x) 

...or the equally valid...

 
from math import * 
x = 2.0 
root_x = sqrt(x) 

At this point it might also be worth mentioning that if you want help on the usage of a library you've just imported, you can do this with help(library_name). If you wanted help on using the math library, simply type help(math) at the interpreter prompt.

Casting

If you have a string (or a list of strings) and you wish to perform mathematical operations on them, then you must cast these as a particular type of number first. This is done by specifying type(string), where type could be something like int or float, and the string is some string (in quotes). The following example should make it clear what you can and can't do:

 
>>> my_numbers = ["1", "2", "3.14"] 
>>> my_numbers[0] 
'1' 
>>> int(my_numbers[0]) 
1 
>>> float(my_numbers[0]) 
1.0 
>>> float(my_numbers[2]) 
3.14 

Note that an error will appear if we try to cast "3.14" directly as an integer. Since 3.14 is not an integer, we must cast it as a float first, then as an integer (if we wanted to do this), or maybe use something like closest_int = round(float('3.14')).

System commands

If you want to perform a system command from within Python, then you need to import commands to provide this functionality. After this, a command can be executed with the fairly straightforward commands.getoutput(some_command_as_a_string) which will return the standard output and/or standard error.

Another way of doing this is to use the popen command provided by the os package. Consider the following example:

 
>>> import os 
>>> some_directory = os.popen('cd') 
>>> results = some_directory.read() 
>>> results 
'C:\\Python22\n' 

This is on a typical Windows system -- the results from a Linux system or indeed any other operating system will differ, as what is passed as a string to popen is executed as a native system command on that platform.

Splitting strings

Much of Python's power comes from its ability to handle strings well. For those of you who have just joined us, results = 'C:\\Python22\n'. Following on from the example in the System Commands section:

 
 >>> results.split(':')[0] 
'C' 

This creates a new list using the ':' as a delimiter - this is similar to the awk option -F ':'. If we left away the [0] we would have a two element list; one part containing 'C' and the other with the '\\Python22\n'. One can split on anything - including the '\n' (for a newline) or a space (' ').

File I/O

It's quite straightforward to stream a file into a Python list. The functionality lives in the sys library (this also contains methods for handling command line parameters as well as other system-like functions).

 
some_file = "my_nice_data.abc" 
fin = open(some_file, "r") 
my_lines = fin.readlines() 

Assuming you have a file called my_nice_data.abc, then after running this you will have a list on which you can operate (maybe using the split command from above?). Note that if there are numbers in the file on which you wish to operate, they must be cast as particular types beforehand. Writing to a file is similar:

 
some_file = "my_nicest_data.abc" 
fout = open(some_file, "w") 
fout.write("A line\n") 
fout.write("Another line\n") 
fout.write("42\n") 
fout.close() 

Further material

There are lots of plug-ins available on the web to extend the 'out-of-the-box' functionality of Python.

The official Python site is a good resource for all things Python. New versions, tools, tutorials and documentation can be found here.

PyMat is an interface between Python and Matlab allowing arrays to be passed back and forth between the two, as well as opening up Matlab's functionality for programmatical access from within Python.

NumPy, or Numerical Python adds a fast, compact, multidimensional array language facility to Python.

SciPy, or Scientific Python is an open source framework for using Python for scientific computing.

Site contents are copyright © 2003-2010 Dr. Richard Boardman. Please contact me if you would like to reproduce anything on this site at rpb@soton.ac.uk