Você está na página 1de 46

Handbook of the Physics Computing Course (Python language) 2002-2003

University of Oxford Sub-faculty of Physics


MJW/CRW/AOH

CONTENTS

Introduction 1.1 The Computing Course and Laboratory . . . 1.2 The Python course . . . . . . . . . . . . . . 1.3 The marking system and use of your logbook 1.4 Hilary term . . . . . . . . . . . . . . . . . . 1.5 Python . . . . . . . . . . . . . . . . . . . . 1.6 Typographical conventions . . . . . . . . . . Learning to use the system 2.1 Logging in and getting started . . . . . . 2.2 Terminal and the Unix command-line . . 2.3 Introduction to IDLE and the interpreter . 2.4 Introduction to Python . . . . . . . . . . 2.5 The editor . . . . . . . . . . . . . . . . . 2.6 Modules and a more interesting program 2.7 Logging out . . . . . . . . . . . . . . . The elements of Python 3.1 Variables . . . . . . . . . . . . . . . . 3.1.1 Names and assignment . . . . 3.1.2 Types . . . . . . . . . . . . . 3.1.3 Case sensitivity . . . . . . . . 3.2 Input and output . . . . . . . . . . . . 3.3 Arithmetic . . . . . . . . . . . . . . . 3.4 for loops . . . . . . . . . . . . . . . . 3.4.1 An example of a for loop . . . 3.4.2 Using the range function . . . 3.5 if statements . . . . . . . . . . . . . . 3.5.1 An example of an if statement 3.5.2 Comparison tests and Booleans 3.5.3 else and elif statements . . . . 3.6 while loops . . . . . . . . . . . . . . . 3.7 Formatted output . . . . . . . . . . . . 3.8 Using library functions . . . . . . . . . 3.9 Arrays . . . . . . . . . . . . . . . . . 3.9.1 Array basics . . . . . . . . . . 3.9.2 More on arrays . . . . . . . . 3.10 Making your own functions . . . . . . 3.11 File input and output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1 1 1 2 2 2 3 5 5 5 6 6 7 7 8 9 9 9 10 11 12 13 14 14 15 16 16 16 17 18 20 21 23 23 25 27 28

3.11.1 Reading from a le . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.11.2 Writing to a le . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.12 Putting it all together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Graphical output 4.1 Simple graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 Less simple graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3 Saving graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29 30 31 33 33 34 34 37 37 37 38 38 39 41 41 41

A Errors A.1 Attribute Errors, Key Errors, Index Errors A.2 Name Errors . . . . . . . . . . . . . . . A.3 Syntax Errors . . . . . . . . . . . . . . . A.4 Type Errors . . . . . . . . . . . . . . . . B Reserved Words

C Installing Python on your own PC C.1 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C.2 Gnuplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ii

CHAPTER

ONE

Introduction
1.1 The Computing Course and Laboratory

Being able to program a computer is a vital skill for the modern physicist. The rst year computing course is designed to teach computer programming in a scientic context, assuming no prior knowledge. This year, two different languages are being used: C and Python. They have similarities and differences, with their own particular advantages, but in both cases you will be learning generic skills which are common to all forms of programming. Half of you will learn Python and the other half C. This version of the course covers Python. All undergraduates are required to attend the computing course in their rst year. You will spend four half-day sessions in the Computing Lab during Michaelmas term. Sessions take place either in the morning (10:0013:00) or the afternoon (14:0017:00). People from either session may also work during the lunch-hour. You will work singly, not in pairs as you will do in other parts of the Practical Course. Computing will contribute the equivalent of 4 days to your Practical Course record: 2 days in Michaelmas and 2 in Hilary.

1.2

The Python course

During your four sessions in the Computing Lab, you will be using a Sun Unix computer. Unix is an operating system; for example, you have probably used Microsofts Windows operating system. Physicists often use Unix in preference to Windows because, once you know how to use it, it is a more powerful and exible environment. You will also learn the basics of computer programming. You will do this by working your way through the rest of this handbook, reading the explanations and attempting the exercises. If you have any trouble, please dont hesitate to speak to a demonstrator: they are there to help. We anticipate you will nish the exercises in this book at around the end of your second session. Dont worry if you nish earlier or later. If you think you have nished the handbook then talk to a demonstrator who will record your completion of the handbooks exercises as CO00 and select one of the problems for you to solve over the remaining sessions: CO11 Quadratic Equation; straight line tting by least squares CO12 Nuclear decay and the Doppler effect CO13 Numerical Integration by Simpsons rule and by a Monte Carlo method CO14 Solution of non-linear equations; solution of a differential equation CO15 Polynomial curve tting by least squares CO16 Graph plotting; Fourier Analysis

1.3

The marking system and use of your logbook

You are encouraged to use your logbook whilst you are in the Computing Lab. Keeping a logbook whilst programming is just as important as when doing experimental work. When you have completed the programming problem (CO11 CO16), you will be marked by a demonstrator, who will expect you to explain in detail how your program works; they will also test your program by running it. So it is in your own interests to keep a logbook as it will help you to explain your work to the demonstrator. The kind of things that could be recorded in your logbook include:

See also Section 1.3.2 of the Practical Course Handbook for more details on keeping a logbook.

1.4

In Hilary term you will be assigned a more advanced programming problem to solve. Towards the end of 3rd Week you will receive an email informing you of which problem you are to do. You can collect the appropriate script from the foyer of the Practical Course. The problem must be completed and an account written and submitted to the Practical Course technicians ofce (DWB Room 206) by 5pm on Friday of 8th Week. Section 1.3.5 of the Practical Course Handbook explains what to include in an account. The Computing Lab will be available for you to work on your problem throughout Hilary term. There will be a demonstrator present on Thursdays and Fridays to give assistance and advice to rst years working on programming problems. First years will have priority on these days; other years nominally have priority on Mondays and Tuesdays. In practice, though, there are likely to be very few 2nd years using the Computing Lab in Hilary term, so there should be machines available to use. No-one has priority on Wednesdays when the Lab may be used freely; however, people wishing to do serious work always have priority over those web-browsing or using email. In Hilary term access to the computers will be subject to availability rather than by formally-booked sessions.

1.5

Python1 is a relatively modern language by programming standards. It was rst released in 1991 (in contrast C is over thirty years old). It has many features typical of a modern language that help computer users write more complex programs in less time. This course will only teach you a subset of Python. Nevertheless, in doing the course you will acquire skills applicable both to Python and to programming in general. Python has been chosen because it is an increasingly popular language. Writing a program in Python will often take less time than to write the equivalent in most other languages and, because you can work with Python interactively, problems with the program are usually solved more quickly. Python is highly-suited to scientic programming (a small but growing number of people are using it in this department), as well as to writing applications and general-purpose programs.
1 Python

The outline design of your program; Steps you took which arent obvious from the problem script; Notes on any problems encountered as you tried to make your program work, and your solutions; Hints from demonstrators; Input data and output results, including graphs.

Hilary term

Python

takes its name from the 1970s television series Monty Pythons Flying Circus.

Chapter 1. Introduction

There is a price to pay for the speed with which Python programs are written: they often take longer to run than equivalent programs in other languages. However, except when serious number-crunching is being done, this trade-off is usually worthwhile. Python has been designed to enable programmers to spend more time thinking about their problem and its logical solution, and less time worrying about the details of the language. In this way you will gain generally applicable programming skills that will serve you well in your future, whether it be in academia or elsewhere.

1.6

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 jargon are written in italics the rst time they are used.

1.6. Typographical conventions

CHAPTER

TWO

Learning to use the system


2.1 Logging in and getting started

Sit at one of the Sun terminals. Move the mouse: the screen should come on; if it doesnt 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. Ask a demonstrator if you need help. The login panel should disappear and after a few seconds, you should see various windows appear on the screen. You will need to to use the Netscape web browser, so click Accept in its License panel. A Netscape browser window will appear displaying the Computing Lab web page; click on the link to the rst year course page and then on Getting started: work through this web document now (you can return to this manual when you have completed it).

2.2

Terminal and the Unix command-line

Minimise the Netscape window by clicking on the dot button at the top-right of its window). You can also minimise 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 U NIX command-line, or shell. You will also use the command-line if you remotely login to the system. A Unix shell is a bit like the DOS-prompt in Microsoft Windows, but it is far more powerful and exible: it makes available hundreds of commands, utilities and programs. The shell indicates that it is ready to receive commands by displaying the following 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.3

Introduction to IDLE and the interpreter

The rest of this chapter describes the IDLE application that you will use to write your own Python programs. IDLE is Pythons Integrated DeveLopment Environment; an application which enables you to both write and run Python programs. To start up IDLE type idle in a terminal and press the Return key:

rayleigh% idle

Note: idle is typed entirely in lower case. 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 >>>

This is the Python interpreter. An interpreter is a program which translates the program source code you write into machine code which the computer can understand and run. The rst four lines in the window are version information and can safely be ignored. >>> is the Python prompt. It is here that you type Python code when using it interactively. At this point, you may wish to minimise the Terminal window; do not close it or IDLE will be killed!

2.4

Introduction to Python

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. We indicated what we wanted to print to the screen by enclosing it in quotation marks. Exercise 2.4 Start Pythons intereactive interpreter and get Python to say Hello world to you by typing the above command, followed by the Return key, which indicates you have nished that instruction. If you have trouble getting a Python prompt, or get an error message when you press Return, ask a demonstrator. 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. For example, you should have found print was written in orange and "Hello world" in green. 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.4.1, code layout is particularly important in Python. 6 Chapter 2. Learning to use the system

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. The disadvantage of the Python Hello world program being so simple is that we havent learnt much about the language! The next sections introduce the editor and a more instructive example.

2.5

The editor

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). IDLEs 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: Creating a new program: selecting New Window from the File menu will open an empty editor window called Untitled. Opening existing programs: you can retrieve a previously saved program by choosing Open from the File menu and selecting the le to open. Saving programs: after typing or editing a Python program, save the le by selecting Save from the File menu. The rst time you save a le, 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 le. Once saved, the program remains on-screen for further editing if you wish. Closing programs: if you really have nished editing your program then choose Close from the File menu. If there are unsaved changes you will be prompted to save them. When you have nished with a window you should close it rather than minimising it otherwise your screen will become cluttered with lots of minimised window icons.

2.6

Modules and a more interesting program

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 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 le 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.

2.5. The editor

Exercise 2.6-1 Here is an example of a complete Python module. Type it into an editor window (File-New Window) and run it by choosing Run from the Run menu or press the F5 key on your keyboard.
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. If you write a program that seems to stop responding then select Stop program from the Run menu. 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. The editor will help you by highlighting and laying out your programs in the same way as the interpreter. Save the program as described above. 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 lenames or directory (folder) names. Exercise 2.6-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.

2.7

Logging out

Whenever you have nished, you should ensure that you logout to make your Sun terminal available for someone else to use. Before you do so, make certain that you have saved any changes you have been making in any editor windows or other applications; you should also Exit from Netscape (see the bottom of its File menu). To logout, click on the Exit button which is under the small globe icon near the centre of the icons along the bottom of the screen. You will be asked to conrm that you wish to logout: click OK to conrm logout. As part of the logout process, all applications you have running will be quit for you. The CDE environment will also remember which applications you were running in your session, and where their windows were situated on the screen: the next time you login, it will try to recreate the session; however, it will not remember any Unix commands, such as idle, which you may have been running from within a Terminal. (Note: Netscape is automatically launched every time you login; if you leave it running when you logout you will get two copies next time you login which is undesirable).

Chapter 2. Learning to use the system

CHAPTER

THREE

The elements of Python


3.1 Variables

3.1.1 Names and assignment


In Section 2.6 we used variables for the rst 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, you should nd the programming equivalent fairly intuitive. Variable names must start with a letter and then may consist only of alphanumeric characters (i.e. letters and numbers) and the underscore character, . There are some reserved words which you cannot use because Python uses them for other things; these are listed in Appendix B. Variables have names like a and b above, or x or fred or z1. Where relevant you should give your variables a descriptive name, such as firstname or height. Values are assigned to variables and then, whenever we refer to a variable later in the program, the reference is replaced with the value currently asssigned to it. This is best illustrated by a simple example:
>>> x = 5 >>> print x 5

You assign by putting the variable name on the left, followed by a single =, followed by what is to be stored. To draw an analogy, you can think of variables as named boxes. A box has been labelled x, and the number 5 put in that box. There are some differences between the syntax1 of Python and normal algebra which are important. Assignment statements work from right to left only. x = 5 is ne, but 5 = x doesnt make sense to Python, which will report a SyntaxError. You can think of the equals sign as an arrow pointing from the number on the right to the variable name , and read the expression as assign 5 to x (or, if you prefer, as x becomes 5). on the left: However, we can still do many of things you might do in algebra, like:

This assignment reads assign 0 to c, assign c to b, assign b to a, so:

1 The

syntax of a language is its grammar and structure, i.e. the order and way in which things are written.

>>> a = b = c = 0

>>> print a 0 >>> print b

0 >>> print c 0

There are also statements that are alegbraically nonsense, that are perfectly sensible to Python (and indeed to most other programming languages). The most common of these is incrementing a variable:

>>> i = 2 >>> i = i + 1 >>> print i 3

The second line in this example is nonsensical in maths, but makes sense in Python if you think of the equals sign as an arrow pointing from right to left. To describe the statement in words: on the right-hand side we have looked at what is in the box labelled i, added 1 to it, then stored the result in the same box.

3.1.2 Types
Variables are not always numeric. There are several types. The most useful are described below: Integer: Any whole number:
>>> >>> >>> >>> myinteger myinteger myinteger myinteger = = = = 0 15 -23 2378

There is no limit to the size of an integer. Float: A oating point number, i.e. a non-integer.
>>> >>> >>> >>> >>> myfloat myfloat myfloat myfloat myfloat = = = = = 0.1 2.0 3.14159256 1.6e-19 3e8

Although 2.0 is a whole number, by writing it as 2.0 we indicate that we want it stored as a oat rather than an integer, with the precision that entails The last examples use exponentials, and in maths would be written and . If a number is given in exponential form it is stored with the precision of oating point whether or not it is a whole number. Suprisingly, oats can actually be less accurate than integers. This is because of the way the computer stores them. A oat is stored to greater precision (in simple terms, to more decimal places) than an integer. For example, 59.998 is a more precise value than 60. But if the number we want is the number of seconds in a minutes 59.998 is not much use! This has important implications for comparing two numbers which will be discussed later. String: A string or sequence of characters that can be printed on your screen. They must be enclosed in either single quotes or double quotesnot a mixture of the two. You can include a single quote in a string enclosed in double quotes, and vice-versa:

>>> mystring = "Here is a string"

10

Chapter 3. The elements of Python

    

$  #"!

>>> mystring = Here is another >>> mystring = "Heres one with a single quote in it"

Arrays and Lists: These are types which contain more than one element. They are analogous to vectors and matrices in mathematics. The discussion of Arrays is deferred until Section 3.9 Arrays. For the time being, it is sufcient to know that a list is written by enclosing it in square brackets as follows: mylist = [ 2, 3, 5, 8] Complex: The complex number type allows the manipulation of variables which are complex (in the mathematical sense). A complex number is most easily created using j or J to represent the square root of -1. For example, a = 2 + 4j creates a complex number a. To evaluate the real and imaginary components of a use the real and imag methods. For example:

>>> print a.real 2.0 >>> print a.imag 4.0

If you are not sure what type a variable is, you can use the type() function to inspect it:

>>> type(mystring) <type str>

str tells you it is a string. You might also see <type int> (integer) and <type float> (oat) Exercise 3.1 Use the interactive interpreter to create integer, oat and string variables. Once youve created them, print them to see how Python stores them. Experiment with the following code snippet to prove to yourself that Python is case-sensitive, i.e. whether a variable named a is the same as one called A: >>> a = 1.2 >>> print A

3.1.3 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).

3.1. Variables

11

Most modern programming languages (eg. C, C++, Java, Python, Perl, etc.) are case-sensitive too. You should have found that Python makes this distinction in the previous exercise. 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. Numeric and Gnuplot are capitalised because they are the names of other programs. Int and Float are capitalised 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.

3.2

Input and output

Computer programs usually involve interaction with the user. This is called input and output. Output involves tasks such as printing things on the screen, writing results to les, and sending graphs and tables to a printer. We have already seen one way of getting input: the input() function in Section 2.6. The input() function can be used to get numbers (and only numbers) from the keyboard. You can put a string between the parentheses of input() to give the user a prompt. Hence the example in Section 2.6 could be rewritten as follows:

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

In this mode of operation the input() function is actually doing output as well as input! The print command can print more than one thing by separating them with a comma, as above. A space is automatically inserted between each thing printed. You can also concatenate (join) two strings using the + operator. No spaces are inserted between concatenated strings:

>>> x = "Spanish Inquisition" >>> print "Nobody expects the" + x Nobody expects theSpanish Inquisition

input() can only read in numbers (integers and oats). If you want to read a word or sentence, i.e. a string, from the keyboard, then you should use the raw input() function:

>>> name = raw_input("Please tell me your name: ")

Exercise 3.2 Copy the example in Section 2.6 into an empty module. Modify it so that it reads in three numbers and adds them up. Further modify the program to ask the user for their name before the three numbers. Then, instead of just outputting the sum, personalize the output message by rst saying: name here are your results where name is their name. Think carefully about when to use input() and raw input().

12

Chapter 3. The elements of Python

3.3

Arithmetic

The programs you write will nearly always use numbers. Python can manipulate numbers in much the same way as a calculator (as well as in the much more complex and powerful ways youll use later). Basic arithmetic calculations are expressed using Pythons (mostly obvious) arithmetic operators.

>>> >>> >>> 7 >>> -3 >>> 10 >>> 0.4 >>> 32 >>> 1 >>> 0.5

a = 2 b = 5 print a + b print a - b print a * b print a / b print a ** b print b % a print 4.5 % 2

# Set up some variables to play with

# Negative numbers are displayed as expected # Multiplication is done with a * # Division is with a forward slash / # The power operation is done with ** # The % operator finds the remainder of a division # The % operator works with floats too

The above session at the interactive interpreter also illustrates comments. This is explanatory text added to programs to help anyone (including yourself!) understand your programs. When Python sees the # symbol it ignores the rest of the line. Here we used comments at the interactive interpreter, which is not something one would normally do, as nothing gets saved. When writing modules you should comment your programs comprehensively and clearly. They should describe your program in sufcient detail so that someone who is not familiar with the details of the problem but who can program can understand how your program works. Examples in this handbook demonstrate good practice. Although you should write comments from the point of view of someone else reading your program, it is in your own interest to do so effectively. You will often want to refer back to programs you wrote some time afterwards. Well written comments will save you a lot of time. Furthermore, the demonstrators will be able to understand your program more quickly (and therefore mark you more quickly too!). The rules of arithmetic precedence are much the same as with calculators. ie. Python generally evaluates expressions from left to right, but things enclosed in brackets are calculated rst, followed by multiplications and divisions, followed by additions and subtractions. If in doubt add some parentheses:

>>> print 2 + 3 * 4 14 >>> print 2 + (3 * 4) 14 >>> print (2 + 3) * 4 20

Parentheses may also be nested, in which case the innermost expressions are evaluated rst; ie.

>>> print (2 * (3 - 1)) * 4 16

3.3. Arithmetic

13

Exercise 3.3 Play around with the interactive interpreter for a little while until you are sure you understand how Python deals with arithmetic. Make sure that you understand the precedence of operators. Ask a demonstrator if you need more help with this. Write a program to read the radius of a circle from the keyboard and print its area and circumference to the screen. You need only use an approximate value for . Dont forget comments and make sure the programs output is descriptive, i.e. the person running the program is not just left with two numbers but with some explanatory text. Again, think about whether to use input() or raw input().

3.4

for loops

3.4.1 An example of a for loop


In programming a loop is a statement or block of statements that is executed repeatedly. for loops are used to repeat a set of commands where the number of repetitions is known at the start of the loop. Here is an example:

sumsquares = 0

# sumsquares must have an initial value because # its a summation variable used each time around # the loop

for i in [0, 1, 2, 3, 4, 5]: print "i now equal to:", i sumsquares = sumsquares + i**2 # sumsquares incremented here print "sum of squares now equal to:", sumsquares print "------" print "Done."

The indentation of this program is essential. Copy it into an empty module. IDLE will try to help you with the indentation but if it doesnt get it right then use the TAB key2 . Dont forget the colon at the end of the for line. The role of indentation is explained below but rst let us consider the for loop. Try and work out what a for loop does from the programs output. The for loop can be considered as a foreach loop: For each thing in the list that follows, execute some statements. Remember a list is enclosed in square brackets. On each iteration of the loop, the next item in the list is assigned to i. That is to say, the rst time around, i = 0, the second time i = 1, etc. Indentation is an intrinsic part of Pythons syntax. In most languages indentation is voluntary and a matter of personal taste. This is not the case in Python. Python treats the indented statements as the section of the program that is to be repeated by the for loop. The indented statements that follow the for line are called a nested block. Note that the print "Done." statement is not indented. This means it will not be repeated each time the nested block is. The blank line after the nested block is not strictly necessary, but is encouraged as it aids readability. The editor and interactive interpreter will try to indent for you. If you are using the interpreter it will keep giving you indented lines until you leave an empty line. When you do this, the condition will be tested and if appropriate the nested block will be executed.
2 You

can also use any number of spaces, as long as the number is consistent

14

Chapter 3. The elements of Python

3.4.2 Using the range function


You will often need to do something a large number of times, in which case typing a long list becomes tedious. The range() function returns a list of numbers, allowing us to avoid typing them ourselves. You should give range() at least two parameters: rst the number at which the list it returns should start, and second, the number up to which the list should go. The second number itself is not in the list, but numbers up to this number are. This may seem strange, but there are reasons. As an example, we could have replicated the for loop above using range(0, 6), which returns the list [0, 1, 2, 3, 4, 5]. The complete program would then have looked like:
for i in range(0, 6): print "i now equal to:", i sumsquares = sumsquares + i**2 # etc.

Here are some more examples of the use of range():

>>> [0, >>> [0, >>> [5,

print 1, 2, print 1, 2, print 6, 7,

range(5) 3, 4] range(0, 5) 3, 4] range(5, 10) 8, 9]

# The list starts at 0 if unspecified

range() takes an optional third parameter that species the step between each number in the list:

>>> [0, >>> [0, >>> [5,

print 2, 4] print 3, 6, print 4, 3,

range(0, 5, 2) range(0, 16, 3) 9, 12, 15] range(5, 0, -1) 2, 1]

You can always get the number of elements the list produced by range() will contain (and therefore the number of times the for loop will be executed) by nding the difference between the rst and second parameters and dividing . that by the step. For example range(10, 20, 2) produces a list with 5 elements since The range function will only produce lists of integers. If you want to do something like print out the numbers from 0 to 1, separated by 0.1, some ingenuity is required:

for i in range(0, 11): print i / 10

Exercise 3.4 Use the range function to create a list containing the numbers 4, 8, 12, 16, and 20. Write a program to read a number from the keyboard and then print a table of the value of and from 1 up to the number the user typed, in steps of, say, 2. Dont worry about aligning the columns of your table for now.

3.4. for loops

5 DC

8 '53  0  @976421)('& A B

15

3.5

if statements

3.5.1 An example of an if statement


The if statement executes a nested code block if a condition is true. Here is an example:

age = input("Please enter your age: ") if age > 40: print "Wow! Youre really old!"

Copy this into an empty module and try to work out how if works. Make sure to include the colon and indent as in the example. What Python sees is if the variable age contains a number greater than 40 then print a suitable comment. As in maths, the symbol means greater than. The general structure of an if statement is:
if(condition): statements to execute if condition is true rest of program

Indentation is again essential. In the above general form, the indented statements will only be executed if the condition is true. However, rest of program is executed regardless; its lack of indentation tells Python that it is nothing to do with the if test.

3.5.2 Comparison tests and Booleans


The condition is generally written in the same way as in maths. The possibilites are shown below: Comparison a < b a <= b a > b a >= b a == b a != b a < b < c What it tests a is less than b a is less than or equal to b a is greater than b a is greater than or equal to b a is equal to b a is not equal to b a is less than b, which is less than c

The == is not a mistake. One = is used for assignment. Testing for equality is different: a = b sets a to the value of b but a == b tests if they are already equal. It is not possible to assign in a place where it makes no sense to do so, e.g. by doing if a = 4. It will often be the case that you want to execute a block of code according to the outcome of more than one condition. In some cases this is possible using the expression you should be familiar with from algebra: a < b < c. This tests whether a is less than b and b is also less than c. Sometimes you will want to do a more complex comparison. Conditions are logically combined using boolean operators, in particular and, or and not.

16

Chapter 3. The elements of Python

Logical operator and or not

Meaning AND: only TRUE if both operands are TRUE OR: TRUE if either operand is TRUE (or both are) NOT: inverts its sole operand: so that TRUE becomes FALSE; FALSE becomes TRUE

if x == 10 and y > z: print "Some statements which only get executed if" print "x is equal to 10 AND y is greater than z." if x == 10 or y > z: print "Some statements which get executed if either " print "x is equal to 10 OR y is greater than z" if not(x > y): print "Some statements which get executed if " print "x is not greater than y"

Exercise 3.5-1 Write a program to ask for the distance travelled and time taken for a journey. If they went faster than some suitably dangerous speed, warn them to go slower next time. Using boolean operators modify the program so that the user is also warned if they went too slowly.

3.5.3 else and elif statements


else and elif statements are used in conjunction with the if statement to execute some alternative statements if the if condition fails. The else statement is used as follows:
if(condition): Some statements executed only if condition is true else: Some statements executed only if condition is false rest of program

If the rst condition is true the indented statements directly below it are executed and then Python jumps to rest of program. Otherwise the nested block below the else statement is executed, and Python proceeds to rest of program. The elif statement is used to test further conditions if (and only if) the condition tested by the if statement fails:

x = input("Enter a number") if 0 <= x print elif 10 < print else: print <= 10: "That is between zero and ten inclusive" x < 20: "That is between ten and twenty" "That is outside the range zero to twenty"

3.5. if statements

17

Exercise 3.5-2

1. Write a program to read in two numbers from the user, and then print them out in ascending order. Modify the program to print three numbers in order. The code for this program will not be too complicated once it is written, but thinking about the logical steps that must be taken in order to sort three numbers is not easy. Make notes on paper before writing any Pythonperhaps draw some diagrams of the ow of the program as it tests the numbers. It should be able to correctly cope with: (2, 6, 1); (1, 6, 2); (6, 1, 2); (4, 6, 4); (6, 4, 4); (4, 4, 6); and even (4, 4, 4)! 2. Modify the program so that it sorts the number in descending order.

3.6

while loops

while loops are like for loops in that they are used to repeat the nested block following them a number of times. However, the number of times the block is repeated can be variable; the nested block will be repeated as long as a condition is satised. At the top of the while loop a condition is tested and if true, the loop is executed.
while condition: statements executed whilst the condition is true rest of program

Here is a short example:


i = 1 while i < 10: print "i equals:", i i = i + 1 print "i is no longer less than ten"

Recall the role of indentation. The last line is not executed each time the while condition is satised; it is only executed when the condition is no longer true. The condition used at the top of a while loop works exactly like those used in if statements: see Section 3.5.2, Comparison tests and Booleans. Here is a longer example that uses the % (remainder) operator to return the smallest factor of a number entered by a user:
print """ This program returns the smallest factor (except one!) of a number entered by the user. """ n = input("number: ") i = 2

# Start at two because one is a # factor of everything

18

Chapter 3. The elements of Python

while (n % i) != 0: i = i + 1

# i.e. as long as the remainder of n / i # is non-zero, keep incrementing i by 1.

# Now no longer in the while loop so we know i is a # factor and can print the result: print "The smallest factor of n is:", i

This program does something new with strings: if you want to print lines of text and control when the next line is started, enclose the string in three double quotes type the text. It will then be printed exactly as you entered it. In particular, a new line will be started whenever one appears in the string. This continues until another set of """ is encountered. This is the most complex program you have seen so far. Make sure you try running it yourself. Convince yourself that it returns sensible answers for small n and try some big numbers. If the program takes a very long time to produce a result then stop it using the Stop program item in the Run menu. Exercise 3.6 Modify the above example of while so that it tells the user whether or not the number they have entered is a prime. Hint: think about what can be said about the smallest factor if the number is prime. Some really big primes you could try with your program are 1,299,709 and 15,485,863. This is far from the most efcient way of computing prime numbers! If you can think of any ways of optimising the program then do so. The while loop is commonly used to repeat a section of the program as long as the user wants it repeating. This can be done by asking a yes/no question and comparing the response in the same way one might compare two integers, e.g. answer == "y":
answer = "y" # answer must already be "y" or the loop will never # be executed!

while answer == "y" or answer == "yes" or answer == "Y": # Note string comparisons are case-sensitive [Evaluate and output results, etc.] answer = raw_input("Evaluate again [y/n]? ") print "Program complete"

Recall the discussion of the precision and accuracy of oats in Section 3.1. Arithmetic involving oats is inherently inaccurate. If you compare to oats which should be equal you may nd that, although they are to many decimal places, at some point they start to diverge and the test for equality fails. Consider the following example:
from time import * i=0.0 while i != 1.0: print i i = i + 0.1 sleep(1) print "i is now exactly equal to 1.0"

The sleep() function inserts a one second pause. Without it the program would run too quickly to see what happens. 3.6. while loops 19

You should nd that the program stays in the loop forever (or until you select Stop Program from the Run menu!) rather than stop when i == 1.0. This is because each time 0.1 is added to i, it diverges slightly from its true value. By the time is reaches 1, it has a sufciently diverged value for the test to fail. You should avoid testing oats for equality in while loops or if tests.

3.7

Formatted output

So far we have used the print command in the simplest way possible; we have had no control over the way in which variables are printed:

>>> g = 9.81 >>> print Acceleration due to gravity is, g, m/s/s Acceleration due to gravity is 9.81 m/s/s

To allow more control over the way in which a number is displayed we use the % operator to produce formatted output:

>>> print Acceleration due to gravity is %f % g Acceleration due to gravity is 9.810000

Notice the %f inside the string. This indicates that when the string is printed Python should replace the %f with the variable that follows the string; g in this case. Now we can control the number of decimal places the number is printed to. For example, to print g to three decimal places, %.3f is used:

>>> print Acceleration due to gravity is %.3f % g Acceleration due to gravity is 9.810

If the number is not specied, %f will print the number to six decimal places by default. The % operator can also control the width of the displayed number. This allows the production of neatly aligned tables. For example, the 10.3f string forces the number to be printed to three decimal places and spaces to be inserted if necessary so that the number takes up ten characters

>>> g = 9.81 >>> pi = 3.14159 >>> e = 2.718281828 >>> carbonA = 12 >>> print "%10.3f" % 9.810 >>> print "%10.3f" % 3.142 >>> print "%10.3f" % 2.718 >>> print "%10.3f" % 12.000

g pi e carbonA

Notice that all the numbers are aligned and have been rounded to the required number of decimal places (including carbonA which is converted to a oat for printing).

20

Chapter 3. The elements of Python

%f is just one of the formatting strings: %d and %i can be used to print integers, %s can be used to print strings, and %e and %E are for exponential notation:
>>> print %5d % 12 12 >>> print %s % ("Newton") Newton >>> print %6.4e % (1.34624362572) 1.3462e+00 >>> print %6.4E % (1.34624362572) 1.3462E+00

To print more than one variable use more formatting strings:


>>> print "String: %s Integer: %d Float: %.4f" % ("Newton", 10, g) String: Newton Integer: 10 Float: 9.8100

The variables listed after the string must be enclosed in parentheses. Usually you will not need to use formatted output. Use the print command in the normal way (separating several variables with commas as in the example at the beginning of this section) whenever possible. Only if you need control over alignment or precision should you resort to formatted output. Exercise 3.7 Recall Exercise 3.4. In it you generated what was probably a rather messy table. Modify your program so the table is correctly aligned.

3.8

Using library functions

Python has a large library of functions which can be used for common programming tasks. You can also create your own. A function is just some Python code which is separated from the rest of the program. This has several advantages: repeated sections of code can be re-used without rewriting them many times, making your program clearer. Furthermore, if a function is separated from the rest of the program it provides a logical separation for the person writing it, so they can concentrate on either the function, or the rest of the program. Python has some built-in functions; type() and range() are examples that we have already used. These are available to any Python program. To use a function we call it. To do this you type its name, followed by the required parameters enclosed in parentheses. Parameters are sometimes called arguments, and are similar to arguments in mathematics. In maths, if we write , we are using the function with the argument . Functions often need more than one parameter to calculate their result. These should be separated by commas, and the order you write them is important. Refer to the discussion of the individual functions for details. Even if a function takes no parameters (you will see examples of such functions later), the parentheses must still be included. Python programs can use many more functions from the library. The denitions of these functions are contained in separate modules, similar to the ones you have been writing and saving in the editor so far. In order to use the functions from a particular library, you must explicitly import it. The most useful module for us is the math library3 . If you want to use the functions it contains, put the line from math import * at the top of your program.
3 Sorry about the spelling of math. Modern computer languages are generally written according to US English spelling conventions. Do the math!

3.8. Using library functions

R5 DQ%

THG F

3R5 G SCQP%& IH6F

21

The math functions are then accessible in the same way as the built-in functions. For example, to calculate the and of we would write a module like this:

from math import * pi_3 = pi / 3 print sin(pi_3) print cos(pi_3)

The math module contains many functions, the most useful of which are listed below. Function sqrt( ) exp( ) log( ) log10( ) sin( ) cos( ) tan( ) asin( ) acos( ) atan( ) fabs( ) floor( ) Description Returns the square root of Returns Returns the natural log, i.e. Returns the log to the base 10 of Returns the sine of Returns the cosine of Returns the tangent of Returns the arc sine of Returns the arc cosine of Returns the arc tangent of Returns the absolute value, i.e. the modulus, of Rounds a oat down to its integer

The trigonometric functions (sin, cos etc.) require their parameters to be in radians not degrees.

Beware! The floor function always rounds down, which can produced unexpected results, e.g.

>>> floor(3.01) 3.0 >>> floor(-3.01) -4.0

Some of the problems require random numbers. In order to generate a random number (oat) in the range 0 to 1 import the random library by typing from random import * at the top of your program. You then have access to the random() function which takes no parameters, and returns a random number in the above interval.

>>> from random import * >>> for i in range(0, 10): print random() 0.506439497519 0.764728666856 0.585323338465 0.48793319274 0.499259816584 0.750013149494 0.168141422421 0.656364752598

22

The math library also contains two constants: pi, , and e, parentheses (see the above example).

(the base of natural logarithms). These do not require

Chapter 3. The elements of Python

THG F

H`

Y CX

!5 )Q% F WU V

0.761254483937 0.7324844792

Exercise 3.8

3.9

Arrays

3.9.1 Array basics


The elements of a list can, in principle, be of different types, e.g. [1, 3.5, "boo!"]. This is sometimes useful but, as scientists, you will mostly deal with arrays. These are like lists but each element is of the same type (either integers or oats). This speeds up their mathematical manipulation by several orders of magnitude. In Python, arrays are not a core data type like integers, oating points and strings. In order to have access to the array type we must import the Numeric library by adding the following line to the start of every program in which arrays are used:

from Numeric import *

When you create an array you must then explicitly tell Python you are doing so as follows:

>>> from Numeric import * >>> xx = array([1, 5, 6.5, -11]) >>> print xx [ 1. 5. 6.5 -11. ]

The square brackets within the parentheses are required. You can name an array anything you might use for any other variable. The decimal point at the end of 1, 5 and -11 when they are printed indicates they are now being stored as oating point values. All the elements of an array must be of the same type; we included 6.5 in the array so Python automatically used oats. We can extend the box analogy used to describe variables in Section 3.1 to arrays. An array is a box too, but within it are smaller, numbered boxes. Those numbers start at zero, and go up in increments of one. See Figure 3.1.

xx
1 5 6.5 -11
xx[0] xx[1] xx[2] xx[3]
Figure 3.1: Arrays can be thought of as boxes within boxes This simplies the programthere need not be very many differently named variables. More importantly it allows the referencing of individual elements by offset. By referencing we mean either getting the value of an element of an

3.9. Arrays

5 DQ%

% D'

Use the math library to write a program to print out the will need to use the range() function.

and

V F aU

IH6F G

of numbers from 0 to

in intervals of

. You

23

array, or changing it. The rst element in the array has the offset [0] (NB. not [1]). The individual element can then be used in calculations like any other oat or integer variable. The following example shows the use of referencing by offset using the array created above:

>>> print xx [ 1. 5. 6.5 -11. ] >>> print xx[0] 1.0 >>> xx[0] = xx[0] + 8 >>> print xx [ 9. 5. 6.5 -11. ] >>> print xx[0] 9.0 >>> print sqrt( xx[0] ) 3.0

Lets consider an example of the use of arrays. The user has ve numbers representing the number of counts made by a Geiger-Muller tube recorded during succesive one minute intervals. The following program will read those numbers in from the keyboard and store them in an array.

from Numeric import * counts = zeros(5, Int) # See below for an explanation of this

for i in range(0, 5): print "Minute number", i response = input("Give the number of counts made in the minute") counts[i] = response print "Thank you"

The contents of the for loop are executed ve times. The user is asked for their one minute count each time, and the response is put into the i element of the counts array The new thing in that example is the zeros function. You cannot get or change the value of an element of an array if that element does not exist. For example, you cannot change the 5th element of a two element array:

>>> xx = array([3, 4]) >>> xx[4] = 99 Traceback (most recent call last): File "<pyshell#4>", line 1, in ? xx[4] = 99 IndexError: index out of bounds

Arrays are not like other data types. Python must rst know how many elements the variable contains so it knows where to put things, i.e. how many boxes are inside the box.4 This means we must create an empty ve element array before we can start storing the Geiger-Muller counts in it. We could do this by writing counts = array(0, 0, 0, 0, 0) but this would quickly get tedious if we wanted a bigger array and is impossible if the size of the array is not known in advance. Instead we do it with the zeros() function. This takes two parameters, separated by a comma. The rst is the
4 If

you have programmed in other languages, you will recognise this as being a bit like declaration.

24

Pcb

Chapter 3. The elements of Python

number of elements in the array. The second is the type of the elements in the array (remember all the elements are of the same type). This can be Int or Float Note: the upper case I and Fthis is to distinguish them from the float() and int() functions discussed later in Section 3.11 File input and output. In the Geiger-Muller example we created an array of type Int because we knew in advance that the number of counts the apparatus made would necessarily be a whole number. Here are some examples of zeros() at work:

>>> xx = zeros(5, Int) >>> print xx [0 0 0 0 0] >>> yy = zeros(4, Float) >>> print yy [ 0. 0. 0. 0.]

If there is any uncertainty as to whether Int or Float arrays are appropriate then use Float. If you attempt to store a oat in an array of integers, the oat will be truncated to the nearest integer. Arrays can be used instead of lists in for loops:

>>> from Numeric import * >>> xx = array([1,10.2,-509]) >>> for i in xx: print i 1.0 10.2 -509.0

This is very useful when writing functions which take array parameters whose size is not known in advance; rather than iterating over the array by writing for i in range(arraysize) where arraysize is some constant number you can just say for i in array. Exercise 3.9 Using for loops, range(), and the zeros() function, construct two one-hundred element arrays, such that element i of one array contains and the corresponding element of the other contains . Compute the scalar product of the two arrays to check that is zero. The scalar, or dot, product is dened as: and are orthogonal, i.e. their dot product

3.9.2 More on arrays


So far we have only considered the features of arrays that are common to most other programming languages. However, Pythons arrays can behave in a way more similar to vectors and matrices, making their manipulation easier. This section should be considered optional but, if you nd yourself using arrays in a problem, you will save yourself a lot of time by reading it. Consider a three-element vector. To double the length of the vector we simply multiply it by two: 3.9. Arrays 25

3 fe)('6& F WU 3   5d % & V

V F WU

IH6F G

qp 8 t sr@i h g q q

3 fe)('& TH6F 3   5d % G

In many languages (C for example) the programming equivalent is more complicated. You step through the array an element at a time, multiplying each element by two. In Python this might look like this:
>>> xx = array([2, 4, -11]) >>> yy = zeros(3, Int) >>> for i in range(0, 3): yy[i] = xx[i] * 2 >>> print yy [ 4 8 -22] # Create empty array ready to receive result

However, this is not required. Pythons arrays understand common mathematical operations and will generally do the right thing. Examples follow: If you add a number to an array, it gets added to each element...
>>> xx = array([2, 4, -11]) >>> yy = xx + 0.1 >>> print yy [ 2.1 4.1 -10.9]

...and if you multiply an array by a number, each element gets individually multiplied (like vectors)...
>>> print xx * 2 [ 4 8 -22 ]

If you add two arrays together the corresponding element in each array gets added together (again, like vectors)...
>>> zz = array([5, 5, 5]) >>> print xx + zz [ 7 9 -6]

...but of course the arrays must be of the same dimensions (see Figure 3.2):
>>> zz = array([5, 5, 5, 5]) >>> print xx + zz Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: frames are not aligned

The Numeric library contains many other useful functions. For example, one can compute the dot product of two arrays using the dot() function providing a much quicker way of doing the exercise in Section 3.9 (we want you to do it the long way this time, though, for practice!). Arrays can be of more than one dimension. A two-dimensional array is similar to a matrix in mathematics. Consider the following matrix:

We create such an array in Python as follows: 26 Chapter 3. The elements of Python

'' 0 7x0 8  u' R y R vw y ' vw  R  x0 ! 

xx
2 4 -11
xx[0] xx[1] xx[2]

zz
5 5 5 5
xx[0] xx[1] xx[2] xx[3]

= ?
Figure 3.2: Arrays must be of the same dimensions for their sum to be meaningful.

>>> xx = zeros([2,2], Float) >>> print xx [[0 0] [0 0]] >>> xx[0][0] = 5.3 >>> print xx [[ 5.3 0. ] [ 0. 0. ]] >>> xx[1][0] = 4 >>> xx[0][1] = -10 >>> xx[1][1] = 16 >>> print xx [[ 5.3 -10. ] [ 4. 16. ]] >>> print xx[1][0] 4.0

# Recall 2nd parameter to zeros is the type

The rst parameter that zeros() is passed maybe a list rather than a single number. This then gives the dimensions of the array (number of rows rst, then columns). Elements of the array are then indexed using two numbers enlcosed in square brackets. First the row offset from the top left, then the column offset.

3.10 Making your own functions


As we saw in Section 3.8, functions are very useful tools for making your programs more concise and modular. The libraries provide a useful range of facilities but a programmer will often want or need to write their own functions if, for example, one particular section of a program is to be used several times, or if a section forms a logically distinct unit. Functions must be dened before they are used, so we usually put the denitions at the very top of a program. Here is a very simple example of the denition of a function that returns the sum of the two numbers it is passed:

3.10. Making your own functions

27

>>> def addnumbers(x, y): sum = x + y return sum >>> x = addnumbers(5, 10) >>> print x 15

The structure of the denition is as follows: 1. The top line must have a def statement: this consists of the word def, the name of the function, followed by parentheses containing the names of the parameters passed as they will be referred to within the function. These are known as formal parameters (x and y in this case). The actual parameters (5 and 10 in the example) are assigned to the formal parameters when the function is called. Parameters are also often referred to as arguments. 2. Then an indented code block follows. This is what is executed when the function is called, i.e. used. 3. Finally the return statement. This is the result the function will return to the program that called it. If your function does not return a result but merely executes some statements then it is not required. If you change a variable within a function then that change will not be reected in the rest of the program. For example:
>>> def addnumbers(x, y): sum = x + y x = 1000 return sum >>> x = 5 >>> y = 10 >>> answer = addnumbers(x, y) >>> print x, y, answer 5 10 15

Although the variable x was changed in the function, that change is not reected outside of the function. This is because the function has its own private set of variables, sometimes called local. This means that the x variable in the function is not the same x as that used by the rest of the program. Local variables minimise the risk of subtle errors in your program.

3.11 File input and output


So far we have taken input from the keyboard and sent output to the screen. However, you may want to save the results of a calculation for later use or read in data from a le for Python to manipulate. You give Python access to a le by opening it:
>>> fout = open("results.dat", "w")

fout is then a variable like the integers, oats and arrays we have been using so farfout is a conventional name for an output le variable, but you are free to choose something more descriptive. The open function takes two parameters. First a string that is the name of the le to be accessed, and second a mode. The possible modes are as follows: 28 Chapter 3. The elements of Python

Mode r w a

Description The le is opened for reading The le is opened for writing, erasing the old lebe careful! The le is opened for appendingdata written to it is added on at the end

3.11.1

Reading from a le

There are various ways of reading data in from a le. The readline() method5 returns the rst line the rst time it is called, and then the second line the second time it is called, and so on, until the end of the le is reached when it returns an empty string:

>>> fin = open("input.dat", "r") >>> fin.readline() 10\n >>> fin.readline() 20\n >>> fin.readline()

The \n characters are newline characters. The parentheses are required. If they are not included the le will not be read. They are to tell Python that you are using the readline() function (recall a function is always followed by parentheses, whether it takes any arguments or not). You can see from the example that you tell Python to use methods by adding a full stop followed by the name of the method to the variable name of the le. This syntax may seem strange but for now just use the examples below as your guide to the syntax, and dont worry about what it means6 . The contents are read in and returned as a string, but if the data are numeric you need to coerce them into either oats or integers before they are used in calculations:

>>> fin = open("input.dat", "r") >>> x = fin.readline() >>> type(x) <type str> >>> y = float(x) >>> type(y) <type float> >>> print y 10.0

However, if the le you are inputting from is formatted such that each line contains more than one datum, you will need to use the string library to turn a line of text into several separate numbers. Begin your program with from string import * to have access to the library, then create a le variable and read in the rst line as usual. (Note: the data read in are just examples).

>>> fin = open("input.dat", "r") >>> line = fin.readline() >>> print line
method is a special kind of function which is associated with a particular variable. is actually the rst you have really seen of Object Oriented Programming, which is a powerful way of programming and thinking about problems that will not be discussed in this course.
6 It 5A

3.11. File input and output

29

1 5.06 78 15 >>> type(line) <type str>

The variable line is now simply a string containing the contents of the line. Assuming the data on the line are separated by white space (ie. any number of spaces or tabs), you can split the string into individual numbers using the split function. The split function takes at least one argument: the string which it will split into a list:

>>> data = split(line) >>> print data [1, 5.06, 78, 15]

The variable data is now a list, each element of which contains each number from the line. Unfortunately, each element is still in the form of a string so you will usually need to coerce them into numbers using either int() or float(). Remember that lists can be referenced by offset in exactly the same way as arrays, so we coerce as follows:
>>> x = int(data[0]) >>> print x 1 >>> y = float(data[1]) >>> print y 5.06

3.11.2

Writing to a le

To output or write to a le use the write() method. It takes one parameterthe string to be written. Unlike the print command, the write() function does not automatically start a new line; if you want to start a new line after writing the data, add a \n character to the end:

>>> >>> >>> >>>

fout = open("output.dat", "w") fout.write("This is a test\n") fout.write("And here is another test line\n") fout.close()

Note: in order to commit changes to a le, you must close() the le as above. The write() method must be given a string to write. Attempts to write integers, oats or arrays will fail:

>>> fout = open("output.dat", "w") >>> fout.write(10) Traceback (most recent call last): File "<pyshell#65>", line 1, in ? fout.write(10) TypeError: argument 1 must be string or read-only character buffer, not int

To output the value of a numeric variable, you must rst coerce it into a string using the str() function:

>>> x = 4.1 >>> print x

30

Chapter 3. The elements of Python

4.1 >>> str(x) 4.1

To print several variables using the same write() function, use the + operator to concatenate the strings:
>>> element = Lithium >>> Z = 3 >>> fout.write("The atomic number of " + element + " is " + str(Z))

Exercise 3.11 Recreate the one hundred element arrays of and you created in Exercise 3.9. Print these arrays out to a le in the form of a table. The rst line of the table should contain the rst element of both arrays, the second line the second element, an so on.

3.12 Putting it all together


This section shows a complete, well-commented program to indicate how most of the ideas discussed so far (Variables, Arrays, Files, etc.) are used together. Below is a rewritten version of the example in Section 2.6, which did nothing more than add two numbers together. However, the two numbers are stored in arrays, the numbers are read in by a separate function, the addition is also done by a separate function, and the result is written to a le.
from Numeric import * def addnumbers(x, y): sum = x + y return sum # Declare functions first.

def getresponse(): # Create a two element array to store the numbers # the user gives. The array is one of floating # point numbers because we do not know in advance # whether the user will want to add integers or # floating point numbers. response = zeros(2, Float) # Put the first number in the first element of # the list: response[0] = input("Please enter a number: ") # Put the second number in the second element: response[1] = input("And another: ") # And return the array to the rest of the program return response # Allow the user to name the file. Remember this is a string # and not a number so raw_input must be used. filename = raw_input("What file would you like to store the result in?") # Set up the file for writing: output = open(filename, "w") # Put the users response (which is what the getresponse() function

3.12. Putting it all together

V F aU

THG F

31

# returns) into a variable called numbers numbers = getresponse() # Add the two elements of the array together using the addnumbers() # function answer = addnumbers(numbers[0], numbers[1]) # Turn the answer into a string and write it to file stringanswer = str(answer) output.write(stringanswer) # And finally, dont forget to close the file! output.close()

Exercise 3.12 The following function computes by summing the Taylor series expansion to terms. Write a program to print a to in steps of . The table of using both this function and the exp() function from the math library, for program should ask the user what value of to use ( must be an integer).

def taylor(x, n): sum = 1.0 term = 1.0 for i in range(1, n): term = term * x / i sum = sum + term return sum

32

Chapter 3. The elements of Python

Ir

 8

Y CX

Y X

CHAPTER

FOUR

Graphical output
4.1 Simple graphs

If you have reached this point before the end of the second session, you should read through this chapter, and attempt the exercise. Otherwise, you should probably just skim through to familiarise yourself with the information included so you can refer back to any of it later if necessary. You may ask a demonstrator to assess you for CO00 and assign and book one of the problems for you. Generating graphs is not part of core Python. In this course you will use the Gnuplot package to generate graphical output. It is an extremely powerful and exible program, although it does have a rather steep learning curve for beginners. However, you will use the Gnuplot.py module to allow you to control Gnuplot from within Python which makes things much easier. In any program from which you would like graphical output you must include the line. . .

from Gnuplot import Gnuplot, Data

. . . in the same way as you import the math and Numeric libraries to have access to mathematical functions and arrays respectively. And then, in the same way as you use the open() function to get a le ready, use the Gnuplot() function to prepare a graph variable:

g = Gnuplot()

g is merely a suggested name for your graphyou are free to call it anything you would call any other variable. Your program should then prepare two arrays to be plotted: one for the -cooridinates, one for the . Let us assume two arrays exist. xx contains the -coordinates of the data, and yy the y coordinates. You then create a variable that points to the data using the Data() function. This creates a compound variable type that holds all the information required to generate a plot.

results1 = Data(xx, yy)

You can then draw the plot to the screen using the command:

g.plot(results1)

33

Usually you will want to give your graphs titles and label the axes. We might label our graph using the following commands:

g.title("Geiger-Muller counts made in one minute") g.xlabel("Time (minutes)") g.ylabel("Counts")

This must be done before the graph is plotted using the g.plot command. Depending on the structure of your program, you may nd the graph ashes up on the screen for such a short time that you cannot see it. This is because of the way the Gnuplot library works: the graph will only remain as long as the Python module that created it is still running. To insert a pause into your program then put a raw input() function after g.plot(). The raw input() function will wait for the user to press return. A simple example is:

g.plot(results1) raw_input("Press return to continue")

Note we have not done anything with the result of the raw input() function. The user might, for example, have typed some text but we are not interested in it and it is discarded.

4.2

Less simple graphs

You will often want to modify the way a graph looks or plot several sets of data on the same graph so you can compare them. If we had created the results variable as follows:

results1 = Data(xx, yy, with=lines, title=Results 1)

then straight lines would have been drawn between the points, and a key with legend Results 1 included on the right-hand side of the graph. A key is useful if you want to plot multiple sets of data on the same graph. To do this set up to Data variables, and pass them to the plot() function:

results1 = Data(xx, yy, with=lines, title=Results 1) results2 = Data(xx, zz, title = Results 2) g.plot(results1, results2)

4.3

Saving graphs

If you want a print-out of the graph then use the hardcopy() method. This usually takes no parameters (although still requires the brackets). To use it simply include the line g.hardcopy() (assuming your graph variable is called g). So as to not waste paper we suggest you draw the graph to screen and then ask the user whether or not to print it out:

34

Chapter 4. Graphical output

# Set up title/axes labels first g.plot(results) # Draw the graph on screen answer = raw_input("Would you like to print this graph? ") if answer == "y" or answer == "Y" or answer == "yes": g.hardcopy()

If you want to save the graph to a le to allow you to include it in a report then use g.hardcopy with one parameter: the lename you would like to save the plot to. The le will then be saved in Postscript format. Give the le the extention .ps:

g.hardcopy("graph1.ps")

Exercise 4

To generate the value of x[n+1] from x[n] use the following procedure: 1. Generate a random number, , in the range [0,1]

Plot a graph of x against y and comment on its appearance.

4.3. Saving graphs

d  tk!  '!  8 4' rle e77)ndrl4e Q)7 j0 ia t d  tR!  8 74Irle e) rl4e Q od ia m

 7@g2u! r f

if

!k  rle e7DDIrl4e Q)77n' ia t  td  '' 8 4R rle D' r#Be mCCT ia m   t  0 d 8

! r2ghDIr  f d

if

!  0 tR'  R 8 7 r#e 7D' rl4e Q7)' r iWs t d  t!  k!  8 4 rle )77' rl4e Q77Irj0 iWs Q

d  f ' DIr2ghg4 r

if

e Cd4' r Ws t t 8 8 4 r Ws Q

'   u

2. if

 )

Create two large arrays, x and y (of order y[0] = 0.0.

elements). Populate their rst elements as follows: x[0] = 0.5;

35

36

APPENDIX

Errors
When there is a problem with your code, Python responds with an error message. This is its attempt at explaining the problem. It might look something like this:

>>> print x Traceback (most recent call last): File "<pyshell#1>", line 1, in ? print x NameError: name x is not defined

The rst few lines sometimes contain useful information about where Python thinks the error occured. If you are typing a module (rather than working interactively), click and hold the right mouse button and select go to le/line. This will take you to the line Python thinks is the problem. This is not always where the actual problem lies so analyse the last line of the error message too. This Appendix attempts to help you understand these messages.

A.1

Attribute Errors, Key Errors, Index Errors

Messages starting AttributeError:, KeyError: or IndexError: generally indicate you were trying to reference or manipulate part of a multi-element variable (lists and arrays) but that element didnt exist. For example:

>>> xx = array([1,2]) >>> print xx[5] Traceback (most recent call last): File "<pyshell#9>", line 1, in ? print xx[5 IndexError: index out of bounds

A.2

Name Errors

Name errors indicate that a variable you have referred to does not exist. Check your spelling. You might have mistyped a function, e.g. primt x. Check you havent attempted to do something with a variable before assigning a value to it, e.g. typing only the following into a module will not work:
print x x = 5

37

A.3

Syntax Errors

These suggest there is a sufciently severe problem with the way your code is written that Python cannot understand it. Common examples are missing out the colon at the end of a line containing a for, if or while loop; writing a condition with just one =, e.g.
if x = 5: print "x is equal to five"

Check that you havent forgotten to end any strings with quotes and that you have the right number of parantheses. Missing out parentheses can lead to a syntax error on the next line. You will get a SyntaxError when you run your program if the user does not respond to an input() function. Incorrectly indenting your program might also cause SyntaxErrors

A.4

Type Errors

You have tried to do something to a variable of the wrong type. There are many forms: TypeError: illegal argument type for built-in operation You asked Python to do a built-in operation on the wrong type of variable. For example, you tried to add a number to a string. TypeError: not enough arguments; expected 1, got 0 You used a function without supplying the correct number of parameters. TypeError: unsubscriptable object You tried to reference a variable that did not have more than one element (e.g. a oat or integer) by offset:

>>> x = 5 >>> print x[0]

38

Appendix A. Errors

APPENDIX

Reserved Words
You may not name your variables any of the following words as they mean special things in Python: and def exec if not return assert del finally import or try break elif for in pass while class else from is print continue except global lambda raise

Do NOT use any of the following words either (although they are not strictly Python reserved words, they conict with the names of commonly-used Python functions): Data array open Float close range Int float type Numeric int write Oxphys input zeros

You should also avoid all the names dened in the math library: acos exp pi asin fabs sin atan floor sqrt cos log tan e log10

39

40

APPENDIX

Installing Python on your own PC


C.1 Python

If you would like to install Python on your own Windows PC then follow these instructions1. Installing just Python on Windows is very easy. However, you will need to install some extra packages to simulate the environment in the Computer Lab. Begin by downloading the le pywin ox.zip from the Computing page on the Practical Course website:
http://www-teaching.physics.ox.ac.uk/computing. This is a collection of all the programs you will need. Unpack the

contents of this archive into a convenient location by following the on-screen instructions2 . Install the components as follows: 1. Install Python: Double-click on the Python-2.2.1.exe le. This will launch the Python installer. Follow the simple onscreen insctructions. All the default options are reasonable so you should be able to complete the installation by simply clicking Next several times (although if you know what you are doing you may like to alter some of the settings). 2. Install Numeric Python: Double-click on the Numeric-22.0.win32-py2.2.exe le and follow the instructions once again. The Numeric Python installer should detect your installed version of Python 2.2. If it does not you may not have installed Python correctly; ensure there is a Python entry in your Start Menu. 3. Upgrade IDLE: Python comes with an older version of IDLE than the one we use on the course. You should upgrade to the most recent version as follows: Copy the idle directory that the pywin ox.zip archive unpacked from its current location to C:\Python22\Tools. Do this by right-clicking on the idle directory, selecting Copy, double-clicking on the My Computer icon (on the Desktop), navigating to C:\, then to Python22, then to Tool and then selecting Paste from the Edit Menu. Windows should ask you if you are sure you want to overwrite the olde idle directory. You should say yes. If you have done this correctly then clicking the IDLE link in the Start Menu should launch IDLE. Check it is the new version by clicking About IDLE in the Help menu. The new window should have the title IDLEfork 0.8.1. If it says IDLE 0.8 then the new version is not correctly installed.

C.2

Gnuplot

The installation of Gnuplot is optional. If you have a graphing package or spreadsheet (such as Excel, which comes with Microsoft Ofce), you may nd it easier to output your results to a le and use that package rather than Gnuplot.
you use MacOS X or Linux you should nd Python is already installed. XP has the necessary software to unpack this archive for you, but if you run an older version of Windows, you may need to install, for example, Winzip (http://www.winzip.com)
2 Windows 1 If

41

If you want to use Gnuplot then copy the following les from the gnuplot directory of the archive to C:\Windows:

Then install Gnuplot.py: rst make sure the folder containing the contents of the Oxford archive is at the top. Doubleclick on the gnuplot.py folder to enter it and then open a DOS Command Prompt window by clicking Run on the Start Menu and typing command (without the quotation marks). Type the following command at the DOS prompt:

A large amount of text should be written to the screen, indicating that Gnuplot.py is being installed. Python and the associated packages should now be correctly installed. You can check the installation has worked by copying you solution to Exercise 4 and attempting to run it.

42

wgnupl32.exe wgnuplot.hlp wgnuplot.mnu pgnuplot.exe

C:\Python22\python.exe setup.py install

Appendix C. Installing Python on your own PC

Você também pode gostar