Handbook of the Physics Computing
Course
Michael Williams
December 3, 2002
Copyright c
�
2002 Michael Williams; this document may be copied, distributed and/or modified under certain condi-
tions, but it comes WITHOUT ANY WARRANTY; see the Design Science License for more details.
A copy of the license is:
� included in the LATEX distribution of this document—see http://users.ox.ac.uk/ sann1276/python.
� always available at http://dsl.org/copyleft/dsl.txt.
ii
CONTENTS
1 Introduction 1
1.1 The Python trial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Typographical conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 Using the system 3
2.1 Logging in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 IDLE basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 Programming using IDLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 Case sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 The elements of Python 7
3.1 Hello world . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Interpreters, modules, and a more interesting program . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.3 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.4 Input and output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.5 Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.6 for loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.7 if statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.8 while loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.9 Using library functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.10 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.11 Making your own functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.12 File input and output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.13 Putting it all together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4 Graphical output and additional Python 27
4.1 Graphical output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.2 Arrays in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.3 Functions you may need for the first-year problems . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.4 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.5 Python differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.6 Taking your interest further . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
A Errors 35
A.1 Attribute Errors, Key Errors, Index Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
A.2 Name Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
A.3 Syntax Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
A.4 Type Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
B Reserved Words 37
iii
iv
CHAPTER
ONE
Introduction
1.1 The Python trial
Thank you for participating in this trial of a proposed new first year computing course. During this trial we would like
you to consult demonstrators as much as you like. It is being run for us to iron out the problems in the course, and so
we will be most appreciative of any feedback that you can give us about the course or the handbook. Of course, we
also hope you will find the trial interesting and useful!
Like the Pascal course you did last year this trial consists of the following elements:
Using the system Logging in; using the graphical interface; files; using the Python interpreter; creating, editing,
storing and running programs. You will learn some of the skills associated with the use of the UNIX operating
system.
The elements of Python Learning enough of a programming language to write simple but useful programs, while
being introduced to the concepts of procedural programming.
To introduce yourself to the basics of Python you will need to read through Chapter 3, “The elements of Python”
and do the exercises given as you go along. If you do not understand how to tackle a particular exercise please
consult a demonstrator.
The handbook should contain all the information you need to complete the exercises and the problem you will
be doing.
Programming Problems Once you have gone through the introduction to Python we would like you to attempt a
more substantial problem. You may select one from the following list (you may select the one you did in the
first year if you wish):
CO11 Quadratic Equation; straight line fitting by least squares
CO12 Nuclear decay and the Doppler effect
CO13 Numerical Integration by Simpson’s rule and by a Monte Carlo method
CO14 Solution of non-linear equations; solution of a differential equation
CO15 Polynomial curve fitting by least squares
CO16 Graph plotting; Fourier Analysis
Note: whichever problem you choose, for the purposes of the trial it will be recorded as experiment CO91
Whilst it is not required, we would like you to use your logbooks to make notes as you do the course; in any case,
you will not need to produce a write-up of the problem you attempt. Rather, we will ask you to discuss it with a
demonstrator and fill in a questionnaire.
This course deliberately covers only a subset of Python, which is an extremely powerful and flexible language. In
doing the course you should acquire skills applicable both to Python and to programming in general. Python has
1
been chosen because it is possible to teach enough of the language to write useful programs relatively quickly, yet it
is potentially a very powerful language, which is being increasingly used throughout academia and the commercial
software industry.
1.2 Typographical conventions
This handbook uses the following typographical conventions:
Most of the document appears in the Times font.
Typewriter font is used for anything typed, e.g. Python code or UNIX commands.
Sans serif is used for menu and application names
New terms and other pieces of jargon are written in italics the first time they are used. [These will be described in a
glossary in a later edition].
2 Chapter 1. Introduction
CHAPTER
TWO
Using the system
2.1 Logging in
Sit at one of the Sun terminals. Move the mouse: the screen should come on; if it doesn’t after a few seconds, press
the power button in the bottom-right corner of the monitor, so the green LED is lit.
You should see a login panel: using lower case, enter your usual Physics username where indicated and then press
Return but before you enter your password, ensure that the graphic on the right says “Solaris Common Desktop
Environment”. If it does not, then click and hold the Options button, and select Common Desktop Environment
from the Session menu. Now enter your password and press Return.
The login panel should disappear and after a few seconds, you should see various windows appear on the screen. If
you want to be able to use the Netscape web browser—which we recommend—click Accept in its License panel (a
Netscape browser window will then appear, which you can minimise by clicking on the “dot” button at the top-right
of its window). You should also mimimise the Help Viewer and File Manager windows in the same manner. You
should now be left with a single Terminal window.
If you do not see a Terminal window, then you can get a new one at any time by clicking once on the terminal icon at
the bottom-right of the screen (it should be the third icon from the right). Click in the Terminal window so its border
turns dark pink (this indicates that you can type things into it). Terminals provide access to what is known as the UNIX
command-line, or shell. A Unix shell is a bit like the DOS-prompt in Microsoft Windows, but it is far more powerful
and flexible: it makes available hundreds of commands, utilities and programs. The shell indicates that it is ready to
receive commands by displaying the following 1 prompt:
rayleigh%
Some basic help and information about Unix commands is available by typing help in a Terminal window. Mostly,
however, you will not need to use the shell because we have made available a single, integrated application for doing
Python programming called IDLE.
2.2 IDLE basics
This section describes the IDLE application that you will be using when you start writing your own Python programs
in the next chapter. You will probably need to refer back to it when you start working through Chapter 3.
IDLE is Python’s Integrated DeveLopment Environment; in other words it is an application which enables you to both
write and run Python programs. 2
To start up IDLE type idle at the shell prompt and press the Return key:
1This is the default shell prompt: it can be customized.
2If you are familiar with UNIX or Linux you may alternatively use your favourite UNIX text-editor to write your Python programs, and then run
them yourself using the python command. However, IDLE does provide a nice environment for developing Python code, so we recommend you
try using it.
3
rayleigh% idle
Note: idle is typed entirely in lower case—see Section 2.4, “Case sensitivity”.
At this point, you may wish to minimise the Terminal window; do NOT close it or IDLE will be killed!
After a few seconds a new window called Python Shell will appear. This is IDLE’s interface to the Python interpreter.
An interpreter is a program which translates the program source code you enter into machine code which the computer
can understand and run. Chapter 3 explains all about using the Python interpreter.
IDLE also includes an editor which is an application, rather like a simple word-processor, that you use to write
programs (or indeed any kind of text). IDLE’s editor has been customized to make it particularly useful for writing
Python programs, and it should be fairly intuitive to use. Documents are opened, closed and saved by selecting
commands in the File menu.
2.2.1 Creating a new program
Selecting New Window from the File menu will open an empty editor window called Untitled.
2.2.2 Opening existing programs
You can retrieve a previously saved program by choosing Open from the File menu and selecting the file to open.
2.2.3 Saving programs
After typing or editing a Python program, save the file by selecting Save from the File menu. The first time you
save a file, Save will actually behave like Save As; in other words, a small window will appear where you can enter
the name you wish to give your program. On subsequent occasions, Save will simply save the file. Once saved, the
program remains on-screen for further editing if you wish.
2.2.4 Closing programs
If you really have finished editing your program then choose Close from the File menu. If there are unsaved changes
you will be prompted to save them.
In general, when you have finished with a window you should close it rather than minimising it as otherwise your
screen will become cluttered with lots of minimised window icons.
2.3 Programming using IDLE
As you will see in Section 3.2 it is possible to write programs either interactively or by using the editor. You will
probably need to refer back to this section when you start writing your own programs.
2.3.1 Using the interactive interpreter
Many of the examples in this handbook use Python’s interactive interpreter. If you don’t already have one open, you
can get an interactive window (a Python Shell) by selecting Python Shell from the Run menu.
4 Chapter 2. Using the system
A new window containing the following text will appear:
Python 2.2.1 (#1, May 2 2002, 23:54:03)
[GCC 2.95.2 19991024 (release)] on sunos5
Type "copyright", "credits" or "license" for more information.
IDLE Fork 0.8 -- press F1 for help
>>>
The first four lines are version information and can safely be ignored. >>> is the Python prompt. It is here that you
type Python code when using it interactively.
The interpreter will highlight your program to aid you: key words it recognizes will be coloured orange while words it
does not will be black; quoted text will appear in green and errors in red. This may help you to spot mistakes in your
program.
The interpreter will also try to help you write Python in other ways, in particular with laying out your code. As
described in Section 3.6.1, code layout is particularly important in Python.
It also has simple history capabilities, allowing you to recall recently typed commands and edit and re-use them. To
recall a command, use the arrow keys to move the cursor back up to the line you would like to repeat and press the
Return key. That line will then appear at your prompt. You can now edit it if required and execute it as normal.
2.3.2 Using the editor
The editor is used to create and save new programs or to open, modify and save existing stored programs (in Python,
stored programs are usually called modules). If you need a new editor window then choose New Window from the
File menu.
To run a program select Run Program from the Run menu (or press F5). The results of the program will appear in a
special Output window.
The editor is customised for writing Python programs: it will highlight and lay out your code for you in the same way
as the interpreter.
2.4 Case sensitivity
If an operating system or programming language differentiates between a word typed partly in upper case, one typed
entirely in upper case, and one typed entirely in lower case it is said to be case-sensitive.
You may have used Microsoft Windows: in general it is not case-sensitive. This system runs Solaris which is a variant
of the UNIX operating system. UNIX operating systems are always case-sensitive. For example, look what happens if
we capitalise the idle command:
rayleigh% Idle
Idle: Command not found
rayleigh% IDLE
IDLE: Command not found
UNIX commands tend to be written entirely in lower case (though sometimes upper-case characters are used as well).
Most modern programming languages (eg. C, C++, Java, Python, Perl, etc.) are case-sensitive too. When writing
programs in these languages you have to use lower case much of the time.
In Python there are a few exceptions to this rule. The most important examples you will encounter in this course are
Numeric, Oxphys, Gnuplot, Int and Float.
2.4. Case sensitivity 5
Numeric and Gnuplot are capitalised because they are the names of other programs. Int and Float are capi-
talised to distinguish them from the terms int and float which have different meanings in Python. The basic rule
is that you should type commands in exactly as they appear in this manual.
6 Chapter 2. Using the system
CHAPTER
THREE
The elements of Python
These notes give a basic introduction to programming using Python and should contain all the information you need
for the first-year course.
3.1 Hello world
Programming languages are traditionally introduced with a trivial example that does nothing more than write the words
Hello world on the screen. The intention is to illustrate the essential components of the language, and familiarise the
user with the details of entering and running programs.
The good news is that in Python this is an extremely simple program:
print "Hello world"
The program is self-explanatory: note that we indicated what we wanted to print to the screen by enclosing it in
quotation marks.
EXERCISE 3.1
Start up Python’s interactive interpreter (see Chapter 2, “Using the system”, for more details). Get Python to
say “Hello world” to you by typing the above command, followed by the Return key (this tells Python you
have finished that instruction). If you have trouble getting a Python prompt, or get an error message when your
program is run, ask a demonstrator.
The disadvantage of the Python “Hello world” program being so simple is that we haven’t learnt much about the
language! The next section contains a more instructive example.
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 interac-
tive 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:
7
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)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.
EXERCISE 3.2
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.
3.3 Variables
3.3.1 Names and Assignment
In Section 3.2 we used variables for the first time: a and b in the example. Variables are used to store data; in
simple terms they are much like variables in algebra and, as mathematically-literate students, we hope you will find
the programmin