Computing 1 Python Tutorial - Leeds

Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

Computing 1: Python Tutorial

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

2 Basic Variables And Operators 5


2.1 Floats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2.1 The Modulo Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4 General Rules For Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

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

4 Errors And Debugging 13


4.1 The Print Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.2 Some Common Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4.3 General Advice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

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

7 Input And Output 29


7.1 Reading From The Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
7.2 Opening Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
7.3 Reading files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
7.3.1 Some More Properties Of Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
7.3.2 A Slightly Subtle Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
7.4 Writing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
7.5 Closing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

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

9 Libraries (In Brief ) 50


9.1 math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
9.2 numpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
9.3 matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
9.4 scipy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

10 Useful Functions And Concluding Remarks 54


10.1 Converting Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
10.2 Useful Functions For Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
10.3 Concluding Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Chapter 1

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.1 Motivation For Computer Programming


Some equations cannot be solved analytically, but can be solved iteratively. This would likely to take a long
time on paper - computers can speed this up. Computers can perform billions1 of calculations per second. So
if you want to perform the same calculation many times a computer is much more efficient - and ultimately
saves you time. And computers do not make "silly" mistakes, whereas humans make mistakes all of the
time.

1.2 How To Use This Document


We actively promote you to copy out examples into a python file (using the .py extension) and run the codes
for yourselves - this will give you practice at writing the language and making you more comfortable with the
basic concepts of programming. If you are viewing the pdf version of this document on a PC we STRONGLY
advise that you DO NOT copy and paste code directly into a Python file. This is for two reasons: sometimes
the character encoding does not match the editor and the code will not run; secondly, the best way to learn
to computer program is to sit down and do it for yourself. Writing out code yourself will help you to become
familiar with the syntax (or grammar) of the language and will help you to understand what is going on -
understanding how things work is just as important as making them work.

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/

1.4 Other Useful Resources


In this document we have tried to include everything we think you will need to understand the basics of
programming in Python and most of the things you will need for the course. However, as stated in the
previous section, it does not cover all of the features Python has to offer and there are many other useful
1 Yes, billions, this is not an exaggeration!

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.

Python Homepage: http://www.python.org/


Interactive Python: http://www.interactivepython.org/
Python Tutor: http://www.pythontutor.com/
Python Course: http://www.python-course.eu/
Tutorials Point: http://www.tutorialspoint.com/python/
Computer Sciences Circles: http://cscircles.cemc.uwaterloo.ca/
Software Carpentry: http://software-carpentry.org/
Hands-on Python Tutorial: http://anh.cs.luc.edu/python/hands-on/index26.html

Many of the libraries used later on have their own web pages and documentation, which you may find useful
when dealing with them.

1.5 Running Python At Home


Most versions of Linux and Mac OSX already have python installed2 , so you won’t need to do anything. In
such cases you can just run your code from the terminal by typing python and the name of your Python
source code file. If you want a nice graphical interface where you can edit and run your code all in one place
there are many options, but two popular choices are: TextWrangler which can be downloaded for free on the
Mac App Store or on Linux Geany is free to install from the package manager. Both of these have syntax
highlighting and allow you to run your code from within the editor.

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

Basic Variables And Operators

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.

• variable names are case sensitive.

• 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’>

As you can see the variable d is a 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.

2.2.1 The Modulo Operator


It is some times useful to find the remainder from integer division. You can do this using the modulo, %,
operator.
Code
print "1%3 = ", 1%3
print "5%3 = ", 5%3
print "3%3 = ", 3%3

Output
1%3 = 1
5%3 = 2
3%3 = 0

2.3 String Operations


In terms of basic operations you can only add and multiply strings
Code
print "Hello "+"World"
print 3*"Hello "

Output
Hello World
Hello Hello Hello

2.4 General Rules For Variables


Variables are assigned right to left
Code
x=7.0

in this example the number 7.0 is assigned to the variable x.

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.

3.1 Creating Lists


The simplest list you can create is an empty one. Lists start and end with square brackets [ ]. To create
an empty list you write:
Code
MyList = []
print "MyList = ", MyList

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.

You can mix the data types inside a list.


Code
y=[1.7,2,"generic text"]
print "y = ", y

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.

3.2 Accessing Lists - Indexing


It can be useful to access either individual elements, or specific portions, of a list. To do this we index the
list. The syntax for indexing is to use square brackets at the end of the list you are indexing; the number of
the element you want to access goes inside the brackets as an integer. Consider the following example:
Code
MyList = [1.4,2.3,9.5,3.6,11.0]
FirstElement = MyList[0]
SecondElement = MyList[1]
print "MyList = ", MyList
print "First Element = ", FirstElement
print "Second Element = ", SecondElement

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.

3.3 Editing Lists


Lists can be edited by indexing individual elements of the list. In this example we want to replace the first
element (index 0) with the string "tree".
Code
MyList = [1.4,2.3,9.5,3.6,11.0]
MyList[0] = "tree"
print "MyList = ", MyList

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.

3.4 Properties of Lists


There are some useful functions that can be used to find out information about a list. These include:

Function Returns
max maximum value
min minimum value
len the number of elements (i.e. length)

Here is a simple to illustrate how to use them.


Code
List2 = [1.5,2.4,6.4,1982.3,2.4,9.2,1.1]
print "Max Value of List2 = ", max(List2)
print "Min Value of List2 = ", min(List2)
print "Length of List2 = ", len(List2)

Output
Max Value of List2 = 1982.3
Min Value of List2 = 1.1
Length of List2 = 7

You can assign the value returned by len(List2) to a variable.


Code
List2 = [1.5,2.4,6.4,1982.3,2.4,9.2,1.1]
N = len(List2)

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.

3.5 Final Word on Lists


Lists are not the only way to store groups of data in Python. There are arrays in Python that behave in
very similar ways to Lists and the numpy module has array structures built-in that are extremely flexible
and have more functionality than lists. However, for the purposes of this document we will stick to using
lists.
Chapter 4

Errors And Debugging

An important part of programming is being able to find errors - this is known as debugging.

4.1 The Print Statement


One particularly powerful tool for finding errors is to print out the value[s] of the variable[s] to see what is
going on as your program runs. The print statement can print any number of things of any type at once
(separated by commas).
Code
S="three"
print "S = ", S
int(S)

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

statement is added and we see that the value of i never changes.

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

4.2 Some Common Errors


Listed below are some common error types (the bit before the ”:” in the error message) and possible reasons
for this message.

Error Type Possible Causes


ValueError Mixing data types or bad mathematical expression e.g. square roots of negative num-
bers
SyntaxError Missing colons at the end of if statements, loops, misspellings, missing brackets
NameError Misspellings

4.3 General Advice


If your code produces an error message look at the line of code for which the error is raised. It’s often better
to start at the bottom end of the error message as this is likely to be the root cause of the problem. Ensure
that spellings are correct. Use print statements to see what is going on.
Chapter 5

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.

5.1 Basic Conditions


Python can evaluate basic conditional statements - it will return either True or False depending upon
whether the statement is, quite literally, true or false. Consider the following example where we are asking
Python to evaluate whether the integer 1 is less than 2. We will also print the data type of the output.
Code
print 1 < 2
print type(1<2)

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.

Below is a table of the different types of conditions that can be evaluated.

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

5.2 The if Statement


The if statement is a simple way to execute a block of code only if a certain condition is True. If the
condition is False Python ignores the block of code. The general syntax for writing an if statement is:
Code
if condition :
do something

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

When writing if statements you must:


• Put a colon after the condition .
1
• Indent the code beneath the if statement that you want to be executed

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.

Entering “anna”, when prompted, produces the output,


Output
Please enter your name: anna
Finished.

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

the word Anna


CHAPTER 5. CONDITIONAL PROGRAMMING 18

5.3 elif and else


You can group if statements together using the syntax elif after the initial if statement 3 . else can be
used as the last statement in a group to run some code if none of the conditions before it evaluate to True.
Here is an example where the user is asked to input any integer. The code then determines whether the
number is greater than, less than or equal to 10 and prints some information to the screen for the user.

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.

5.4 Combining Conditions


Combining two conditions into one if statement can be done using the and and or commands. The and
expression will only execute if both conditions are True. The or expression requires that only one of the
conditions are True. An example using and is given below:
3 elif is short-hand for else if and is used to prevent the line of code being too long.
4 raw input always converts the input to a string
CHAPTER 5. CONDITIONAL PROGRAMMING 19

Code
x = -1
y = -2

if x >= 0 and y >= 0:


print "x and y are both greater or equal to than 0"
elif x < 0 and y < 0:
print "x and y are both less than 0"
else:
print "x and y are a mixture of pos/neg numbers"

Output
x and y are both less than 0

Try changing the values of x and y to satisfy each condition.

Here is an example using the or syntax.


Code
x = -6
y = 3

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.

5.5 try and except


If you want to see whether a piece of code executes properly you can use try and except statements. It
works along the lines of try this code, if it works carry on, if it produces an error, skip it. It can be useful
for identifying errors. Consider the example of trying to convert a numeric string to a float.
Code
x = "7"

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]

print "MyList = ", MyList

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

6.1 for Loops


Accessing each element of an arbitrarily sized variable (e.g. a list) can be done using a for loop. The syntax
when using for loops is:
Code
for element in variable :
execute some code

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.

6.2 Indexing Lists Using for Loops


You can use a combination of the range function and a for loop to access each element of a list. Here we
will print out each element of an array by indexing the list.
Code
y = [1,3,6,10,15]

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]

print "MyList = ", MyList

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]

print "MyList = ", MyList

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

6.3 range Function


Although the range function is not strictly in line with the theme of this section it is incredibly useful when
using loops. Why? Because it is very useful for generating the indices used to access lists. The syntax for
the range function is as follows.
Code
range(start, stop, step)

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.

6.4 Combining Loops


It is also possible to nest a loop inside another loop. It is clear from the following example how the values of
i and j change at each step through the loops.
Code
x = [1,2,3]
y = [10,20,30]

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

6.5 while Loops


Sometimes it useful to have a block of code execute until some specific condition is met. Using a for loop
limits us to a specific number of repetitions (i.e. the number of elements in the object you are iterating over).
However, a while loop has the potential to run infinitely and never stop 2 . The general syntax for a while
loop is:
Code
while condition :
do something

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.

You can press ctrl+c to kill your program whilst it is running.


CHAPTER 6. LOOPS 26

6.6 Breaking Loops


Sometimes you may have more than one condition for breaking the loop. Fitting all of these onto one
line after the while can be confusing and unclear to someone else reading your code. Furthermore, consider
the example of finding the roots of an equation. Your conditions for ending the loop would be based upon
the root being sufficiently close to 0. However, what if the root never reached 0? The code would simply
run infinitely. It would therefore be useful to, say, limit the number of times the loop executes such that
your code will not run infinitely. To do this we use the break statement. When Python sees this it will
immediately break out of the loop structure.

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.

6.7 Many Ways to Skin a Cat...


In this section we will show different ways of executing the same problem using for and while loops. This
is to show the versatility of using control structures and that there is no one correct way to perform a given
task.3
The problem we will tackle is to find the sum of numbers in a list4 . We will index each element of the list
and add that to a running variable Total. After the sum has been computed a message will be printed to
the screen informing the user of the answer.
We will use two examples with for loops and two examples using while loops. The # symbol will be used
to comment5 the code to explain what is going on.

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

something we are too concerned with.


4 This can also be done using the built in function sum.
5 As soon as Python sees the symbol # any remaining text on that same line is ignored. Comments are a really useful way

to explain what your code is doing.


CHAPTER 6. LOOPS 27

Code
#generate list
z = [6.2,4.6,8.2,9.3,9.1]

#find the length of z


length = len(z)

#create variable Total for storing the sum of z


Total = 0

#loop through array z to find sum of elements


for i in z:
Total = Total + i

print "Sum of list z = ", Total

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]

print "Sum of list z = ", Total

Code
z = [6.2,4.6,8.2,9.3,9.1]
length = len(z)
Total = 0

#variable to keep track of the index of z to be accessed


index = 0

while True:
Total = Total + z[index]
index = index + 1

if index == length:
break

print "Sum of list z = ", Total


CHAPTER 6. LOOPS 28

Code
z = [6.2,4.6,8.2,9.3,9.1]
length = len(z)
Total = 0
index = 0

while index < length:


Total = Total + z[index]
index = index + 1

print "Sum of list z = ", Total

Output
Sum of list z = 37.4

This output is generated by all four different versions of the code.


Chapter 7

Input And Output

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.

7.1 Reading From The Screen


There are two commands which are commonly used to read data from the screen. These are: input and
raw input. Both work in a very similar way. They both allow the programmer to print a message on the
screen to tell the user what to do and they both pause the program and wait for the user to press the enter or
return key. Once this happens they both return any text entered by the user. This can be saved in a variable
for use later in the program. The important difference between the two functions is the type of variable
which is returned. input will examine what has been entered and try to set the variable to the correct type,
in the same way as the interpreter does in the source code2 . This can help to make code shorter, but often
leads to problems if the user does not enter the kind of variable the program was expecting. In contrast
raw input will take whatever the user has entered and turn it into a string. This usually means more lines
of code are needed to get the variable required by later stages of the program, but it gives the programmer
much more control and thus it is much easier to deal with incorrect input and the program is less likely to
crash. Consider the example below.
Code
x=raw input("Enter something for raw input: ")
print "You entered ",x," Which is a ",type(x)
y=input("Enter something for input: ")
print "You entered ",y," Which is a ",type(y)

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’>

1 This is the .py file.


2 Hence the user must enter data which would be valid in a Python source file.

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

7.2 Opening Files


In order to read from and write to files we must first tell the interpreter which file we want to use. We can
do this using the open function3 . Here we give the name of the file and the operation we want to perform:
r to read or w to write4 . If we choose r then the interpreter will assume the file already exists. If it doesn’t
the program will crash. Choosing w will make the interpreter create the file if it does not exist or overwrite
it if it does, in which case any data in the file will be lost.
Code
input file=open("My input file.txt","r")
output file=open("My output file.txt","w")

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 .

7.3 Reading files


There are may ways to read in data from a file, but perhaps the most intuitive way is simply to think of the
file as a list of strings, where each element in the list represents a line in the file. Therefore we can simply
use a for loop to go through all the lines one at a time as in the example below.
Code
input file=open("My input file.txt","r")
for line in input file:
print line

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

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

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.

7.3.1 Some More Properties Of Strings


Since files are made up of strings it is worth considering how some of the methods available for str type
variables may be useful when reading data from a file. As we saw in the section on variables strings can be
converted into different types such as floats or integers using the float and int functions. However we may
need to do some more processing first.

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.

7.3.2 A Slightly Subtle Point


One aspect of reading files which can be confusing is the fact that once a line has been read it cannot be
read again without first closing and reopening the file. This is not immediately obvious since the program
will move from line to line automatically. The way to understand this is to think of the file as being like a
cassette tape. As the lines are been read we are essentially playing the tape, but we cannot play it in reverse
so to get back to a line which has already been read we must go right back to the beginning.

7.4 Writing Files


If a file is open for writing then we can use the write method which writes a given string to the file, just like
print does for the screen. If the write method is used more than once while a file is open strings are added
to the end of the file.
CHAPTER 7. INPUT AND OUTPUT 34

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

7.5 Closing Files


When a program ends all the files it had open are automatically closed. However it is good practice to close
the files once you have finished with them, before the program ends. In Python all files are closed using the
close method like so:
Code
input file=open("My input file.txt","r")
for line in input file:
print line
input file.close()

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

ends. In most cases the file will be blank until it is closed.


Chapter 8

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.

8.1 Defining A Function


Functions are defined using the def command. This is always followed by the function name. You will
use this name whenever you want to use, or call, the function. The names of the function arguments go in
brackets after the name. There will be more on these later. The definition ends with a colon (:). The code
which makes up the function and which performs whatever operation you want the function to perform is
indented and goes on the lines underneath the definition. Finally functions can return variables. There will
be more on this later as well. Functions must be declared before they are used. The example below
shows how to define and call a simple function that takes no arguments and returns nothing.
Code
def My function():
print "Hello this is My function!"

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

8.2 Args, Kwargs And Optional Arguments


Functions like the one in the above example are of limited use since they can only do one thing so we might
as well just do that in the main program. Functions are most useful when they can act as mini programs
and do something with data that is given to them by the main program and return a result. This section
will explain the various methods that are available for giving a function some data. The next section will
deal with getting the result back. Perhaps the most intuitive way to give data to a function is by passing
arguments to the function. We have already done this with several of the in-built functions. Now let us take
a look at how to do it with a function of our own.
Code
def My function(a,b,c):
print "a = ", a
print "b = ", b
print "c = ", c

print "Calling the function"


My function(10,6,8)

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

print "Call 1"


My function(10,6,8)
print "Call 2"
My function(10,6)

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

arguments must come at the end.

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")

print "Call 1"


My function(a=10,b=6,c=8) #here the name doesn’t have " "
print "Call 2"
My function(a=10,c=8,b=6)

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")

print "Call 1"


My function(10,6,8,x=50,y=13,z=99)
print "Call 2"
My function(10,x=50,y=13,z=99)
print "Call 3"
My function(10,6,8,x=50,z=13,y=99)
print "Call 4"
My function(10,6,8,x=50)
print "Call 5"
My function(10,x=50)
CHAPTER 8. FUNCTIONS 39

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.

8.3 Returning Values


The return statement can be used to make a function pass values back to the function that called it. This
statement can be placed anywhere in the function and can be used may times over, but the interpreter will
stop and go back to the calling function once it finds return. Consequently it usually only appears at the
end, but there are situations where it is useful elsewhere. As with arguments functions can return any number
of variables of any type. Let’s start with a simple example:
CHAPTER 8. FUNCTIONS 40

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

def Cleaver sqrt(n):


if n<0:
return "Impossible"
else:
return sqrt(n)

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

8.4 Local And Global Variables (More Advanced)


Now that we are more used to using functions we need to understand a little bit more about the scope that
the variables we use have. In other words whether they can be seen by a particular function. Unlike many
other languages where the programmer specifies whether a variable is local or global Python uses a set of
rules which enables the interpreter to decide how to treat a variable. This can be quite confusing at first
sight. However it does save a certain amount of typing. If a variable is defined in the main part of the code
(i.e. it is not in a function) then it will be treated as a global variable by any function which does not try to
change it. If a variable is defined within a function then it is a local variable and only that function can see it.
Also (and this is the confusing part) if a function tries to change a variable which was declared in the main
function it will be treated, in that function only, as if it was a local variable and the global value will remain
the value it was given in the main function, the exception being if it is changed in the main function itself.
If we want to change the global version of the variable within a function we have to tell the interpreter that
within this function we are referring to the global version. We do this using the global statement followed
CHAPTER 8. FUNCTIONS 42

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

a=1 #this is a global variable


print "the main function sees a = ", a
f()

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]

8.5 Calling Functions Recursively


As well as calling functions from the main program it is possible to call functions from other functions and
it is even possible for functions to call themselves. This latter ability is known as recursive calling. Here is
an example of how it’s done.
CHAPTER 8. FUNCTIONS 45

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

8.6 Creating And Importing Modules


As we have seen functions provide us with a very powerful way of organising sections of code, but long,
complicated programs can still result in very large source code files and this can make things difficult to find
and use. Fortunately Python provides a way in which we can split up source code over several files. This
means we can organise our code even more, putting functions which perform similar tasks in a file together1
and, perhaps, importing several such files into our main program to get at the functions we want to use.
There are a number of other advantages to doing this: Using this kind of modular structure makes it easy
to share useful functions between different programs and even different people without having to copy them
out. And it also means that we can compile certain sections of code to achieve better performance whilst
still using the familiar interpreter interface.

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

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)

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

Return the absolute value of the argument.

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

help(Higest Common Factor)

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

Libraries (In Brief )

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-

mance from the available hardware, in a way that Python cannot.

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

1.0 Plot Of A Range Of sin(n*x) for n=1,2,3,4,5


n=1
n=2
n=3
0.5
sin(n*x)

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

Useful Functions And Concluding


Remarks

Provided in this section is a list of useful functions that you may find useful to use in your own programs.

10.1 Converting Data types


For converting from one data type (e.g. string to a float) you use the following functions.

Convert to Syntax
string str()
float float()
integer int()

10.2 Useful Functions For Lists

Function Returns
len() Length (number of elements)
min() Minimum value present
max() Maximum value present
sum() Sum of each entry

10.3 Concluding Remarks


We hope you have found this document useful and that it has helped you to understand the basics. It can
often be difficult to know where to start with programming if you have never done it before. Really the only
way to learn is to practice and try things for yourself. We strongly encourage you to type out the examples
and run them, then once you have figured out how they work try to make changes and get them to perform
different tasks. This is often the best way to learn a new concept. As you become more and more confident
with the structure and terminology you should find that it gets much easier to adapt to unfamiliar functions
and modules. It is very very difficult, even if you try, to cause any damage to a computer (but do be careful
with your files, it’s best to keep copies somewhere safe) by running Python scripts so don’t be afraid to try
new things: if it goes wrong you can always stop the process. We wish you all the best for the course and
hope you enjoy learning Python!

54

You might also like