Home

Further Python

We have now gone through about half of Hello World:

And along the way we have seen something of the scientific libraries, especially

Having covered the essentials of Python, we will move on to biological applcations. You may wish, however, to explore some more fatures of Python.

Objects and modules

Chapters 14 and 15 of Hello World deal with what is commonly called object-oriented programming (OOP) and with details of libraries. When constructing larger programs, it may become difficult to keep a good overview over its structure and the variables that are being used. We will not construct such complicated programs in this course, but it may be worth looking through these chapters for future work.

Objects and modules are covered in chapters 13 and 14 of Hello World and we have not gone into this topic, or what is called object-oriented programming. We have, however, seen some aspects of objects and modules.

Interacting with Hardware

Python programs can be used to control experimental set-ups, especially custom-built ones.

The following will take a picture using the default webcam, if available, and save the image to a file.

import cv2
vidcap = cv2.VideoCapture()
vidcap.open(0)
image = vidcap.retrieve()[1]
cv2.imwrite('frame.png',image)
vidcap.release()

Make the camera take pictures of a plant over a period of several hours, and save them in a suitably-named sequence of files. To pause between frames, you can use time.sleep(dt) where dt is a time interval in seconds.

Esoterica

One feature of Python that you can completely ignore, because we won't use at all: the eval function. Consider the program.

import numpy
from pylab import plot, show
pi = numpy.pi
x = numpy.linspace(-pi,pi,100)
try:
    while True:
        s = raw_input("Select a numpy function ");
        y = eval("numpy."+s+"(x)")
        plot(x,y)
        show()
except Exception:
    print "Cannot do %s(x). Bye..." % s

Now, a comment sign can convert instructions to ordinary strings. The eval function, on the other hand converts ordinary strings into functions.

There are the two syntactic forms to import from a library. Both are equivalent, but one may be more concise than the other, depending on the situation.