Computing 1 Python Tutorial - Leeds
Computing 1 Python Tutorial - Leeds
Computing 1 Python Tutorial - Leeds
MC and CH
2015
Contents
1 Introduction 3
1.1 Motivation For Computer Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 How To Use This Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Other Useful Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Running Python At Home . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3 Lists 9
3.1 Creating Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2 Accessing Lists - Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.3 Editing Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.4 Properties of Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.5 Final Word on Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5 Conditional Programming 15
5.1 Basic Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.2 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.3 elif and else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.4 Combining Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.5 try and except . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
6 Loops 21
6.1 for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
6.2 Indexing Lists Using for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
6.3 range Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6.4 Combining Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6.5 while Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
6.6 Breaking Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
6.7 Many Ways to Skin a Cat... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1
CONTENTS 2
8 Functions 36
8.1 Defining A Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
8.2 Args, Kwargs And Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
8.3 Returning Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
8.4 Local And Global Variables (More Advanced) . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
8.5 Calling Functions Recursively . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.6 Creating And Importing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
8.7 Doc-Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Introduction
This document aims to provide an overview of some of the basic features of computer programming using the
Python computer programming language. It is designed to be used as an additional reference to the lectures.
Furthermore it can be used as a quick reference for programming in the future. It is therefore advised that
you retain your copy as it may be very useful in future years.
1.3 Disclaimer
This document does not include all programming features associated with the Python language and as such is
not a definitive guide. If you would like a complete guide to the Python language look up the documentation:
http://www.python.org/doc/
3
CHAPTER 1. INTRODUCTION 4
resources online if you want more detail or just a different approach. Here is a list of some useful resources,
though it is worth bearing in mind that these are mostly targeted at learning programming in general rather
than for scientific use.
Many of the libraries used later on have their own web pages and documentation, which you may find useful
when dealing with them.
There is an excellent program, python(x,y), that can be installed on Windows computers. This includes
many useful modules (including all those used in this course) and an integrated development environment
called Spyder, where you can edit and run your code. For more information go to http://code.google.
com/p/pythonxy/
2 Though you may need to install some of the additional libraries yourself. This is usually quite straightforward.
Chapter 2
To assign a variable use the equals sign, =. In this example we will make a a float, b an integer and c a
string.
Code
a=7.8
b=7
c="7.8"
In Python, unlike many other languages, you do not need to specify the type (e.g. integer, float, string, etc.)
when you create a variable. At this point it’s worth bearing a few things in mind:
• variable names can contain numbers, but they MUST start with a letter.
• Python has certain protected words, such as if, for, and global (the text editor will normally highlight
these), which it uses to interpret the code. These cannot be used as variable names.
• variable names can be reused for different types of variable in one program.
You can use the type function to see the type of a variable
Code
a=7.8
b=7
c="7.8"
print "a has type ", type(a)
print "b has type ", type(b)
print "c has type ", type(c)
Output
a has type <type ’float’>
b has type <type ’int’>
c has type <type ’str’>
It is straight forward to convert one type to another using the functions float,int and str.
Code
b=7
d=float(b)
print "d = ", d
print "d has type ", type(d)
5
CHAPTER 2. BASIC VARIABLES AND OPERATORS 6
Output
d = 7.0
d has type <type ’float’>
Be careful when:
• Converting from float to int. The computer will ALWAYS round down.
Code
a=7.8
print "a = ", int(a)
Output
a = 7
• Converting strings to numbers. Any string that contains non-numeric characters will raise an error and
your code will crash.
2.1 Floats
In Python floats behave how numbers behave on a calculator and you can perform basic mathematical
operations (+, -, * and /). Each operation is prioritised according to the following table with the highest
priority operation at the top of the table performed before lower priority operations.
Operation Syntax
Brackets ()
Powers **
Multiplication *
Division /
Addition +
Subtraction -
Here is an example
Code
print (2+4)*6
Output
36
2.2 Integers
Integer operations work in much the same way as float operations, however there is one crucial difference
with the division operation.
CHAPTER 2. BASIC VARIABLES AND OPERATORS 7
Code
print "1/3 = ", 1/3
print "5/3 = ", 5/3
Output
1/3 = 0
5/3 = 1
As you can see division will ALWAYS round down to the nearest integer.
Output
1%3 = 1
5%3 = 2
3%3 = 0
Output
Hello World
Hello Hello Hello
If there is an expression on the right hand side of the equals sign this is always evaluated first and then
the variable on the left is set to this value. This is shown in the following example
CHAPTER 2. BASIC VARIABLES AND OPERATORS 8
Code
x=7.0
y=x+3.0
print "x = ",x," y = ",y
x=x+1.7
print "x = ",x
x=2*x
print "x = ",x
Output
x = 7.0 y = 10.0
x = 8.7
x = 17.4
Here the line y=x+3.0 uses the value of x, but doesn’t change it. Instead it sets y. In the two lines x=x+1.7
and x=2*x the value of x from before is used, but then x is reassigned (overwritten).
Chapter 3
Lists
A list can be used to store more than one piece of information within a single variable. For example you
may want to store a list of numbers, or the names of your ex-wives. Lists are another type of variable, in
the same sense that floats and strings are different types of variable.
Output
MyList = []
Python then knows that the variable MyList is a list containing no data. When initialising lists you can also
enter the contents of the list.
Code
MyList = [1.4,2.3,9.5,3.6,11.0]
print "MyList = ", MyList
Output
MyList = [1.4,2.3,9.5,3.6,11.0]
The list has been assigned the variable name MyList with five elements 1.4,2.3,9.5,3.6, and 11.0. Each
element of the list (e.g. 1.4 or 9.5) is separated by using a comma.
Output
y = [1.7,2,"generic text"]
9
CHAPTER 3. LISTS 10
Here we have a list with a float, integer, and a string comprising each element of the list. For the
purposes of scientific programming mixing data types inside a list can lead to problems so it is generally
good practice to stick to a single data type (usually float) when using lists.
Output
MyList = [1.4,2.3,9.5,3.6,11.0]
First Element = 1.4
Second Element = 2.3
As you can see to access the first element of the list (2.4) we use the index 0. This is because counting in
Python starts at 0. You can think of it as accessing the zeroth element of the list. So to access the fourth
entry in the list (3.6) you use the index 3.
Indexing also works with negative numbers. You can use -1 to access the last final element of a list and -3
to access the third to last element,
Code
MyList = [1.4,2.3,9.5,3.6,11.0]
FinalElement = MyList[-1]
ThirdLastElement = MyList[-3]
print "Last element = ", FinalElement
print "Third last element = ", ThirdLastElement
Output
Last element = 11.0
Third last element = 9.5
You can also slice lists to create another list containing only some of the data in the original list. The syntax
is to give two indices, separated by a colon, to tell Python where the slicing begins and ends.
Code
MyList = [1.4,2.3,9.5,3.6,11.0]
NewList = MyList[1:3]
print "NewList = ", NewList
Output
NewList = [2.3,9.5]
CHAPTER 3. LISTS 11
Notice that the sliced list contains all of the elements from the lower index up to, but NOT including, the
upper bound index.
Output
MyList = ["tree",2.3,9.5,3.6,11.0]
The first element of MyList has now been permanently changed from 1.4 to "tree".
Multiplication of lists behaves similarly to multiplication of strings; you can only multiply them by inte-
gers. Consider the following,
Code
MyList = [1.4,2.3,9.5,3.6,11.0]
NewList = 2*MyList
print "MyList = ", MyList
print "NewList = ", NewList
Output
MyList = [1.4,2.3,9.5,3.6,11.0]
NewList = [1.4,2.3,9.5,3.6,11.0,1.4,2.3,9.5,3.6,11.0]
The output of the code shows that multiplication of a list by 2 returns a single list with the original entries
repeated twice. This is true for any integer N whereby multiplication of the list will return a single list with
N lots of entries of the original list.
WARNING: Multiplication of a list by a number does not multiply each element of the list by
that number1 !
Multiplying a list by a float (e.g. 2.7) will return an error - try it for yourself.
You can add values to the end of a list using the append method. append is a method that can act on
a variable of the type List.
Code
List1 = []
List1.append(4.3)
print "List1 = ", List1
Output
List1 = [4.3]
1 To do this manually you could index each element individually and multiply it by 2. However, this is tedious and requires
you to know how long your list is. There are more flexible ways of editing the contents of lists, which we will cover in the section
on control structures.
CHAPTER 3. LISTS 12
The value that you want to append (in this case 4.3 ) is placed inside round brackets. Notice that the syntax
for using the append method does not require you to reassign List1 using (=) to add the new value.
There are other methods that can be used on lists including sort, count, and insert. See the Python
documentation for information on the different methods that can be used on lists. They all follow a similar
syntax for applying them.
Function Returns
max maximum value
min minimum value
len the number of elements (i.e. length)
Output
Max Value of List2 = 1982.3
Min Value of List2 = 1.1
Length of List2 = 7
This is very useful when handling with data where you don’t necessarily know how large the data you are
working with is going to be.
An important part of programming is being able to find errors - this is known as debugging.
Output
S = three
Traceback (most recent call last):
File "Errors And Debugging.py", line 3, in <module>
int(S)
ValueError: invalid literal for int() with base 10: ’three’
If there is an error the error message (which is usually red) will be the last output from the program. This
is because Python reads your program line-by-line and so will crash when it reaches an error and any code
after the error will not execute. Consider the error message in the above example. ValueError: gives us
the type of error and line 3 tells us that the error occurred at or around line 3.
Use of the print statement allows us to see what the value of S is. Adding "S = " to the print state-
ment made it clear what we were outputting. Once we can see what the value of S is we can clearly see why
the code fails to execute at line 3. This is because we attempted to convert a non-numeric string to a float
which is not allowed.
Another example of how print can be useful is when there is something wrong which isn’t generating an
error message. Here we want to list the first 9 square numbers:
Code
i=1 #loop counter
while i<10:
j=i*i
print "i = ", i
Here the loop will never end. However this is not straight forward to see from the output until the print
13
CHAPTER 4. ERRORS AND DEBUGGING 14
In this case the error can be fixed by adding the line i=i+1 inside the loop.
Code
i=1 #loop counter
while i<10:
j=i*i
i=i+1
Conditional Programming
Sometimes it is useful for a program to perform different tasks depending upon the present conditions within
the code. A real life example would be whether you turn left or right at a set of traffic lights. You may look
to see whether the traffic is busy and there is a preferred direction. You can make decisions in programming
using conditions.
Output
True
<type ‘bool’>
The bool type specifies the boolean value of an expression or variable. It can only be True or False. It is
possible to find out the boolean value of a given variable or expression using the bool function.
Code
w = 1
x = 10
y = []
z = 0
print "boolean value of 1 is ", bool(w)
print "boolean value of 10 is ", bool(x)
print "boolean value of empty list is ", bool(y)
print "boolean value of 0 is ", bool(z)
Output
boolean value of 1 is True
boolean value of 10 is True
boolean value of empty list is False
boolean value of 0 is False
So any finite sized variable, whether a float, string, list or integer has boolean value True. However,
15
CHAPTER 5. CONDITIONAL PROGRAMMING 16
empty variables, such as the integer 0 and lists of length zero, return a boolean value of False.
Meaning Syntax
Greater than >
Less than <
Greater than or equal >=
Less than or equal <=
Equal to ==
Not equal to !=
Note that to evaluate whether two variables are equal you use a double equal sign (==) and not a single one!
This is because a single equals sign is used for variable assignment. It is a very common mistake to only put
one equal sign when evaluating conditional statements so be careful. Furthermore comparing whether two
strings are equal is case sensitive - it is not enough to just match up the letters.
Below are some examples of using the different conditions. Note that they work for different data types such
as strings and floats.
Code
print "1 > 2 evaluates to ", 1 > 2
print "7.3 >= 0 evaluates to ", 7.3 >= 0
print "3 == 3 evaluates to ", 3 == 3
print "4 == 3 evaluates to ", 4 == 3
print "‘Anna’ == ‘anna’ evaluates to ", "Anna" == "anna"
print "‘Anna’ == ‘Anna’ evaluates to ", "Anna" == "Anna"
print "2 != 3 evaluates to ", 2 != 3
Output
1 > 2 evaluates to False
7.3 >= 0 evaluates to True
3 == 3 evaluates to True
4 == 3 evaluates to False
‘Anna’ == ‘anna’ evaluates to False
‘Anna’ == ‘Anna’ evaluates to True
2 != 3 evaluates to True
The condition can be any expression that evaluates to either True or False. The do something code will
execute ONLY if condition evaluates to True. The most transparent example of this is given below,
CHAPTER 5. CONDITIONAL PROGRAMMING 17
Code
if False:
print ‘Hello’
if True:
print ‘Goodbye’
Output
Goodbye
Here the conditions have been explicitly written as False and True. The first line of code is False and
so Python skips the indented code - this is because the code after an if statement is only evaluated if the
condition is True. Python then moves onto the third line of code. This is accepted because True, by
definition, is True and so Python executes the indented code to print the string "Goodbye".
If you fail to do this Python will crash and print an error message.
We will now replace the explicit use of True and False with some conditional expressions that you are
more likely to come across in practical programming. The following code asks the user to enter their name,
the code then prints a greeting if the name entered matches the computer’s one friend, Anna. The final line
of code is used to indicate the code has finished.
Code
name = raw input("Please enter your name: ") #covered later
if name == "Anna":
print "Welcome, Anna."
print "Finished"
Entering “Anna” (note the upper case A) when prompted produces the output,
Output
Please enter your name: Anna
Welcome, Anna.
Finished.
Here bold font indicates the user input. In this case the user entered Anna, the variable name now contains
the string "Anna"2 . The condition evaluates to True as the variable name exactly matches the person that
we were looking for. Python then runs the code indented beneath the if statement and the greeting is printed.
The last output shows that Python is case sensitive (i.e. the conditional statement "Anna"=="anna" evaluates
to False) and so you must be consistent when using capital letters. This also applies to defining variables
and functions.
1 Indented code is normally 2 or 4 spaces in from the edge. However, as long as you are consistent, you can indent with any
number of spaces. Most text editors will indent automatically after you type a colon.
2 raw input automatically converts the characters entered at the screen to a string so we did not need quote marks around
Notes on the code: The raw input function is used to request the number from the user. The function
int converts the string to an int type4 .
Code
x = int(raw input("Enter any integer: "))
if x > 10:
print x," is greater than 10."
elif x < 10:
print x," is less than 10."
else:
print x," is equal to 10."
Here are the outputs for inputting different numbers. The numbers in-putted are in bold.
Output
Enter any integer: 5
5 is less than 10.
Output
Enter any integer: 23
23 is greater than 10.
Output
Enter any integer: 10
10 is equal to 10.
Code
x = -1
y = -2
Output
x and y are both less than 0
if x >= 0 or y >= 0:
print "one, or both, of x and y are positive numbers"
else:
print "Both x and y are negative"
Output
one, or both, of x and y are positive numbers
Mixtures of and and or conditions can be combined which gives the programmer lots of flexibility when it
comes to writing if statements.
try:
float(x)
print "Worked"
except:
print "Failed"
print "End"
CHAPTER 5. CONDITIONAL PROGRAMMING 20
Output
Worked
End
We can convert the string “7” to a float so the indented code beneath except was ignored. Here is an
example where the try code would ordinary produce a failure. We will attempt to convert the string “seven”
to a float - which raises an error.
Code
x = "seven"
try:
float(x)
print "Worked"
except:
print "Failed"
print "End"
Output
Failed
End
You can use the indented code after except to flag up where the error in your code occurs.
Chapter 6
Loops
Loops are an efficient, and concise, way of executing a piece of code multiple times. Consider the problem
from section 3.3 of multiplying each element of a list by a constant N. Using the multiplication syntax the
list was simply repeated N times and it only worked when N was an integer.
Code
MyList = [1.4,2.3,9.5,3.6,11.0]
MyList = 2*MyList
print "2 times MyList = ", MyList
Output
2 times MyList = [1.4, 2.3, 9.5, 3.6, 11.0, 1.4, 2.3, 9.5, 3.6, 11.0]
Here N=2 was used. To multiply each element individually in the list by N, and keeping the length of the
array the same, we can index each element manually on successive lines and multiply it by N,
Code
N = 2
MyList = [1.4,2.3,9.5,3.6,11.0]
MyList[0] = N*MyList[0]
MyList[1] = N*MyList[1]
MyList[2] = N*MyList[2]
MyList[3] = N*MyList[3]
MyList[4] = N*MyList[4]
Output
MyList = [2.8, 4.6, 19.0, 7.2, 22.0]
Each element of MyList is accessed individually and multiplied by N1 . The new value then replaces the old
value in the list. Notice that lines 4-8 are exactly the same except for the value of the index. If there was
a way of iterating through the indices of MyList then we would only have to write lines 4-8 once. This is
where the ability to loop through the different indices would save a lot of lines of code, especially if the list
had many more than 5 elements.
1 Remember that the first element of the list has an index of zero.
21
CHAPTER 6. LOOPS 22
NOTE: Put a colon after variable and indent the code to be executed.
Python will take the first entry in variable , assign the value of the entry to element and then execute the
code indented after the colon. It will then repeat this for every entry in variable , assigning the value to
the variable element and executing the indented code.
Let us use a for loop to print out all of the entries in a list.
Code
x = [6.2,9.3,12.0,1.4]
for i in x:
print i
Output
6.2
9.3
12.0
1.4
Here i has been used as the element to be assigned to each value in the list. You can use any valid Python
variable name instead of i and you will get the same output.
Code
x = [6.2,9.3,12.0,1.4]
for cow in x:
print cow
Output
6.2
9.3
12.0
1.4
As a general rule it is better to use more appropriate names such as i,j,n or a name that more clearly
represents what the element represents.
for i in range(0,5):
print "Element ", i, " of y = ", y[i]
CHAPTER 6. LOOPS 23
Output
Element 0 of y = 1
Element 1 of y = 3
Element 2 of y = 6
Element 3 of y = 10
Element 4 of y = 15
Recall that range(0,5) (the upper limit is 5 as this is the length of the list y, i.e. the number of elements
that it has.) will produce the list [0,1,2,3,4]. For each element in this list i takes on its value. We then
use this value as the index for accessing the different elements of our list y.
let us now go back to the example of multiplying each element in a list by 2. We will attempt to do this with
a for loop. This will require use of indented code to do the re-assignment process of updating the list y.
Code
N = 2
MyList = [1.4,2.3,9.5,3.6,11.0]
for i in range(0,5):
MyList[i] = N*MyList[i]
Output
MyList = [2.8, 4.6, 19.0, 7.2, 22.0]
We have successfully multiplied each element of MyList by 2. In this example the range function was ex-
plicitly given the upper limit of 5. However, what if we do not know the length of MyList? We can use the
len function to find the length of the list we are iterating over and pass this value to the range function.
Code
N = 2
MyList = [1.4,2.3,9.5,3.6,11.0]
for i in range(0,len(MyList)):
MyList[i] = N*MyList[i]
Output
MyList = [2.8, 4.6, 19.0, 7.2, 22.0]
This adds more flexibility to using the for control structure. The use of len guarantees that we access all
of the elements in the list and that we stop attempting to index at the right point in the list. If we were
to guess an upper limit that was larger than the highest index in MyList Python would raise an error and
crash.
CHAPTER 6. LOOPS 24
The function returns a list of integers with the first value start, the end value being one less than stop and
in increments of step. Start is 0 by default and step is 1 by default. All values passed to the range functions
MUST be integers. Here are some examples of using range to generate lists.
Code
x = range(11)
print "x = ", x
y = range(0,11)
print "x = ", y
z = range(0,11,1)
print "z = ", z
a = range(3,10,2)
print "a = ", a
Output
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
z = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = [3, 5, 7, 9]
List x shows that passing range only one argument tells the function where to stop; the start and step
are set to their default values of 0 and 1 by Python. List y shows that passing two arguments defines the
(start,stop) values in that order, with the default increment of 1 being automatically implemented. List
z shows that you can also produce the same array by specifying all three values. Finally list a is an example
where the start and step values are non-default values. Note that for the first three examples 11 was
specified as the stop value and it was NOT included in any of the lists.
for i in x:
for j in y:
print i,"+",j," = ", i+j
CHAPTER 6. LOOPS 25
Output
1 + 10 = 11
1 + 20 = 21
1 + 30 = 31
2 + 10 = 12
2 + 20 = 22
2 + 32 = 32
3 + 10 = 13
3 + 20 = 23
3 + 30 = 33
As long as condition is True (this is similar to if statements) the indented code will run.
Consider the example of counting from 1-5 and printing the values to screen.
Code
x = 1
while x < 6:
print x
x = x + 1
print "Finished Counting"
Output
1
2
3
4
5
Finished Counting
We have to create the variable x so that we have a variable to use in the condition. We set the value of x
to 1 as this is where we want to start counting. Python then checks the condition when it encounters the
while on line 3 of the code. As 1<6 the indented code is executed; the value of x is printed to the screen
and the variable is then increased by 1 to represent the next step in counting. Having reached the end of the
indented code, Python then looks back at the condition to see if it is still True. x is now equal to 2, which is
less than 6, so the indented code is executed again. This process is repeated until x equals 6, at which point
the condition x<6 is False and the loop is escaped. Python then goes to the line after the end of the loop
and prints Finished Counting.
2 Strictly speaking pulling the power cable out of the PC would kill the loop but that’s a rather extreme measure to take.
Let us write the previous example of counting from 1-5 using a break statement. We will use an if statement
to determine when x>5 and then use the break statement to end the loop.
Code
while True:
print x
x = x + 1
if x > 5:
break
print "Finished Counting"
Output
1
2
3
4
5
Finished Counting
We used True after the while command as this will ensure that the loop will keep on running until it is
broken by the user. We ended up with the same output as the previous example where the condition of x<6
was explicitly stated after the while command.
The four different loop structures are: a general for loop; a for loop with explicit indexing and using
the range function; a while loop with an if condition to break; and a while loop with the condition explic-
itly stated.
3 There will be differences in efficiency (i.e. how quickly the task is performed). However, for basic programming, this is not
Code
#generate list
z = [6.2,4.6,8.2,9.3,9.1]
Code
z = [6.2,4.6,8.2,9.3,9.1]
length = len(z)
Total = 0
for i in range(0,length):
Total = Total + z[i]
Code
z = [6.2,4.6,8.2,9.3,9.1]
length = len(z)
Total = 0
while True:
Total = Total + z[index]
index = index + 1
if index == length:
break
Code
z = [6.2,4.6,8.2,9.3,9.1]
length = len(z)
Total = 0
index = 0
Output
Sum of list z = 37.4
For a program to be useful we need to be able to provide it with information and extract its output in a form
that is convenient to work with. We have already come across the print statement which provides us with
a way of extracting values from a program, but this is not always ideal, especially if we expect there to be a
lot of data or if we would like to be able to save the output without having to copy and paste it every time.
Hence it is useful to be able to save the data to a file directly. As well as getting output from programs it is
also useful to be able to give them information while they are running. This means we can write one general
program and use it for a whole range of parameters without ever needing to change the source code1 . As
with output there are two main ways of providing input: from the screen or from a file.
Output
Enter something for raw input: 6
You entered 6 Which is a <type ’str’>
Enter something for input: 6
You entered 6 Which is a <type ’int’>
29
CHAPTER 7. INPUT AND OUTPUT 30
Output
Enter something for raw input: 6.7
You entered 6.7 Which is a <type ’str’>
Enter something for input: 6.7
You entered 6.7 Which is a <type ’float’>
Output
Enter something for raw input: [1,2,3,4]
You entered [1,2,3,4] Which is a <type ’str’>
Enter something for input: [1,2,3,4]
You entered [1, 2, 3, 4] Which is a <type ’list’>
Output
Enter something for raw input: ”Hello”
You entered "Hello" Which is a <type ’str’>
Enter something for input: ”Hello”
You entered Hello Which is a <type ’str’>
Output
Enter something for raw input: Hello
You entered Hello Which is a <type ’str’>
Enter something for input: Hello
Traceback (most recent call last):
File "Input And Output.py", line 4, in <module>
x=input("Enter something for input: ")
File "<string>", line 1, in <module>
NameError: name ’Hello’ is not defined
In general it is better to use raw input to avoid errors like the one shown above, because it allows the
programmer to make decisions about how the input should be used. For example if you wanted the user to
enter a float you could take the string from raw input and try to convert it to a float. If this fails you could
print a message or even give the user another try. Below is an example of how to do this.
Code
while(True):
data=raw input("Enter a number: ")
try:
x=float(data)
print "Float accepted, x = ",x
break
except:
print "You must enter a float!"
Output
Enter a number: NO
You must enter a float!
Enter a number: I don’t want to!!!
You must enter a float!
Enter a number: OK then, next time.
You must enter a float!
Enter a number: 4.5
Float accepted, x = 4.5
CHAPTER 7. INPUT AND OUTPUT 31
Just like any other variable you can have as many files open as you want, you can even open the same file as
many times as you like for reading, although files which are opened for writing can only be opened once.
One more important thing to mention at this stage is the way in which the interpreter looks for files.
If only the file name is given then the interpreter will look for/create the file in the same directory(folder) as
the source code. This is usually the best place to keep any data files as it avoids possible complications5 .
Input File
Some thing on line one
Some more text on line 2
Even more on line 3
And so on
And so on
Until line 6 which is the last line
3 There are different ways of doing this, but for simplicity only one method will be presented here.
4 There are more options such as a to append and the file can even be opened in binary mode (plain text mode is the default
mode) if it is not a plain text file, but r and w are the most common and the only ones you are likely to need so we will restrict
ourselves to using them.
5 If you don’t want to keep the data files in the same directory as the source code then you must specify the absolute (starting
from the highest level directory e.g. / in Unix and Mac OSX or C:\in windows) or relative (to the source code directory) path
to the location of the data file.
CHAPTER 7. INPUT AND OUTPUT 32
Output
Some thing on line one
And so on
And so on
Note that a blank line has been printed in between the lines of the output. This is because the input file, like
almost all text files, contains invisible new line characters6 which make the interpreter print another return
in addition to the one which is printed by default.
Firstly it can be useful, especially when you want to print nicely formatted output, to remove certain char-
acters, such as newline (\n) characters, from a string. As the above example shows these lead to unwanted
blank lines. Specified characters or strings can be removed using the strip method as in the example below.
Code
input file=open("My input file.txt","r")
for line in input file:
print line.strip("\n")
Input File
Some thing on line one
Some more text on line 2
Even more on line 3
And so on
And so on
Until line 6 which is the last line
Output
Some thing on line one
Some more text on line 2
Even more on line 3
And so on
And so on
Until line 6 which is the last line
Another thing which is especially useful is the split method. This allow us to split a string into a list
of smaller strings by specifying a special character (or sub-string though a single character is often better)
6 In Python we denote these as \n
CHAPTER 7. INPUT AND OUTPUT 33
as a separator (commas, spaces and tabs are popular choices). This is especially useful when dealing with
numerical data which we may want in multiple columns e.g. x and y data to plot. In the example below the
split method is used to enable the program to read in x and y data from a comma separated values file and
save it in two lists.
Code
data file=open("xy data.csv","r")
x=[] #empty lists to store the data in
y=[]
for data point in data file:
data point=data point.strip("\n")
split data=data point.split(",")
print data point, " becomes ", split data
x.append(float(split data[0]))
y.append(float(split data[1]))
print "x = ", x
print "y = ", y
Input File
1,2
2,4
3,6
4,8
5,10
Output
1,2 becomes [’1’, ’2’]
2,4 becomes [’2’, ’4’]
3,6 becomes [’3’, ’6’]
4,8 becomes [’4’, ’8’]
5,10 becomes [’5’, ’10’]
x = [1.0, 2.0, 3.0, 4.0, 5.0]
y = [2.0, 4.0, 6.0, 8.0, 10.0]
In this example the string which contains each line is first overwritten with the line without the \n character
and then split. In the list the first element ([0]) is the first column and so is converted to a float and added
to the list of x values and the second element ([1]) is the second column. This is added to the list of y
values.
Code
output file=open("My output file.txt","w")
for i in range(0,10,1):
output file.write(str(i))
Output File
0123456789
There are some important differences between print and write however. Firstly write does not automat-
ically add new lines. This is clear from the example above. You have to put these in yourself if you want
them, and secondly unlike print you cannot use other types such as integers and floats and you cannot pass
write more than one argument; it only accepts one string so if you need to output more you have to add
strings together or use multiple write commands. The example below uses both.
Code
output file=open("My output file.txt","w")
for i in range(0,10,1):
output file.write(str(i)+"^2 = "+str(i**2)+"\n")
output file.write("This is the end of the file\n")
Output File
0^2 = 0
1^2 = 1
2^2 = 4
3^2 = 9
4^2 = 16
5^2 = 25
6^2 = 36
7^2 = 49
8^2 = 64
9^2 = 81
This is the end of the file
There are several advantages to closing files in this way. Firstly it means there is less chance of the file being
damaged accidentally at a later stage in the program. It also helps to give your program structure; it will
be much clearer which part reads the file and which part does some other processing if the file is closed. It
allows you to reopen the file with the same variable name, so you can get back to the beginning, or reuse
the name for something else if you wish. It allows other programs which might want to access the file to
CHAPTER 7. INPUT AND OUTPUT 35
access it. And finally the act of closing the file makes the computer write the data to the disk7 so it will be
available for other programs to use or for the same program to reopen later on.
7 Using the write method does not guarantee that the file will be written to the disk until the file is closed or the program
Functions
In the previous sections we used functions extensively (e.g. range,open,len...). Now we will have a look at
how to define some of our own and have a look in a little more detail at how functions work in general.
Defining functions makes absolutely no difference to how the code runs. The computer runs the code just
as it would if everything was in one long program. However it can make a great deal of difference to the
programmer as choosing the right function definitions can save you from repeating the same lines of code
over and over again and make your programs much shorter and easier to read. You may also find that a
function you wrote for one program is useful in another and so you don’t have to go to the effort of writing
and debugging it twice.
My function()
Output
Hello this is My function!
The main thing to notice here is that the code within the function is indented. This means that the interpreter
will ignore it until the function is called. The call to the function is not indented and so the interpreter calls
the function. In Python functions can be declared anywhere. You can even declare functions within functions,
and the interpreter uses the indentation to work out which bits to run and which bits to save for later. Having
said this declaring functions all over the place makes your code very hard to read and may lead to errors
which could have easily been avoided. Many programmers declare all the functions they need at the top of
the program. That way the bit of code that the interpreter executes is all in one place and you can be sure
that all your functions are declared before they are used, as they must be.
36
CHAPTER 8. FUNCTIONS 37
Output
Calling the function
a = 10
b = 6
c = 8
The key to this is in the function definition (def My function(a,b,c)). Here we have told the interpreter
the names of the variables we want to use in the function and the order in which they will be passed to the
function. The order is very important as this is how the interpreter knows which value to assign to each
variable. At this stage all of the arguments the function can take must be passed to it when it is called. Not
doing so will cause an error. We can make arguments optional by providing a default value, to be used if no
argument is given. We do this in the function definition as in the following example.
Code
def My function(a,b,c=-1):
print "a = ", a
print "b = ", b
print "c = ", c
Output
Call 1
a = 10
b = 6
c = 8
Call 2
a = 10
b = 6
c = -1
As before the order of the arguments is crucial, and with this in mind, it should be clear that the optional
CHAPTER 8. FUNCTIONS 38
If we need a little more freedom to put the arguments in whatever order we like we can pass the func-
tion key word arguments or kwargs instead. However we do have to do slightly more work to get the values
out. In the function we have to use the kwargs.get method to get the value of a kwarg given its name and
when we call the function we have to name the variables as we pass them. Here is an example
Code
def My function(**kwargs): #the *’s are important
print "a = ", kwargs.get("a") #the name must be a string
print "b = ", kwargs.get("b")
print "c = ", kwargs.get("c")
Output
Call 1
a = 10
b = 6
c = 8
Call 2
a = 10
b = 6
c = 8
There are a few things to note here which may cause difficulties. Firstly, if you ask for a kwarg that hasn’t
been passed then its value is none. Secondly, if you pass a kwarg that the function doesn’t need it will be
ignored.
Of course it is possible to mix args and kwargs and optional arguments and even set the default values
of kwargs, although the kwargs must come last. Below is an example of this
Code
def My function(a,b=-1,c=None,**kwargs):
print "a = ", a
print "b = ", b
print "c = ", c
print "x = ", kwargs.get("x")
print "y = ", kwargs.get("y","-100")
print "z = ", kwargs.get("z","z was not given")
Output
Call 1
a = 10
b = 6
c = 8
x = 50
y = 13
z = 99
Call 2
a = 10
b = -1
c = None
x = 50
y = 13
z = 99
Call 3
a = 10
b = 6
c = 8
x = 50
y = 99
z = 13
Call 4
a = 10
b = 6
c = 8
x = 50
y = -100
z = z was not given
Call 5
a = 10
b = -1
c = None
x = 50
y = -100
z = z was not given
Both arguments and kwargs can be of any type, even lists, but it is important that they are compatible with
the function. For example, a function that performs mathematical operations on its arguments can only be
passed floats or integers for the arguments upon which the mathematical operations are to be performed.
Code
def Higest Common Factor(a,b):
hcf=1
for i in range(2,min([a,b])+1,1):
if(a%i==0 and b%i==0):
hcf=i
return hcf
x=12
y=28
z=Higest Common Factor(x,y)
print "The highest common factor of ", x, " and ", y, " is ",z
Output
The highest common factor of 12 and 28 is 4
Here we can see that we can store the output of a function that returns only one variable in the same way as
we would assign any other variable with the variable name on the left hand side and the value, in this case
the value returned by the function, on the right. But Python allows us to do more than that. We can also
return multiple variables and even different types of variables. It does this by returning a list (technically
it’s a tuple), which is used to assign values to multiple variables, as shown in the example below.
Code
def stats(a):
maxa=max(a)
mina=min(a)
rangea=max(a)-min(a)
meana=sum(a)/len(a)
outputa="There were "+str(len(a))+" numbers."
return maxa,mina,rangea,meana,outputa
data=[1.1,2.2,3.3,4.4,5.5]
mx,mn,r,av,out=stats(data)
print out
print "Max = ", mx
print "Min = ", mn
print "Range = ", r
print "Average = ",av
Output
There were 5 numbers.
Max = 5.5
Min = 1.1
Range = 4.4
Average = 3.3
Note that once again, as with passing arguments, the order of the variables is crucial. Variables are returned
in the same order as they appear after the return statement. With the exception of only having one variable
to assign the return values to having the wrong number of variables will cause an error. If only one variable
is on the left hand side of the equals sign then it is assigned as a list containing all of the return values, as
shown below:
CHAPTER 8. FUNCTIONS 41
Code
def stats(a):
maxa=max(a)
mina=min(a)
rangea=max(a)-min(a)
meana=sum(a)/len(a)
outputa="There were "+str(len(a))+" numbers."
return maxa,mina,rangea,meana,outputa
data=[1.1,2.2,3.3,4.4,5.5]
list out=stats(data)
print list out
Output
(5.5, 1.1, 4.4, 3.3, ’There were 5 numbers.’)
Finally, since it was mentioned earlier that it is possible to have multiple return statements in one function
here is an example of where that might be appropriate.
Code
from math import sqrt #this will be covered later
ans=Cleaver sqrt(36)
print "The square root of 36 is ", ans
ans=Cleaver sqrt(-36)
print "The square root of -36 is ", ans
Output
The square root of 36 is 6.0
The square root of -36 is Impossible
by the function name before we make any changes. Here are some examples of these rules in action.
Code
def f():
print "f sees a = ", a
Output
the main function sees a = 1
f sees a = 1
Code
def f():
print "f sees a = ", a
def g():
a=2
print "g sees a = ", a
a=1
print "the main function sees a = ", a
f()
g()
print "After g() has run:"
print "the main function sees a = ", a
f()
g()
Output
the main function sees a = 1
f sees a = 1
g sees a = 2
After g() has run:
the main function sees a = 1
f sees a = 1
g sees a = 2
Code
def f():
print "f sees a = ", a
a=1
print "the main function sees a = ", a
f()
a=a+10
print "After a change by the main function:"
print "the main function sees a = ", a
f()
CHAPTER 8. FUNCTIONS 43
Output
the main function sees a = 1
f sees a = 1
After a change by the main function:
the main function sees a = 11
f sees a = 11
Code
def f():
print "f sees a = ", a
def g():
global a #note that a has been declared global
a=2
print "f sees a = ", a
a=1
print "the main function sees a = ", a
f()
g()
print "After g() has run:"
print "the main function sees a = ", a
f()
g()
Output
the main function sees a = 1
f sees a = 1
g sees a = 2
After g() has run:
the main function sees a = 2
f sees a = 2
g sees a = 2
Code
def f():
a=a+1 #this will cause an error
print "f sees a = ", a
a=1
print "the main function sees a = ", a
f()
CHAPTER 8. FUNCTIONS 44
Output
the main function sees a = 1
Traceback (most recent call last):
File "Functions.py", line 163, in <module>
f()
File "Functions.py", line 158, in f
a=a+1 #this will cause an error
UnboundLocalError: local variable ’a’ referenced before assignment
Here the final example fails because we are trying to make a change to the variable a within the function.
This causes the interpreter to create a new local variable called a, but this variable is used in the calculation
before it has been assigned a value, hence the error message.
With this in mind one may ask: What happens to the variables we pass to functions? Well this depends on
their type. If a single value such as a float, integer or string is passed then it is treated as a local variable
within the function and what happens in the function has no effect on the value in other parts of the program.
However if a list is passed then the function can change the elements and they will remain changed even
when the function has ended. This can be seen in the example below:
Code
def f(n,l):
n=n+10
for i in range(0,len(l),1):
l[i]=l[i]+10
print "f sees n = ", n, " and l = ", l
l=[1,2,3]
n=4
print "the main function sees n = ", n, " and l = ", l
f(n,l)
print "now the main function sees n = ", n, " and l = ", l
Output
the main function sees n = 4 and l = [1, 2, 3]
f sees n = 14 and l = [11, 12, 13]
now the main function sees n = 4 and l = [11, 12, 13]
Code
def green bottles(n):
if n>0:
n=n-1
print "and if one green bottle should accidentally fall"
print "there’d be ",n," green bottle(s) standing on the wall"
green bottles(n) #here is the recursive call to the function
b=10
print "there were ",b," green bottle(s) standing on the wall"
green bottles(b)
Output
there were 10 green bottle(s) standing on the wall
and if one green bottle should accidentally fall
there’d be 9 green bottle(s) standing on the wall
and if one green bottle should accidentally fall
there’d be 8 green bottle(s) standing on the wall
and if one green bottle should accidentally fall
there’d be 7 green bottle(s) standing on the wall
and if one green bottle should accidentally fall
there’d be 6 green bottle(s) standing on the wall
and if one green bottle should accidentally fall
there’d be 5 green bottle(s) standing on the wall
and if one green bottle should accidentally fall
there’d be 4 green bottle(s) standing on the wall
and if one green bottle should accidentally fall
there’d be 3 green bottle(s) standing on the wall
and if one green bottle should accidentally fall
there’d be 2 green bottle(s) standing on the wall
and if one green bottle should accidentally fall
there’d be 1 green bottle(s) standing on the wall
and if one green bottle should accidentally fall
there’d be 0 green bottle(s) standing on the wall
This is essentially doing the same job as a loop would, but by using functions. This kind of behaviour can
be especially useful when we are trying to improve an initial guess to reach some desired accuracy, using
iteration. The following example finds a point at which the lines with equations y = x2 and y = x + 10
intersect to a given accuracy.
Code
from math import sqrt #this will be covered later
def solve(x,**kwargs):
a=kwargs.get("acc",0.1)
if abs(x**2-x-10)>a:
x=sqrt(x+10)
print "x = ", x
solve(x,acc=a)
guess=10
solve(guess,acc=0.001)
CHAPTER 8. FUNCTIONS 46
Output
x = 4.472135955
x = 3.80422606518
x = 3.71540388991
x = 3.70343136698
x = 3.70181460462
x = 3.70159622388
Having already written some functions we are well on the way to creating our first module. All we have left
to do is gather them together and save them in a Python script file of their own. For the purposes of this
example we will put the following functions in a file called MyModule.py saved in the same directory as the
source code for the main program. Any name will do as long as there are no spaces or special characters in
it.
Code
def Higest Common Factor(a,b):
hcf=1
for i in range(2,min([a,b])+1,1):
if(a%i==0 and b%i==0):
hcf=i
return hcf
def stats(a):
maxa=max(a)
mina=min(a)
rangea=max(a)-min(a)
meana=sum(a)/len(a)
outputa="There were "+str(len(a))+" numbers."
return maxa,mina,rangea,meana,outputa
Now if we want to use some of these functions in a program we simply need to tell the interpreter where to
1 Actually, being object oriented, Python goes one further still allowing us to organise groups of functions and variable types
into classes that enable us to access them in a very convenient way. However this is well beyond the scope of this document.
CHAPTER 8. FUNCTIONS 47
find the code. We do this using the import statement followed by the name of the module2 (this is just the
file name without the .py)3 . This is usually done at the very top, but doesn’t have to be as long as it come
before the first use of any of the functions. Then when we need to use a function we tell the interpreter that
we want it to use the one from the module we have just imported by using the module name followed by the
function name.
Code
import MyModule #note the lack of the .py
x=12
y=28
z=MyModule.Higest Common Factor(x,y)
print "The highest common factor of ", x, " and ", y, " is ",z
Output
The highest common factor of 12 and 28 is 4
This method allows us to use functions of the same name from different modules which can sometimes be
useful. However there are some tricks which can save a great deal of typing. First of all when the module is
first imported we can choose the name by which we wish to refer to it using the as statement.
Code
import MyModule as mm
x=12
y=28
z=mm.Higest Common Factor(x,y)
print "The highest common factor of ", x, " and ", y, " is ",z
Output
The highest common factor of 12 and 28 is 4
Secondly if we know we will only need a limited number of functions we can import them by name and drop
the module name altogether. However this does limit us somewhat if we want to use a function with the
same name from two different modules.
Code
from MyModule import Highest Common Factor
x=12
y=28
z=Higest Common Factor(x,y)
print "The highest common factor of ", x, " and ", y, " is ",z
Output
The highest common factor of 12 and 28 is 4
This is what we did with sqrt from the math module in some of the earlier examples. If more than one
function is to be imported they can be separated by commas. We can even combine the two commands.
2 By default the interpreter will look in two places. Firstly its root folder where the inbuilt modules are and then in the same
folder as the source code. If you want to put modules else where you need the full path.
3 You may notice that a .pyc file appears in the directory, this contains a version of the module which has been compiled into
a set of much simpler instructions which the interpreter can run much faster than a standard .py file.
CHAPTER 8. FUNCTIONS 48
Code
from MyModule import Highest Common Factor as hcf
x=12
y=28
z=hcf(x,y)
print "The highest common factor of ", x, " and ", y, " is ",z
Output
The highest common factor of 12 and 28 is 4
And again more functions/variables can be imported by separating the names by commas.
Code
from MyModule import Higest Common Factor as hcf,stats as S
8.7 Doc-Strings
All of this organisation make it much easier for the programmer to see what is going on. Unfortunately it’s
not much help to someone who doesn’t know Python who just wants to use one or two functions. Fortunately
help (the help function) is at hand for just this kind of situation. If you try calling help with the name of
one of the standard functions you will see it prints lots of useful information. For example:
Code
help(abs)
Output
Help on built-in function abs in module builtin :
abs(...)
abs(number) -> number
Nearly all Python functions have this information. It’s part of what makes Python so user friendly, so we
should probably add it to our functions, in case we want to use them again later and we have forgotten how
they work. This is done using doc-strings, these can be thought of as being similar to comments, in that they
don’t change how the code runs (the computer doesn’t even see them), except that they will be reproduced
on the screen if the help function is used. Doc-Strings can span multiple lines and they are reproduced
just as they look in the source code (unless they are too wide for the screen of course). To begin and end
doc-strings we use triple, double quotes (""") and they always go just under the function definition. Here is
an example.
CHAPTER 8. FUNCTIONS 49
Code
def Highest Common Factor(a,b):
"""This function finds the highest common factor of two numbers.
It takes exactly two arguments a and b (which must be ints).
It has no optional arguments or kwargs.
It returns one integer which is the highest common factor."""
hcf=1
for i in range(2,min([a,b])+1,1):
if(a%i==0 and b%i==0):
hcf=i
return hcf
Output
Help on function Highest Common Factor in module main :
Highest Common Factor(a, b)
This function finds the highest common factor of two numbers.
It takes exactly two arguments a and b (which must be ints).
It has no optional arguments or kwargs.
It returns one integer which is the highest common factor.
Chapter 9
As well as the standard functions Python also has a vast range of libraries full of useful functions. Many
of these libraries have been optimised for performance1 and so allow us to perform calculations much faster
than we could do by using the standard methods.
Since the array of libraries is vast and each library can itself contain many many functions, we will not
try to explain them all here. Instead we will give a brief overview of some of the libraries that are particu-
larly useful in Physics and have a look at one or two of their functions, in the hope that this will give you
confidence to explore unfamiliar libraries and functions for yourself as and when you need them.
Unfortunately since different functions are contributed by different people most libraries have no standard
format for how functions should look or behave, and there is certainly no reason to believe that the way
in which functions work in one library is the same as they do in another. However nearly all of them have
doc-strings to help us and we can even use help with the module name in most cases to get an overview of
the functions. Also there is always online documentation which is typically very good. Usually the doc-string
for a function will tell you what arguments the function takes, what types they are and what they mean and
also tells us what, if anything, the function returns and how we should interpret it. A good understanding
of the terminology around using functions can often been all you need.
9.1 math
Let us start by having a look at the math library which comes with almost every Python distribution. This
contains all the standard mathematical functions, like: square root (which we’ve already seen), trigonometric
functions, logarithms, exponentials, constants like pi and so on. We can import it just as we would any
module, as we did in the section on functions. Typically the functions in this library take one float as an
argument and return one float, just like their counterparts on a scientific calculator. This library only works
with real numbers. To deal with complex numbers you can use the cmath library. One thing to be careful of
is that all the trigonometric functions work in radian mode so if you want to use degrees you need to convert.
9.2 numpy
numpy is a slightly more specialised maths library for performing highly optimised high performance calcula-
tions on large amounts of data using a special type of variable called a numpy array. These look very much
like the lists we are familiar with, but there are some special properties worth baring in mind. Firstly, all
the variables in a numpy array must be of the same type, usually floats. Secondly, and our reason for using
1 Many are written in compiled languages like C and FORTRAN, which produce binary code and achieve maximum perfor-
50
CHAPTER 9. LIBRARIES (IN BRIEF) 51
them, we can tell the interpreter to perform a mathematical operation on every element in the array just by
performing that operation on the array. For example
Code
import numpy as np
l=[1.0,2.0,3.0]
a=np.array(l)
print "l = ", l
print "a = ", a
print "2a = ", 2*a
Output
l = [1.0, 2.0, 3.0]
a = [ 1. 2. 3.]
2a = [ 2. 4. 6.]
This is also true if we pass a numpy array to a function. The next important difference is the way in which
we index numpy arrays. For the most part they are the same as lists, and all the same indexing conventions
apply but we do get one powerful new tool if we are willing to change our notation slightly. If you want to
make a list of lists (i.e. a two dimensional list) then we can easily access the rows2 , but there is no convenient
way to extract one column. In a numpy array this is very easy to do as the next example will illustrate.
However, for this to work we need to index the array like this: [r,c] (r is the row index and c the column
index), not [r][c] (this will not cause an error, it will just give us row c rather than column c).
Code
import numpy as np
l=[[11.0,12.0,13.0],[21.0,22.0,23.0],[31.0,32.0,33.0]]
lrow2=l[1]
a=np.array(l)
arow2=a[1,:]
acolumn2=a[:,1]
print "l = ", l
print "lrow2 = ", lrow2
print "a = ", a
print "arow2 = ", arow2
print "acolumn2 = ", acolumn2
Output
l = [[11.0, 12.0, 13.0], [21.0, 22.0, 23.0], [31.0, 32.0, 33.0]]
lrow2 = [21.0, 22.0, 23.0]
a = [[ 11. 12. 13.]
[ 21. 22. 23.]
[ 31. 32. 33.]]
arow2 = [ 21. 22. 23.]
acolumn2 = [ 12. 22. 32.]
As you can see from the example numpy arrays also print out in a much nicer format.
As well as allowing us to create numpy arrays, which as we’ve seen can be very useful, numpy also pro-
vides us with special versions of the standard maths functions provided by the math library, which are
specially designed to work on numpy arrays and are highly optimised for performing calculations on very
large amounts of data efficiently. These are called just like any other maths functions except we have a
choice: we can either pass and return a single float or we can do exactly the same with a numpy array full
2 Python used a row major indexing system which mean in two dimensions we think of the first index as the row index.
CHAPTER 9. LIBRARIES (IN BRIEF) 52
of as may floats as we like (this is where we will really notice the performance increase).
9.3 matplotlib
matplotlib is a very large library and we will only look at one of its modules called pyplot. As the name
suggests this is for potting data. This library provides methods for plotting all sorts of graphs, but most of
them take the same form so we will only look at a simple (x, y) plot. To do this we first need to call plot
and give it two lists or numpy arrays for the x and y values. These must be the same length (you cannot
plot functions like this, you have to use the function to make the y list for a given x list). Then we call show.
This will open a window with the plot in it.
Code
import matplotlib.pyplot as plt
x=[1.0,2.0,3.0,4.0,5.0]
y=[2.0,4.0,5.0,6.0,7.0]
plt.plot(x,y)
plt.show()
Output
2
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
If you want to save the plot rather than make it appear on the screen you just need to swap the show function
for the savefig function and give it a string containing the file name (including extension) that you want it
to be saved as. If we want to change the style of the plot we can do this by adding an option argument with
a style code for the style. There are also a range of other commands that allow us to set the axis labels and
plot title and add a legend. We can also add multiple data sets to one plot by repeatedly calling the plot
function, before we call show. To produce multiple plots we call show after every plot command (or every
group of plot commands). Here is a more complicated example:
CHAPTER 9. LIBRARIES (IN BRIEF) 53
Code
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,2*np.pi,np.pi/100) #numpy version of range
for n in range(1,6):
y=np.sin(n*x)
plt.plot(x,y)
plt.title("Plot Of A Range Of sin(n*x) for n=1,2,3,4,5")
plt.xlabel("x")
plt.ylabel("sin(n*x)")
plt.legend(["n=1","n=2","n=3","n=4","n=5"])
plt.show()
Output
0.0
0.5
1.00 1 2 3 4 5 6 7
x
9.4 scipy
We will conclude this section just by mentioning one other library which is likely to be useful in Physics.
scipy has a huge range of highly optimised functions for common mathematical algorithms such as fitting of
general functions with multiple fit parameters, root finding, creating interpolating functions and numerical
integration and differentiation. scipy also contains values for many physical constants.
Chapter 10
Provided in this section is a list of useful functions that you may find useful to use in your own programs.
Convert to Syntax
string str()
float float()
integer int()
Function Returns
len() Length (number of elements)
min() Minimum value present
max() Maximum value present
sum() Sum of each entry
54