Chapter 4. Introduction to Python

Table of Contents
Programming fundamentals
The Rules
Constructions
Conclusion

In this chapter I attempt to explain the fundamentals of Python. Here I have the same difficulty as Bertie Wooster faces when he tries to keep us abreast of the developments in Much Obliged, Jeeves. If I start too early, and begin at the very beginning, telling you all about how a computer doesn't understand plain English, I'm likely to irritate the coves who already know all about that, and just want a quick update on the high-level datastructures of Python and the current state of iterators and generators. However, that would leave the birds who are just starting out wondering whether it was such a good idea, after all, to pick up this book, and start learning how to program.

The fact is, writing an introduction to a complete programming language — or the concept of programming in itself — in just one chapter is the deuce of a task. It can't really be done, I'm afraid to say. If you already know a few programming languages, the on-line Python tutorial that is included with BlackAdder (or with Python itself) will probably suffice. If you haven't programmed all that much before, I highly advise you to buy Marc Lutz' excellent book, Learning Python, which is more like an introduction to programming, with a focus on Python.

Still with me? Then we had better take a quick tour through Python — which is really one of the easiest programming languages to master. Like ancient Gaul, and like this book, I have divided this chapter into three sections. The first tries to gently introduce the concept of programming to people who need to be primed with the most basic concepts. This is difficult for me to do, because I have been programming since I was twelve years old, so bear with me. The second is about Rules. Every programming language needs rules, and these are the rules that you need to keep in mind while programming Python. The final part gives an overview of the various constructions that Python contains for your satisfaction and pleasure.

Programming fundamentals

Please don't think that I can teach you programming in just the space of this section — you need to read some good books for that, such as Steve McConnel's Code Complete. What I can do is show you what the fuss is all about.

Computers do not do anything of their own volition: ultimately, someone has always told the machine what to do. Even crashing, down to the ultimate Blue Screen of Death, is caused by a computer blindly following instructions given by a human being.

Instructions can take the form of mouseclicks on fancy icons or buttons, or of bits of text the computer can understand. While there is still no computer that can understand plain English, there are many sub-dialects of English that a computer can understand. Python is one of these — a mix between pidgin English and mathematical notation. It is close to both the way computers work, and the way people think.

Unless you have a speech-to-text interface for your computer, you will have to type out all the pidgin-English, and then tell the computer to read what you've written, and do what you told it to. In a sense, you have to write a kind of manual for the computer to read, on how to perform a certain task.

Let's start with a simple example: fire up BlackAdder, and open the Python Interpreter window. If you start typing at the >>>, nothing will happen — only by pressing the Enter key will Python realize that it has been spoken to. Go ahead and type something — you can't hurt the computer or your system, except if, by a fluke, you type import os, followed by Enter and os.system("deltree c:") — which would radically clean out your C drive. So don't do this! On the other hand, asking Python about the captain's age or the contents of a bathtub that's being filled by two taps is all right.

Chances are very small that you will have hit upon something Python understands by accident, for you are strictly limited to the few keywords Python actually knows about. Most of these keywords are concerned with creating blocks of instructions, called functions. Functions are used to construct more complex systems. Other keywords are used for creating another kind of block, called classes, which are combinations of information and instructions.

Let's construct a class that knows the value of something (though not the price), and has a function that does something to that value. Remember to press enter at the end of each line, and don't type the three > signs or the three dots — Python does this for you.

Python 2.1.1 (#1, Aug 11 2001, 20:14:53) [GCC 2.95.2 19991024
(release)] on linux2 Type "copyright", "credits" or "license"
for more information.
>>> class FirstClass:
...     def __init__(self, value):
...             self.item=value
...     def printValue(self):
...             print self.item
...
>>> firstObject=FirstClass(value="BlackAdder goes forth")
>>> firstObject.printValue
<method FirstClass.printValue of FirstClass instance at 0x80db1f4>
>>> firstObject.printValue()
BlackAdder goes forth
>>>
    

If you type neatly and without mistakes, the contents of the Python interpreter window might look like this. Let's look at what happens: we have defined a ‘class' — that's a combination of information and complex actions that work on the contained information. The class has a name: FirstClass. (It is customary to capitalize the first letter of each word in a classname).

A class in itself is only the ‘template', so to speak, while an object is the ‘document' — just as you can make documents out of templates in a wordprocessor, you can make objects from classes.

Furthermore, the class has two ‘functions' — defined with the def statement.

The first function, __init__, is called when you want to create an object. The function has two ‘parameters' — that is, two names associated with a value (which we call a ‘variable' because the value can change, though the name remains the same). The first parameter refers to the object — it's always called self in Python (though it is called this in Java or C++). The second parameter is the value we want the object to manage for us.

You can use a dot ‘.' to associate variables with each other. The line ‘self.item = value' means that from now on the object we refer to with self (but also, in another context, with firstObject) knows that the name item is associated with the value represented by the parameter value.

Cleverly, Python doesn't forget this, so when you create an object with the name firstObject and the string value (that is to say, some text, as opposed to a number) ‘BlackAdder goes forth', you can later call the printValue() function, which will be able to do something with that value.

In order to call—that is, ask Python to execute— a function, you must add brackets after the function name; the parameters always go between the brackets. You don't have to put self between brackets, for Python does this for you. If you don't add the brackets, you are referring to the function, not asking Python to execute it. Python then answers you with the revealing sentence:

>>> firstObject.printValue
<method FirstClass.printValue of FirstClass instance at 0x80db1f4>
    

This tells you what kind of an object a function is. Calling the function will ‘print' the value of item in your window:

>>> firstObject.printValue()
BlackAdder goes forth
>>>
    

As I said, the self is supplied by Python, because you call the function from the object. That is, by prefixing the variable that points to the object to the function name, with a dot in between. This is the same as typing the following code (that is, calling the function with the object as its first parameter). As such, the following two expressions are equivalent:

>>>firstObject.printValue()
BlackAdder goes forth
>>>FirstClass.printValue(firstObject)
BlackAdder goes forth
    

Of course, typing in all these instructions correctly every time you want the computer to print ‘BlackAdder goes forth' is quite a chore. To get around this, you can write a small text document (this is not the same as a Word document!) using BlackAdder's text editor, and then ask Python to execute it.

To sum up: composition of complex wholes from smaller parts using a debased variant of English, and calling things names, is what programming is all about. The rest is made up of rules —rules intended to make it easier for computer the compute to determine what it should do, and more difficult for you to explain yourself to the machine.

Warning

Please be warned that if you execute your programs (or scripts) from BlackAdder, all the output of ‘print' will disappear into the void. The output will only be shown if you start your scripts using the debugger, and have the Python Interpreter window open. If you merely type in stuff in the Interpreter window you will see all output.

If this section went over your head with the airspeed of an unladen African swallow, don't worry. There is much more to programming — more than I can explain in a third of a chapter. Please read the Python tutorial that is included with Python and with BlackAdder. It is well-written and a little less hasty. Another good source is the free Livewires Python course, which you can find in PDF format at: http://www.livewires.org.uk/python/. I heartily recommend it as the best introduction to the general idea of programming I've ever read.