3.2 Interpreters, modules, and a more interesting program

There are two ways of using Python: either using its interactive interpreter as you have just done, or by writing modules. The interpreter is useful for small snippets of programs we want to try out. In general, all the examples you see in this book can be typed at the interactive prompt (»>). You should get into the habit of trying things out at the prompt: you can do no harm, and it is a good way of experimenting.

However, working interactively has the serious drawback that you cannot save your work. When you exit the interactive interpreter everything you have done is lost. If you want to write a longer program you create a module. This is just a text file containing a list of Python instructions. When the module is run Python simply reads through it one line after another, as though it had been typed at the interactive prompt.

When you start up IDLE, you should see the Python interactive interpreter. You can always recognise an interpreter window by the »> prompt whereas new module windows are empty. IDLE only ever creates one interpreter window: if you close it and need to get the interpreter back, select Python shell from the Run menu. You can have multiple module windows open simultaneously: as described in Chapter 2 each one is really an editor which allows you to enter and modify your program code (because of this, they will often be referred to in this handbook as editor windows). To get a new empty module (editor) window select New window in the File menu.

Here is an example of a complete Python module. Type it into an editor window and run it by choosing Run from the Run menu (or press the F5 key on your keyboard)3.1.

    print "Please give a number: "
    a = input()
    print "And another: "
    b = input()
    print "The sum of these numbers is: "
    print a + b

If you get errors then check through your copy for small mistakes like missing punctuation marks. Having run the program it should be apparent how it works. The only thing which might not be obvious are the lines with input(). input() is a function which allows a user to type in a number and returns what they enter for use in the rest of the program: in this case the inputs are stored in a and b.

If you are writing a module and you want to save your work, do so by selecting Save from the File menu then type a name for your program in the box. The name you choose should indicate what the program does and consist only of letters, numbers, and ``_'' the underscore character. The name must end with a .py so that it is recognised as a Python module, e.g. prog.py. Furthermore, do NOT use spaces in filenames or directory (folder) names.

Change the program so it subtracts the two numbers, rather than adds them up. Be sure to test that your program works as it should.


... keyboard)3.1
You might write programs that seem to stop responding. If this happens try selecting Stop Program from the Run menu