You are on page 1of 434

1

1
An introduction to Python
for absolute beginners
http://www.ucs.cam.ac.uk/docs/course-notes/unix-courses/PythonAB
Bob Dowling
ni!ersity "omputing #er!ice
scientific-computing$ucs.cam.ac.uk
'elcome to the "omputing #er!icePs course 04ntroduction to Python1.
,his course is designed for people with absolutely no experience of programming.
4f you ha!e any experience in programming other languages you are going to find
this course extremely boring and you would be better off attending our course
iPython for Programmersi where we teach you how to con!ert what you know from
other programming languages to Python.
,his course is based around Python !ersion 5. Python has recently undergone a
change from Python . to Python 5 and there are some incompatibilities between
the two !ersions. ,he older !ersions of this course were based around Python .
but this course is built on Python *.
Python is named after 7onty Python and its famous flying circus: not the snake. 4t
is a trademark of the Python #oftware -oundation.

2
2
"ourse outline % &
'ho uses Python ( what for
'hat sort of language it is
)ow to launch Python
Python scripts
*eading in user data
+umbers
"on!ersions
"omparisons
+ames for !alues
,ext
,ruth ( -alsehood

3
3
"ourse outline % .
Assignment
+ames
/ur first 0real1 program
2oops
if3 else3
4ndentation
"omments

4
4
"ourse outline % 5
Lists
4ndices
2engths
"hanging items
6xtending lists
7ethods
"reating lists
,esting lists
*emo!ing from lists
for3 loop
4terables
#lices

5
5
"ourse outline % 8
Files
*eading ( writing
'riting our own functions
,uples
7odules
#ystem modules
6xternal modules
Dictionaries
-ormatted text

6
#o who uses Python and what for9
Python is used for e!erythingB -or example:
0massi!ely multiplayer online role-playing games1 like 6!e /nline: science
fiction?s answer to 'orld of 'arcraft:
web applications written in a framework built on Python called 0DFango1:
desktop applications like Blender: the 5-d animation suite which makes
considerable use of Python scripts:
the #cientific Python libraries J0#ciPy1K:
instrument control and
embedded systems.
6
'ho uses Python9
/n-line games
'eb ser!ices
Applications
#cience
4nstrument control
6mbedded systems
en.wikipedia.org/wiki/List_of_Python_software

7
7
'hat sort of language is Python9
6xplicitly
compiled
to machine
code
Purely
interpreted
": ";;:
-ortran
#hell:
Perl
6xplicitly
compiled
to byte
code
<a!a: "=
4mplicitly
compiled
to byte
code
Python
Compiled Interpreted
'hat sort of language is Python9 ,he nam!e !iew of computer languages is
that they come as either compiled languages or interpreted languages.
At the strictly compiled end languages like ": ";; or -ortran are icompiledi
Jcon!ertedK into raw machine code for your computer. Hou point your "P at
that code and it runs.
#lightly separate from the strictly compiled languages are languages like
<a!a and "= Jor anything running in the .net frameworkK. Hou do need to
explicitly compile these programming languages but they are compiled to
machine code for a fake "P which is then emulated on whiche!er system
you run on.
,hen there is Python. Python does not ha!e to be explicitly compiled but
behind the scenes there is a system that compiles Python into an
intermediate code which is stashed away to make things faster in future.
But it does this without you ha!ing to do anything explicit yourself. #o from
the point of !iew of how you use it you can treat it as a purely interpreted
language like the shell or Perl.

8
8
*unning Python % &
'e are going to use Python from the command line either directly or
indirectly.
#o: first 4 need a nix command line. 4 will get that from the A4 by clicking
on the terminal icon in the desktop application bar.

9
9
*unning Python % .
$ python3
nix prompt
nix command
4ntroductory blurb
Python prompt
[GCC 4.6.3] on lin!"
#defalt$ %ay 3 "&'"$ '()(4)4"*
Python !ersion
Python 3.".3
+++
+ow: the nix interpreter prompts you to gi!e it a nix command with a
short bit of text that ends with a dollar. 4n the slides this will be represented
simply as a dollar.
,his is a nix prompt asking for a nix command.
,he nix command we are going to gi!e is 0python31. Please note that
trailing 051. ,he command 0python1 gi!es you either Python . or Python 5
depending on what system you are on. 'ith this command we are insisting
on getting a !ersion of Python 5.
,he Python interpreter then runs: starting with a couple of lines of blurb. 4n
particular it identifies the specific !ersion of Python it is running. J5...5 in this
slide.K
,hen it gi!es a prompt of its own: three 0greater than1 characters. ,he
Python 5 program is now running and it is prompting us to gi!e a Python
command.
Hou cannot gi!e a nix command at a Python prompt Jor )ice )ersaK.

10
10
>uitting Python
+++ exit()
+++ quit()
+++
"trl D ;
Any one
of these
,here are !arious ways to @uit interacti!e Python. ,here are two commands
which are e@ui!alent for our purposes: [it#* and e!it#*: but the
simplest is the key se@uence j"trlk;jDk.

11
11
A first Python command
+++ print('Hello, world!')
,ello$ world-
+++
Python prompt
Python command
/utput
Python prompt
,here is a tradition that the first program you e!er run in any language
generates the output 0)ello: worldB1.
4 see no reason to buck tradition. 'elcome to your first Python commandO
we are going to output 0)ello: worldB1.
'e type this command at the Python prompt. ,he con!ention in these slides
is that the typewriter text in bold face is what you type and the text in regular
face is what the computer prints.
'e type 0print1 followed by an opening round brackets and the text
0,ello$ world-1 surrounded by single @uotes: ending with a closing
round bracket and hitting the *eturn key: j k: to indicate that we are done
with that line of instruction.
,he computer responds by outputting 0,ello$ world-1 without the
@uotes.
/nce it has done that it prompts us again asking for another Python
command with another Python prompt: 0+++1.

12
12
Python commands
print
Python 0function1
(
-unction?s 0argument1
*ound brackets
% 0parentheses1
( ) 'Hello, world!'
0"ase sensiti!e1 print PRINT
,his is our first Python 0function1. A function takes some input: does
something with it and JoptionallyK returns a !alue. ,he nomenclature deri!es
from the mathematics of functions: but we don?t need to fixate on the
mathematical underpinnings of computer science in this course.
/ur function in this case is 0print1 and the command necessarily starts
with the name of the function.
,he inputs to the function are called its 0arguments1 and follow the function
inside round brackets J0parentheses1K.
4n this case there is a single argument: the text to print.
+ote that Python: as with many but not all programming languages: is 0case
sensiti!e1. ,he word 0print1 is not the same as 0Print1 or 0PGFKH1.

13
13
Python text
,he body
of the text
>uotation marks
' ' Hello, world!
!
,he @uotes are not
part of the text itself.
,he text itself is presented within single @uotation marks. J'e will discuss
the choice of @uotation marks later.K
,he body of the text comes within the @uotes.
,he @uotes are not part of the textO they merely indicate to the Python
interpreter that 0hey: this is textB1
*ecall that the the printed output does not ha!e @uotes.

14
14
>uotes9
print "ommand
.print. ,ext
#o what do the @uotes 0do19
4f there are no @uotes then Python will try to interpret the letters as
something it should know about. 'ith the @uotes Python simply interprets it
as literal text.
-or example: without @uotes the string of characters pUrUiUnUt are a
commandO with @uotes they are the text to be printed.

15
15
Python scripts
hello'.py
-ile in home directory
$ python3
,ello$ world-
$
nix prompt
nix command
to run Python
Python script
Python script?s output
nix prompt
hello1.py
print#.,ello$ world-.*
*un from Unix prompt
#o we understand the 0hello: world1 command and how to run it from an
interacti!e Python. But serious Python programs can?t be typed in li!eO they
need to be kept in a file and Python needs to be directed to run the
commands from that file.
,hese files are called 0scripts1 and we are now going to look at the Python
script !ersion of 0hello: world1.
4n your home directories we ha!e put a file called 0hello'.py1. 4t is
con!entional that Python scripts ha!e file names ending with a 0.py1 suffix.
#ome tools actually re@uire it. 'e will follow this con!ention and you should
too.
,his contains exactly the same as we were typing manually: a single line
with the print command on it.
'e are going to make Python run the instructions out of the script. 'e call
this 0running the script1.
#cripts are run from the nix command line. 'e issue the nix command
0python31 to execute Python again: but this time we add an extra word: the
name of the script: 0hello'.py1.
'hen it runs commands from a script: python doesn?t bother with the lines
of blurb and as soon as it has run the commands Jhence the outputK it exists
immediately: returning control to the nix en!ironment: so we get a nix
prompt back.

16
16
6diting Python scripts % &
,o edit scripts we will need a plain text editor. -or the purposes of this
course we will use an editor called 0gedit1. Hou are welcome to use any
text editor you are comfortable with Je.g. Bi or eNa/sK.
nfortunately the route to launch the editor the first time is a bit clunky.
Actually: it?s a lot clunky.
&. "lick on the 0Dash )ome1 icon at the top of the icon list.
,his launches a selection tool that starts blank. 4f you ha!e been using some
other files then these may show as 0recent files1.
.. At the bottom of the widget you will see the 0house1 icon highlighted.
"lick on the 0three library books1 icon next to it.
,his switches the selector to the library of applications.

17
17
6diting Python scripts % .
5. "lick on the 0see more results1 text to expose the complete set of
supported applications.
8. #croll down until you see the 0,ext 6ditor1 application. J,he scroll
mouse tends to work better than dragging the rather thin scroll bar.K
S. "lick the 0,ext 6ditor1 icon.

18
18
6diting Python scripts % 5
,his will launch the text editor: gedit.

19
19
6diting Python scripts % 8
-uture launches won?t be anything like as painful. 4n future the text editor will
be immediately a!ailable in 0*ecent Apps1.

20
20
Progress
4nteracti!e Python
Python scripts
print#* command
#imple Python text

21
21
6xercise &
&. Print 0Aoodbye: cruel worldB1 from interacti!e Python.
.. 6dit e!er/ise'.py to print the same text.
5. *un the modified e!er/ise'.py script.
. minutes
Please ask if you ha!e @uestions.
During this course there will be some 0lightning exercises1. ,hese are !ery
@uick exercises Fust to check that you ha!e understood what?s been co!ered
in the course up to that point.
)ere is your first.
-irst: make sure you can print text from interacti!e Python and @uit it
afterwards.
#econd: edit the e!er/ise'.py script and run the edited !ersion with the
different output.
,his is really a test of whether you can get the basic tools running. "lease
ask if you ha!e any problemsB

22
22
A little more text
hello".py
print#. 01 $ 23 45.* -ull 0nicode1 support
www.ni/ode.org//harts/
+ow let?s look at a slightly different script Fust to see what Python can do.
Python 5 has excellent support for fully international text. J#o did Python .
but it was concealed.K
Python 5 supports what is called the 0nicode1 standard: a standard
designed to allow for characters from almost e!ery language in the world. 4f
you are interested in international text you need to know about the nicode
standard. ,he *2 shown will introduce you to the wide range of characters
supported.
,he example in the slide contains the following characters:
P2A+"N?# "/+#,A+, D4D4D6D BH ,'/ P4
n "H*4224" #7A22 26,,6* 6
o 2A,4+ #7A22 26,,6* 2 '4,) BA*
")6*/N66 26,,6* DA
6,)4/P4" #H22AB26 P)A*H+A6A2 A
p A*66N #7A22 26,,6* /76AA
h ')4,6 #7424+A -A"6
A*76+4A+ #7A22 26,,6* *6)
"/P,4" #7A22 26,,6* 2ADA
q PA*,4A2 D4--6*6+,4A2
r D/B26 6I"2A7A,4/+ 7A*N

23
23
Aetting characters
C
AltAr #hift ; = ; g
02A,4+ #7A22
26,,6* A
'4,) B*6D61
6&''f
"haracter #elector
2inux
E
4 don?t want to get too distracted by international characters: but 4 ought to
mention that the hardest part of using them in Python is typically getting
them into Python in the first place.
,here are three 0easy1 ways.
,here are key combinations that generate special characters. /n 2inux: for
example: the combination of the three keys jAltArk: j#hiftk: and j=k set up the
bre!e accent to be applied to the next key pressed.
Perhaps easier is the 0"haracter #elector1 application. ,his runs like a free-
standing 0insert special character1 function from a word processor. Hou can
select a character from it: copy it to the clipboard and paste it into any
document you want.
-inally: Python supports the idea of 0nicode codes1. ,he two characters
061 followed by the hexadecimal Jbase &YK code for the character in the
nicode tables will represent that character. Hou ha!e all memori_ed your
code tables: ha!en?t you9

24
24
,ext: a 0string1 of characters
+++ type('Hello, world!')
7/lass .str.+ A string of characters
, e l l o $ w o r l d - '3
"lass: string
2ength: &5
2etters
str
'e will @uickly look at how Python stores text: because it will gi!e us an
introduction to how Python stores e)erything.
6!ery obFect in Python has a 0type1 Jalso known as a 0class1K.
,he type for text is called 0str1. ,his is short for 0string of characters1 and is
the con!entional computing name for text. 'e typically call them 0strings1.
4nternally: Python allocates a chunk of computer memory to store our text. 4t
stores certain items together to do this. -irst it records that the obFect is a
string: because that will determine how memory is allocated subse@uently.
,hen it records how long the string is. ,hen it records the text itself.

25
25
,ext: 0behind the scenes1
str
'3 8" '&' '&9 '&9 ''' 44 3" 33 '&& :
&''f
'6
;
+++ hr(!"#)
.;.
+++ ord('$')
"98
+++ '%u&11''
.;.
"98
'&
4n these slides 4?m going to represent the stored text as characters because
that?s easier to read. 4n reality: all computers can store are numbers. 6!ery
character has a number associated with it. Hou can get the number
corresponding to any character by using the ord#* function and you can
get the character corresponding to any number with the /hr#* function.
7athematical note:
,he subscript &R and &Y indicate the 0base1 of the numbers.

26
26
Adding strings together: ;
print#.,ello$ . < .world-.*
hello3.py
0"oncatenation1
+++ 'Hello, ' ( 'world!'
.,ello$ world-.
+++
+ow let?s do something with strings.
4f we sadd? two strings together Python Foins them together to form a longer
string.
Python actually permits you to omit the 0<1. Don?t do this.

27
27
Pure concatenation
+++ 'Hello,' ( 'world!'
.,ello$ world-.
+++ 'Hello,' ( 'world!'
.,ello$ world-.
+++ 'Hello,' ( 'world!'
.,ello$world-.
/nly simple
concatenation
+o spaces added
automatically.
,his Foining together is !ery simple. 4f you want words split by a space you
ha!e to put the space in.

28
28
#ingle ( double @uotes
+++ 'Hello, world!'
.,ello$ world-.
+++
.,ello$ world-.
#ingle @uotes
)Hello, world!) Double @uotes
#ingle @uotes
#ingle @uotes
4t doesn?t matter whether we write our strings with single or double @uotes
Jso long as they match at the two endsK. Python simply notes that we are
defining a string.

29
29
Python strings: input ( output
.,ello$ world-.
'Hello, world!'
)Hello, world!)
#ingle or double
@uotes on input.
#ingle @uotes on output.
"reate same
string obFect.
4nternally there are no @uotes: Fust a record that the obFect is text.
'hen Python comes to display the string and declares 0this is text1 itself it
uses single @uotes.

30
30
ses of single ( double @uotes
+++
,e said =hello= to her.
print('He *+id )hello) to her.')
+++
,e said .hello. to her.
print()He *+id 'hello' to her.))
)a!ing two sorts of @uotes can be useful in certain circumstances. 4f you
want the text itself to include @uotes of one type you can define it
surrounded by the other type.

31
31
'hy we need different @uotes
+++
>ile =7stdin+=$ line '
print#.,e said .hello. to her..*
?
@ynta!Arror) inBalid synta!
print('He *+id 'hello' to her.')

Hou must mix the @uotes like that. 4f you do not then Python will be unable to
make sense of the command.
'e will look at Python?s error messages in more detail later.

32
32
Adding arbitrary @uotes
+++ print('He *+id %'hello%' to her.')
,e said .hello. to her.
6.
6=
.
=
06scaping1
<ust an ordinary
character.
,here is a more general solution to the 0@uotes within @uotes1 problem.
Preceding each @uote within the body of the text signals to Python that this
is Fust an ordinary @uote character and should not be treated specially.
+ote that what is encoded in the string is a single character. ,he backslash
is a signal to the Python interpreter as its constructs the string. /nce the
string is constructed: with @uotes in it: the backslash?s work is done.
,his process of flagging a character to be treated differently than normal is
called 0escaping1 the character.

33
33
Putting line breaks in text
+++ print('Hello,
,ello$
world-
'hat we want
world')
,ry this
+++ print('Hello,

>ile =7stdin+=$ line '
print#.,ello$
?
+++
@ynta!Arror) ACL while
s/anning string literal
06/21: 6nd /f 2ine

'e will follow the theme of 0inserting awkward characters into strings1 by
looking at line breaks.
'e cannot insert a line break by hitting the j k key. ,his signals to Python
that it should process the line so far and Python cannotO it is incomplete.

34
34
4nserting 0special1 characters
+++ print('Hello,
,ello$
world-
world!') %n
,reated as
a new line.
str
'3 e l l o $ w o r l d - ,
6n "on!erted into a
single character.
+++ len
'3 len#* function: gi!es
the length of the obFect
('Hello,%nworld!')
Again: the backslash character comes to our rescue.
4f we create a string with the se@uence 06n1 then Python interprets this as
the single character .
Python can tell us exactly how many characters there are in a string. ,he
len#* function tells us the length of the string in characters. ,here are &5
characters in the string created by .,ello$6nworld-.. ,he @uotes are not
part of the text and the 6n becomes a single character.

35
35
,he backslash
6.
6=
.
=
#pecial /rdinary
6n
6t

/rdinary #pecial
'e ha!e used backslash again: this time for a slightly different result.
Backslash before a character with special significance: such as the @uote
character: makes the character 0ordinary1. sed before an ordinary
character: such as 0n1: it produces something 0special1.
/nly a few ordinary characters ha!e special characters associated with
them but the two most commonly useful are these:
6n new line
6t tab stop

36
36
6n: unwieldy for long text
.@DEFGA HGALIJKAL$ Mr. LiBesey$ and the6n
rest of these gentleNen haBing asked Ne6n
to write down the whole parti/lars6naOo
t Hreasre Fsland$ froN the6nOeginning to
the end$ keeping nothing6nOa/k Ot the O
earings of the island$6nand that only Oe/
ase there is still6ntreasre not yet lif
ted$ F take p Ny6npen in the year of gra
/e '8__ and go6nOa/k to the tiNe when Ny
father kept6nthe IdNiral PenOow inn and t
he Orown6nold seaNan with the saOre /t f
irst6ntook p his lodging nder or roof..
#ingle
line
,he 06n1 trick is useful for the occasional new line. 4t is no use for long texts
where we want to control the formatting oursel!es.

37
37
#pecial input method for long text
Triple
@uotes
...
rest of these gentleNen haBing asked Ne
to write down the whole parti/lars
aOot Hreasre Fsland$ froN the
Oeginning to the end$ keeping nothing
Oa/k Ot the Oearings of the island$
and that only Oe/ase there is still
treasre not yet lifted$ F take p Ny
pen in the year of gra/e '8__ and go
Oa/k to the tiNe when Ny father kept
the IdNiral PenOow inn and the Orown
old seaNan with the saOre /t first
took p his lodging nder or roof.
@DEFGA HGALIJKAL$ Mr. LiBesey$ and the
...
7ultiple
lines
Python has a special trick precisely for con!enient definition of long: multi-
line text.
4f you start the text with a 0triple @uote1 then the special treatment of hitting
the j k key is turned off. ,his lets you enter text 0free form1 with natural line
breaks.
,he triple @uote is three @uote characters with no spaces between them.
,he @uote character used can be either one but the triple use at one end
must match the one used at the other end.

38
38
Python?s 0secondary1 prompt
+++ '''Hello,
world''' ...
Python asking for more
of the same command.
,he triple @uote lets us see another Python feature. 4f we type a long string
raw then after we hit we see Python?s 0secondary prompt1. ,he three dots
indicate that Python is expecting more input before it will process what it has
in hand.

39
39
4t?s still Fust textB
+++ 'Hello,%nworld!'
.,ello
+++
...
'''Hello,
world!'''
.,ello6nworld.
world. 6n
Python uses Gn to represent
line breaks in strings.
Exactly the sameB
4t is also important to note that triple @uotes are Fust a trick for input. ,he text
obFect created is still a standard Python string. 4t has no memory of how it
was created.
Also note that when Python is representing the content of a string obFect Jas
opposed to printing itK it displays new lines as 06n1.

40
40
Hour choice of input @uotes:
.,ello$6nworld-. =,ello$6nworld-=
===,ello$
world-===
...,ello$
world-...
str
'3 e l l o $ w o r l d - ,
#ame result:
-our inputs:
'e ha!e now seen four different ways to create a string with an embedded
new line. ,hey all produce the same string obFect.

41
41
Progress
4nternational text
print#*
"oncatenation of strings
2ong strings
#pecial characters

42
42
6xercise .
5 minutes
&. *eplace IIII in e!er/ise".py so it prints the following
text Jwith the line breaksK and then run the script.
coffee
cafL
caffM
Naffee
L
M
6&&eQ
6&&e9
AltAr
AltAr
;
;
=
O
e
e
,here is more than one way to do this.
Hou can get the line breaks with Gn in a single-@uoted string or with literal line
breaks in a triple-@uoted string. An alternati!e: but not in keeping with the
exercise: is to ha!e four print#* statements.
Hou can get the accented characters by using the 6 se@uences or you can
type them in literally with the keyboard combinations shown. J2inux onlyK

43
43
Attaching names to !alues
Nessage R .,ello$ world-.
print#Nessage*
hello4.py
str
'3 e l l o $ w o r l d - , Nessage
0!ariables1
+++ ,e**+-e.'Hello, world!'
+++ ,e**+-e
.,ello$ world-.
+++ type(,e**+-e)
7/lass .str.+
+ow we will mo!e on to a serious issue in learning any computing language:
how to handle names for !alues.
"ompare the two scripts hello'.py and hello4.py. ,hey both do exactly
the same thing.
'e can enter the text of hello4.py manually if we want using interacti!e
Python: it will work e@ually well there.
,he first line of hello4.py creates the string s)ello: worldB? but instead of
printing it out directly the way that hello'.py does: it attaches a name:
0Nessage1: to it.
,he second line runs the print#* function: but instead of a literal string as
its argument it has this name instead. +ow the name has no @uotes around
it: and as 4 said earlier this means that Python tries to interpret it as
something it should do something with. 'hat it does is to look up the name
and substitute in the attached !alue.
'hene!er the name is used: Python will look it up and substitute in the
attached !alue.

44
44
Attaching names to !alues
Nessage R .,ello$ world-.
print#Nessage*
hello4.py
print
function
str
'3 e l l o $ w o r l d - , Nessage
+++ type(print)
7/lass .Oiltin_fn/tion_or_Nethod.+
Both 0print1 and 0Nessage1 are the same this way. Both are names
attached to Python obFects. 0print1 is attached to a chunk of memory
containing the definition of a function and 0Nessage1 is attached to a chunk
of memory containing the text.

45
45
*eading some text into a script
$ python3
LesS
input1.py
Poo-
/oo!
Nessage R inpt#.LesS.*
print#Nessage*
inpt'.py
inpt#.LesS.*
Nessage R :
print#Nessage*
+ow that we know how to attach names to !alues we can start recei!ing
input from the user of our script.
-or this we will use the cunningly named 0inpt#*1 function.
,his function takes some Jtypically shortK text as its argument. 4t prints this
text as a prompt and then waits for the user to type something back Jand
press j k. 4t then returns whate!er the user typed Jwithout the j kK as its
!alue.
'e can use this function on the right hand side of an assignment.
*ecall that the assignment completely e!aluates the right hand side first.
,his means that it has to e!aluate the inpt#* function: so it prompts the
user for input and e!aluates to whate!er it was that the user typed.
,hen the left hand side is processed and the name 0Nessage1 is attached to
this !alue.
'e can then print this input text by using the attached name.

46
46
"anPt read numbers directlyB
nNOer R inpt#.KS.*
print#nNOer < '*
inpt".py
$ python3 input!.py
KS 1&
Hra/eOa/k #Nost re/ent /all last*)
>ile =inpt".py=$ line "$ in 7Nodle+
print# < *
string integer
nNOer
HypeArror)
Can.t /onBert .int. oOTe/t
to str iNpli/itly

'
4n the pre!ious example script inpt'.py we simply took what we were
gi!en by inpt#* and printed it. ,he print#* function is a flexible beastO it
can cope with almost anything.
,he script hello".py attempts to take what is gi!en and do arithmetic with
it: namely add & to it. 4t fails: e!en though we type a number at inpt#*?s
prompt.
,his also gi!es us an error message and it?s time to in!estigate Python?s
error messages in more detail.
,he first Jthe 0trace back1K tells us where the error was. 4t was on line . of
the file inpt".py. 4t also tells us what was on the line. *ecall that with
syntax errors it also pointed out where in the line it reali_ed something was
going wrong.
,he second part tells us what the error was: we tried to add a string JtextK
and an integer Ja numberK. 7ore precisely: Python couldn?t con!ert the
things we were adding together into things that we could add.

47
47
inpt#*: strings only
nNOer R inpt#.KS.*
print#nNOer < '*
inpt".py

$ python3 input!.py
KS 1&
inpt#.KS .* str
" & '
int
'&
Q
,he problem is that the inpt#* function always returns a string and the
string 0character & followed by character R1 is not the same as the integer
ten.
'e will need to con!ert from the string to the integer explicitly.

48
48
#ome more types
+++ type('Hello, world!')
7/lass .str.+
+++ type(0!)
7/lass .int.+
+++ type(3.10112)
7/lass .float.+
string of characters
integer
floating point number
,o date we ha!e seen only two types: 0str1 and
0Oiltin_fn/tion_or_Nethod1. )ere are some more.
4ntegers Jwhole numbersK are a type called 0int1.
-loating point numbers Jhow computers approximate real numbersK are a
type called 0float1.
,he inpt#* function ga!e is a 0str1. 'e want an 0int1.

49
49
"on!erting text to integers
+++ int('1&')
'&
+++ int('31&&')
U'&&
+++ int('1&&31&')
ValeArror)
inBalid literal for int#* with Oase '&) .'&&U'&.
str
" & '
int
'&
str
6 U
int
U'&&
& ' &

,here is a function d also called 0int#*1 % that con!erts the textual


representation of an integer into a genuine integer.
4t copes with extraneous spaces and other Funk around the integer but it
does not parse general expressions. 4t will take the textual form of a number:
but thatPs it.

50
50
"on!erting text to floats
+++ 'lo+t('1&.&')
'&.&
+++ 'lo+t('1&.')
'&.&
P&R.RP is a string
&R.R is a floating
point number
,here is a similar function called float#* which creates floating point
numbers.

51
51
"on!erting between ints and floats
+++ 'lo+t(1&)
'&.&
+++ int(1&.2)
'& ,runcates
fractional part
+++ int(31&.2)
U'&
,he functions can take more than Fust strings: though. ,hey can take other
numbers: for example. +ote that the int#* function truncates floating point
numbers.

52
52
"on!erting into text
+++ *tr(1&)
.'&.
+++ *tr(1&.&&&)
.'&.&.
integer
float
string
string
,here is also a str#* function for turning things into strings.

53
53
"on!erting between types
int#*
float#*
anything
anything
integer
float
str#* anything string
-unctions named after the type they con!ert into.
4n general there is a function for each type that con!erts whate!er it can into
that type.

54
54
*eading numbers into a script
te!t R inpt#.KS.*
nNOer R int#te!t*
print#nNOer < '*
inpt3.py $ python3 input3.py
KS 1&
''
#o finally we can see what we ha!e to do to make our failing script work: we
need to add a type con!ersion line.

55
55
Progress
+ames
,ypes
,ype con!ersions
Dalues
*eading in text
str#* int#* float#*
inpt#prompt*
name R value
strings
integers
floating point numbers

56
56
6xercise 5
*eplace the two IIII in exercise5.py to do the following:
&. Prompt the user with the text 0)ow much91.
.. "on!ert the user?s answer to a floating point number.
5. Print ..S plus that number.
5 minutes

57
57
4ntegers

T3 -.: -&: R:
&: .: 5: 8 3U
+ow that we ha!e some rudimentary understanding of Python it?s time to
di!e in a little deeper to the three types we ha!e met so far.
'e are going to start with the whole numbers: 0integers1 in technical
language.
7athematical note:
,he fancy b is the mathematical symbol for the integers based on the
Aerman word *ahlen.

58
58
4nteger addition ( subtraction
+++ !&(1
"(
+++ !&31
'(
#paces around the
operator don?t matter.
0+o surprises1
'e can start our handling of integers with some !ery basic arithmetic.
+ote that spaces around the plus and minus character are ignored.
Adding or subtracting two integers simply gi!es a third integer.

59
59
4nteger multiplication
,here is no 0V1 on the keyboard. 2inux:
: ; #hift AltAr ;
se 0W1 instead
+++ !&41
'&&
#till no surprises
,he arithmetical operations addition and subtraction ha!e their usual
mathematical symbols reflected on the standard keyboard. 'e ha!e a plus
sign and a minus sign Jactually a 0hyphen1K character and we use them.
,here is no multiplication symbol on the standard keyboard. Hou can
generate it as one of the octopus-friendly key combinations: but it?s not a
simple key.
4nstead: the computing profession has settled on using the asterisk J0W1K to
represent multiplication. /n your keyboards this is j#hiftk;jXk.
7ultiplying two integers gi!es a third integer.

60
60
4nteger di!ision
,here is no 0W1 on the keyboard. 2inux:
. ; #hift AltAr ;
se 0/1 instead
+++ !&51
4.&
,his is a floating point numberB
#urpriseB
,here is no di!ision symbol on the keyboard without holding three keys
down at the same time. Again a con!ention has arisen to use the forward
slash character Jstrictly called a 0solidus1K for di!ision.
#o far there ha!e been no surprises in Python?s integer arithmetic. ,hat
changes with di!ision.
+ot all integer di!ision can be achie!ed precisely. Hou cannot di!ide 5 into S
exactly. Because of this Python 5 always returns a type of number capable
of representing fractional !alues Ja floating point numberK e!en when the
di!ision would ha!e been exact.

61
61
4nteger di!ision gi!es floats B
-ractions
+++ !&50&
&.(
+++ !&53&
&.6666666666666666
-loats sometimes
"onsistency -loats always
B
,he designers of Python decided that consistency of output was important
and therefore because it might sometimes need to use a float it should
always use a float.
+ote that e!en floating point numbers cannot exactly represent all fractions.
g can be precisely represented but cannot. 'e will return to the
imprecision of floating point numbers when we look at them in detail.
J4f you really want to stick to integers then Python 5 offers the 0//0 operator
which returns an integer answer: rounded strictly down in case of fractional
answers.K

62
62
4nteger powers
,here is no 08
.
1 on the keyboard.
se 0WW1 instead
+++ 044!
'6
+++ 044!
@ynta!Arror) inBalid synta!
#paces around the
operator don?t matter.
#paces in the
operator doB
<ust as there is no mathematical symbol on the keyboard for multiplication
and di!ision: there is no symbol at all for raising to powers. 7athematically
we represent it by superscripting the power after the number being raised.
'e can?t do this on the keyboard so instead we cheat and in!ent our own
symbol for the operation.
"omputing has split for this operation. #ome languages use the circumflex
accent J0?1K and others: including Python: use a double asterisk: 0WW1.
+ote that while spaces around the operator are ignored you can?t split the
two asterisks.

63
63
4nteger remainders
e.g. 4s a number e!en or odd9
+++ 06!
&
+++ 16!
'
se 0X1
+++ 316!
' *emainder is always non-negati!e
,here?s one last integer arithmetic operator we will use once in a while.
Another way to look at di!ision is to ask what the remainder is after a
di!ision. Python represents this concept by using the percent sign between
to numbers to represent the remainder when the first number is di!ided by
the second.
'e will use it for one purpose only in this course: to determine if a number is
e!en or odd. 4f a number?s remainder when di!ided by . is R then it?s e!en
and if the remainder is & then it?s odd.

64
64
)ow big can a Python integer be9
+++ !44!
4
+++ 044!
'6
+++ 1744!
"(6
+++ !1744!
6((36
+++ 7113744!
4"Q4Q68"Q6
+++ !1744!
6((36
+++ !1744!
6((36
+++ !44!
4
+ow we will look at the numbers themsel!es. 'e can ask the @uestion 0how
big can an integer be91 7athematically: of course: there is no limit. 4n a
computer there are always limits. 6ach computer has only a finite amount of
memory to store information so there has to be a limit. 'e will see that
Python has no limits in principle and it is only the technical limit of the
computer that can restrict us. 4n practice this is ne!er an issue for the si_e of
integers.
'e will experiment with large integers by repeated s@uaring. 'e start with a
. and keep s@uaring.

65
65
)ow big can a Python integer be9
+++ 0!2027#!2744!
'9446844&838&Q(('6'6
+++ 1"007#00&#3#&211171744!
34&"9"366Q"&Q394634633846&843'869"''4(6
+++ 30&!"!3772!&23"0730733#07&#031#7"!1101744!
''(8Q"&9Q"383'6'Q(4"3(8&Q9(&&9698Q&89(3"6QQ946
6(64&(64&3Q4(8(94&&8Q'3'"Q63QQ36
+++ 111#2!&"2!3#3171210!31#&2"1&&"7"#2&#"13!72
'34&89&8Q"QQ4"(Q8&QQ(84&"4QQ9"&(946'"848Q36(9"
&(Q"3Q33888"3(6'4438"'864&3&&83(46Q869&'984"Q9
'66Q&34"86Q&&3'9(9'96496&(&9(38(399"9''Q46(6QQ
4643364Q&&6&94&Q6
2"077170&170&3201#1"0&&#2131!273223744!
Python takes it in its stride and happily carries on.

66
66
)ow big can a Python integer be9
&R885XXXX&8&5&S.SRYYZ&[S.[&R[&YY.85X.S[ZZY8.8ZR8[5X5[XR5X8.558X5.X5Z
S5ZR[Z[&SS[8SYX8XX.YX&&Z58ZZ[SSX58RXZR&RY[&885Z.Y.X5[ZX[S[585X&XS[Z5
YR[.Y5.5YRX[XS&5YS.[[Z8SZSYZ[YS85[RZZZX58R5Y&SZR&585X5[&X5&88.XR[RR&
&XSSZ8Y..Y5[Y5&XX5Z5Z[[&.[8SY[.558YX8588SXYY&[8ZYXR[ZRX[RSXR5[R8R[&.
X8R8X[8R&&XYRZ&&88Y[Z[[[X5SZXR.ZRRYYXYZ5XZ[YXX&[X[[XSZ8YZRSY5R&ZR.YR
Z8RSZZS[Z8S585.X.58YZ5R5R.YYZY885RSZR.SR&SZ[.5ZZXY[[&8.&SS8&YZ5X5SSS
ZXXS.Z&8XY5&X.5[Z&88588ZY[58RX[X&&X[.Y5Z8ZY8[S&RR&XZR8&58ZRRX8&[RY&Y
[SRZ5YYX555XSRSS&R5.Z[.RXX.YZSSR[YZZX5Y&Y5YZ8&&Z55R&S.&5[ZYX.SX5[&XX
RZ&X55YSY[S&..&5&X8Z.X8Y5YX&.SSSR..SZZX5RR8&.588[X8XY.SZSY[88Z.&Z8Y&
[R.5XRYSRSZ&5.8SY&RX.S[5&X5S5XRRX[YRXY..&R.X58.[R&Z[YZX.R.5&5&YZR&[Y
[XRRYY[S&ZS8XSR[ZZ.&Y5Y8&Z5[R.XS5[S&.8[X8R&8ZR[&SZ&5S8SZZX.[ZRS&55ZZ
Y&&SS&[Z8.[&&RYX5&&58RZRSX8.[.XX8.[Z[Z&SS8X8Z[X.ZS85.5S58S&[RYS..5.Y
ZRY&5Z8ZRSZX[YZ5RR.&..ZY55ZSYX[[X.X[XZ8X88RY&YRR[8&.Z8SY[8Z&ZX.5RSRS
[&Y8.5[[&S8X&Y5.&5XRY5&R8SZR.Z&Y&5YZ.Y[RX58.XSY88R[5R88[XZZZ[&ZR&[X&
8YS[Y58[5..5XSR.Y[.S5RSZXZZ[ZSZZYRZR[ZZ8YZ.R&[[8Y.8X&[[&X88ZXY[8SSYS
Z.SR&[X5.ZR[R8[5&&Z855&YSSSRXR[SYX..&X8YS[&[8Y5[5.ZYXX8Z&.X&ZS.R5&[8
S[RR.88RZ.YY&YZ&RX[8&8X5XSR[X8&&Z.ZXR8S..ZX&XS[55XZ[[Y8X&R5&.YRXSZR5
RR&5R.8&58Y[&XZ[.YY[5.&Y8Z&S&&&5&YR.Z.R[X&[5XR5585YRZR.85XR8[RX58R8R
5&S8&ZR55Y
,here is no limitB
6xcept for
machine
memory
,he Python language has no limit on the si_e of integer.

67
67
Big integers
.
8
&Y
.SY
YSS5Y
8.Z8ZY[.ZY
&X88Y[88R[5[RZSS&Y&Y
58R.X.5YYZ.RZ5X8Y583
Y55[8YR[85&[YX.&&8SY
" / ";;
-ortran
/ut of the reach
of " or -ortranB
long long
4+,6A6*\&Y
long
4+,6A6*\X
int
4+,6A6*\8
,his may sound rather tri!ial but: in fact: Python is @uite exceptional in this
regard. ,he compiled languages ha!e to allocate space for their integers in
ad!ance and so place limits on how large they can grow.

68
68
-loating point numbers
&.R
R.55555555
5.&8&SZ.YS
..[&X.X&X.

And that?s it for whole numbers. +ow we will look at floating point numbers:
a computer?s way of storing fractional !alues. ,his is a computer?s
approximation to the real numbers. As we will see it is a problematic
approximation.
,he fancy is the mathematical symbol for the real numbers: from the
6nglish word +eal.

69
69
Basic operations
+++ !&.& ( 1.&
"(.&
+++ !&.& 3 1.&
'(.&
+++ !&.& 4 1.&
'&&.&
+++ !&.& 5 1.&
4.&
+++ !&.& 44 1.&
3"&&&&&.&
6@ui!alent to integer arithmetic
-or our basic operations: floating point numbers beha!e Fust the same as
integers: using the same operators to achie!e the same results. -loating
point di!ision creates a floating point number.

70
70
-loating point imprecision
+++ 1.& 5 3.&
&.3333333333333333
+++ 1&.& 5 3.&
3.333333333333333(
] 17 significant figures
4f you are relying on
this last decimal place:
you are doing it wrongB
#o let?s see our first problem.
-loating point arithmetic is not exact: and cannot be.
-loating point numbers on modern hardware tends to gi!e a precision of
&[ significant figures. Hou do see the occasional issue as shown on the slide
but: frankly: if you are relying on the exact !alue of the final decimal place
you are doing it wroing.

71
71
)idden imprecision
+++ &.1
&.'
+++ &.1 ( &.1
&."
+++ &.1 ( &.1 ( &.1
&.3&&&&&&&&&&&&&&&4
*eally: if you are relying on
this last decimal place:
you are doing it wrongB
B
+ot all imprecision is o!ert. #ome of it can creep up on you.
"omputers work in base .. ,hey can store numbers like g and t exactly.
But they cannot store numbers like &/&R exactly: Fust like we can?t represent
exactly in a decimal expansion.
,he errors in storing &/&R are small enough: though: that they are in!isible at
first. )owe!er: if they accumulate they become large enough to show
through.
*eally: don?t depend on precise !alues.

72
72
)ow big can a Python float be9 % &
+++ 71137.&44!
4"Q4Q68"Q6.&
+++ 0!2027#!27.&44!
'.9446844&838&Q(("e<'Q
#o far: so good.
#witch to
0scientific notation1
&.X88Y[88R[5[RZSS.
&.X88Y[88R[5[RZSS.
V&R
&Z
e;&Z
2et?s ask the same @uestion about floats as we asked about integers: how
large can they be9
'e will repeat our approach of repeated s@uaring. 'e fast-forward to start
at YSS5Y.R s@uared and notice that we soon get anomolous responses.
'hen we s@uare 8:.Z8:ZY[:.ZY we get a number with the letter 0e1 in it.
ser?s of pocket calculators at school may recognise this representation: it
indicates a number between &.R and Z.ZZZ3 multiplied by a power of &R.
-loating point numbers can only hold roughly &[ significant figures of
accuracy. ,his means that when the integer needs more than &[ digits
something has to gi!e.

73
73
-loats are not exact
+++ 0!2027#!2744!
'9446844&838&Q(('6'6
+++ 0!2027#!27.&44!
'.9446844&838&Q(("e<'Q
4nteger
-loating point
&.X88Y[88R[5[RZSS.V&R
&Z
&X88Y[88R[5[RZSS.RRR
&X88Y[88R[5[RZSS&Y&Y -
5X8
,he approximation isn?t bad. ,he error is 5X8 in &X88Y[88R[5[RZSS&Y&Y: or
approximately .V&R
-&[
.

74
74
)ow big can a Python float be9 % .
+++ 1."007#00&#3#&211!e(1244!
3.4&"9"366Q"&Q39(e<39
+++ 3.0&!"!3772!&23"1e(3"44!
'.'(8Q"&9Q"383'6"e<88
+++ 1.11#2!&"2!3#317!e(##44!
'.34&89&8Q"QQ4"(Q8e<'(4
+++ 1.30&#"&#2!220!12#e(11044!
CBerflowArror) #34$
.KNeri/al reslt ot of range.*
#o far: so good.
,oo bigB
4f we accept that our answers are now only approximate we can keep
s@uaring. ,he 0e-number1 representation of scientific notation is accepted on
input by Python.
'hen we come to s@uare &.58R[XR[Z.ZZ8.SZ[V&R
&S8
: though: we hit
another issue: this one fatal.
'e get an 0o!erflow error1. ,his means we ha!e tried to create a floating
point number larger than Python can cope with. nder some circumstances
the 0too big1 problem gi!es rise to a sort-of-number called 0inf1 Jstanding
for 0infinity1K.

75
75
-loating point limits
'."34(689Q&'"34(68Y'&
K
&[ significant figures
-5.S ^ + ^ 5RX
8.Z8RYSY8SX8&V&R
-5.8
^ + ^ X.ZXX8YSY[85&V&R
5R[
Positi!e !alues:
<ust for the record: floating point numbers ha!e limits both in terms of the
largest and smallest numbers they can contain.

76
76
z
z
2
"omplex numbers
+++ (1.!1(&.18)44!
#'.3'"(<'."(T*

Python also supports complex numbers: using T for the s@uare root of -&.
'e will not use them in this course: but you ought to know they exist.

77
77
Progress
Arithmetic
4ntegers
-loating point numbers
"omplex numbers
< U W / WW X
+o limitsB
2imited si_e
2imited precision

78
78
6xercise 8
5 minutes
*eplace the IIII in e!er/ise4.py to e!aluate
and print out the following calculations:
&. ..5 W [&
.. J& ; &/&RK
&R
5. J& ; &/&RRK
&RR
8. J& ; &/&RRRK
&RRR

79
79
"omparisons
S ^ &R
S ` &R

'e can do arithmetic on numbers. 'hat else9


'e need to be able to compare numbers.
4s S less than &R9 Hes it is.
4s S greater than &R9 +o it isn?t.

80
80
"omparisons
+++ 1 9 1&
Hre
+++ 1 : 1&
>alse
Asking the @uestion
Asking the @uestion

+ow let?s see that in Python.


,he 0less than1 character appears on the keyboard so we don?t need
anything special to express the concept like 0\\1 for powers.
Python seems to answer the @uestions with 0Hre1 and 0>alse1.

81
81
,rue ( -alse
+++ type(True)
7/lass .Oool.+ 0Booleans1
S &R ;
S &R ^
int int
&S
,rue
int
bool
,he important thing to understand is that this is not Fust Python reporting on
a test but rather the !alue generated by the test. Hre and >alse are Jthe
onlyK two !alues of a special Python type called a 0Boolean1 used for
recording whether something is true or not.
<ust as the 0;1 operator takes two integers and returns an integer !alue: the
0^1 operator takes two integers and returns a Boolean.
Booleans are named after Aeorge Boole: whose work laid the ground for
modern algebraic logic. J)is classic book?s full title is 0An 4n!estigation of the
2aws of ,hought on 'hich are -ounded the 7athematical ,heories of 2ogic
and Probabilities1: in true Dictorian style.K

82
82
,rue ( -alse
bool
bool
Hre
>alse
/nly two !alues
,he boolean type has precisely two !alues.

83
83
#ix comparisons
7aths
=

<
>

Python
RR
-R
7
+
7R
+R
Double e@uals sign
,here are six comparison operations in Python.
,he e@uality comparison is defined in Python with a double e@uals sign:
0RR1. ,he sign is doubled to distinguish comparison from assignment.
,here is no 0not e@uals1 symbol on the standard keyboard. 4nstead: Python
uses the 0-R1 pair of characters. JAs with 0WW1 there must be no space
between the two characters.K
02ess than1 and 0greater than1 we ha!e already co!ered. ,hese are
implemented directly by the 0^1 and 0`1 characters.
,here are no 0less than or e@ual to1 or 0greater than or e@ual to1 keys:
though: so Python resorts to double character se@uences again.

84
84
6@uality comparison ( assignment
naNe R Bale
R
Bale
'
RR Bale
"
RR
Attach a name to a !alue.
"ompare two !alues
4f e!er there was a 0classic typo1 in programming it is the confusion of 0e1
and 0ee1. Be careful.

85
85
,extual comparisons
+++ '+t' 9 'do-'
Hre
Alphabetic ordering
+++ ';+t' 9 '+t'
Hre
+++ '<o-' 9 '+t'
Hre
ppercase before lowercase
All uppercase before lowercase
Booleans typically arise from comparisons. 'e can compare more than
numbers Jintegers or floating pointK. 'e can also compare strings.
,ext comparisons are based around the ordering of characters in the
nicode character set. +ote that all the uppercase letters in the 2atin
alphabet precede all the lowercase letters. #o any text that starts with an
uppercase letter counts as 0less than0 any text that starts with a lowercase
letter.

86
86
/rdering text is complicated
Aerman:
#wedish:
_ ^ a
a ^ _
Python ine@ualities use nicode character numbers.
,his is o!er-simplistic for 0real1 use.
Alphabetical order9
Dictionary:
Phone book:
of ^ af
af ^ of
,raditional Aerman usage9
0"ollation1 is a whole field of computing in itself
Please note: howe!er: that this is Fust a comparison of strings. 4t is not a
general comparison of text. /rdering text is called 0collation1 and is a !ery
compicated field.
-or example: different languages order characters differently. #ome
countries ha!e different orderings for different purposes.
4f you want to learn more about this field: start with the nicode page on
collation: http)//www.ni/ode.org/reports/tr'&/


87
87
0#yntactic sugar1
& 7 nNOer 7 '&
& 7 nNOer
and
nNOer 7 '&
+++ nu,=er . 1
+++ & 9 nu,=er 9 1&
Hre
A common re@uirement is to determine if a number lies in a particular range.
-or this purpose: Python supports the mathematical notation a , b , c. ,he
ine@ualities can be any combination that make sense.

88
88
"on!erting to booleans
float#* "on!erts to floating point numbers
int#* "on!erts to integers
str#* "on!erts to strings
=ool#* "on!erts to booleans
7/lass .float.+
7/lass .int.+
7/lass .str.+
7/lass .Oool.+
As with all Python types there is a function named after the type that tries to
con!ert arbitrary inputs into Booleans. Ai!en that there are only two Boolean
!alues this tends to be a !ery simple function.

89
89
seful con!ersions
.>red. Hre
.. >alse
+on-empty string
6mpty string
' Hre
& >alse
+on-_ero
bero
'" Hre
U' Hre
,he empty string is mapped to >alse. 6!ery other string is mapped to
Hre.
-or integers: R is mapped to >alse and e!ery other !alue to Hre.
-or floating point numbers: R.R is mapped to >alse and e!ery other !alue to
Hre.

90
90
Boolean operations
+umbers ha!e ;: c: \ 3
'hat do booleans ha!e9
bool
bool
bool
bool
bool
9
Boolean types ha!e their own arithmetic Fust like ordinary numbers. 4t was
the algebra of these that Aeorge Boole de!eloped.

91
91
Boolean operations % 0and1
bool
bool
bool
and
Hre Hre and
Hre >alse and
>alse Hre and
>alse >alse and
Hre
>alse
>alse
>alse
Both ha!e
to be ,rue
,he first operation on Booleans is the 0and1 operator.
,he and of two booleans !alues is Hre if Jand only ifK both its inputs are
Hre. 4f either is >alse then its output is >alse.
+++ True +nd L+l*e
>alse
+++ True +nd True
Hre


92
92
Boolean operations % 0and1
+++ 0 9 1 +nd 7 9 #
Hre
4 7 (
6 7 8
Hre
Hre
and Hre
+++ 0 9 1 +nd 7 : #
>alse
4 7 (
6 + 8
Hre
>alse
and >alse
'e are much more likely to encounter the input booleans as the results of
comparisons that as literal !alues.

93
93
Boolean operations % 0or1
bool
bool
bool
or
Hre Hre or
Hre >alse
>alse Hre
>alse >alse
Hre
>alse
Hre
Hre
At least
one has
to be ,rue
or
or
or
,he next boolean operation to look at is 0or1. ,he results of this operation is
Hre if either of its inputs are Hre and >alse only if both its inputs are
>alse.

94
94
Boolean operations % 0or1
+++ 0 9 1 or 7 9 #
Hre
4 7 (
6 7 8
Hre
Hre
or Hre
+++ 0 9 1 or 7 : #
Hre
4 7 (
6 + 8
Hre
>alse
or Hre
Again: we tend to encounter it more often with other tests than with literal
booleans.

95
95
Boolean operations % 0not1
bool bool
not
Hre not
>alse Hre
>alse
not
,he final operation is 0not1. ,his takes only one input and 0flips1 it. Hre
becomes >alse and )ice )ersa.

96
96
Boolean operations % 0not1
+++ not 7 9 #
>alse
6 7 8 Hre not >alse
+++ not 7 : #
Hre
6 + 8 >alse not Hre

97
97
Ambiguity in expressions
5 ; Y / 5
J5 ; YK / 5 5 ; JY / 5K
5 S


98
98
Di!ision before addition
S
5 Y / 5 ;
5 . ;
Di!ision first
Addition second

99
99
0/rder of precedence1
!44y !4y !5y !6y !(y !3y (! 3!
!..y !:y !:.y !!.y !9y !9.y
not ! ! or y ! +nd y
-irst
2ast

100
100
Progress
"omparisons RR -R 7 + 7R +R
Booleans Hre >alse
+umerical comparison
Alphabetical ordering
( 7 8
.dig. 7 .dg.
Boolean operators and or not
/rder of precedence

101
101
6xercise S
5 minutes
Predict whether these expressions will e!aluate to Hre or >alse.
,hen try them.
.dog. 7 .Cat. or 4( X 3 RR '(
.sparrow. + .eagle.
6& U 4( / ( < '& RR '
&.
..
5.

102
102
+ames and !alues: 0assignment1
+++ +lph+ . 1&&
&. +lph+ . 1&&
.. +lph+ . 1&&
int
'&&
Python creates
an 0integer &RR1
in memory.
int
'&& alpha
Python attaches
the name 0alpha1
to the !alue.
+ow let?s go back to the attaching of names to !alues that we saw with our
hello3.py script.
"onsider the simple Python instruction shown.
Python does two things: strictly in this order:
-irst: it notices the literal !alue &RR Jan integerK. #o Python allocates a
chunk of memory large enough and creates a Python obFect in it that
contains a Python integer with !alue &RR.
#econd: it creates the name 0alpha1 and attaches it to the integer.

103
103
Assignment: right to left
+lph+ 1&& .
0*)#1: right hand side
6!aluated first
02)#1: left hand side
Processed second
,he key thing to note is that the processing happens right to left. 6!erything
to the right hand side is processed first. /nly after that processing is done is
the left hand side considered.
4n this example it?s tri!ial. 4t will become less tri!ial !ery soon so remember
that the right hand side is e!aluated before the left hand side is e!en looked
at.
ps: "omputing uses the phrases 0left hand side1 and 0right hand side1 so
often that they are typically written as 02)#1 and 0*)#1.

104
104
#imple e!aluations
+++ =et+ . 1&& ( !&
*)# &. 1&& !& (
int
'&&
function
<
int
"&
int
'"&
..
int
'"&
5.
Oeta
2)#
'e can see a slightly more in!ol!ed example if we put some arithmetic on
the *)#.
Again: the *)# is e!aluated first.
-irst: Python notices three 0tokens1: the &RR: the name 0<1 and the .R. 4t
creates two integer obFects Fust as it did with the pre!ious example and it
looks up a pre-existing function obFect that does addition of integers.
#econd: Python triggers the addition function to generate a third integer with
the !alue &.R.
,his completes the e!aluation of the *)#.
,hird: Python creates a name 0Oeta1 and attaches it to the freshly created
integer &.R.

105
105
+ames on the *)# d &
+++ -+,,+ . +lph+ ( 0&
*)#
&.
+lph+ 0& (
function
<
int
4&
int
'&&
alpha
int
'4&
..
5.
+ow we will consider a more significantly in!ol!ed example: one with a
name on the *)#.
-irst: Python recogni_es the three tokens on the *)#. ,hese are the name
0alpha1 the 0<1 and the literal integer 8R.
#econd: it looks up the names. ,he 0alpha1 is replaced by the integer &RR
and the name 0<1 is replaced by the actual function that does addition. ,he
token 8R is replaced by the actual integer 8R in memory.
,hird: it runs the function to gi!e an integer &8R obFect in memory.

106
106
+ames on the *)# d .
+++ -+,,+ . +lph+ ( 0&
2)#
8.
gaNNa
int
'4&
/nly after all that is the 2)# considered: and the name 0gaNNa1 is created
and attached to the newly minted integer.

107
107
#ame name on both sides d R
gaNNa
int
'4&
#tarting
position
+++ print(-+,,+)
'4&
+ow JfinallyBK we get to the interesting case.
'e start with the name gaNNa being attached to the !alue &8R.

108
108
#ame name on both sides d &
+++ -+,,+ . -+,,+ ( 1&
*)#
&. -+,,+ 1& (
function
<
int
'&
int
'4&
gaNNa
int
'(&
..
5.
8.
,hen we run an assignment that has the name gaNNa on both the left and
right hand sides.
Again: first of all Python focuses exclusi!ely on the *)#.
,he expression 0gaNNa < '&1 is e!aluated to gi!e rise to an integer &SR in
Python memory.

109
109
#ame name on both sides d .
+++ -+,,+ . -+,,+ ( 1&
S.
Y.
2)#
int
'(&
int
'4& gaNNa
*)#
int
'(&
int
'4& gaNNa
*)#
/nly once that e!aluation is complete does Python turn its attention to the
2)#.
,he name gaNNa is going to be attached to the integer &SR in Python
memory. +o attention is paid to where the integer &SR came from.
,he name gaNNa is already in use and is attached to the integer &8R. 4ts
attachment is changed to the new integer &SR.

110
110
#ame name on both sides d 5
+++ -+,,+ . -+,,+ ( 1&
[.
X.
2)#
int
'(& gaNNa
int
'(&
int
'4& gaNNa

+o longer
used.
/nce that is done there are no remaining references to the old integer &8R.
Python automatically cleans it up: freeing the space for re-use.
,his is a process called 0garbage collection1. 4n some languages you ha!e
to free up unused space yourselfO in Python the system does it for you
automatically.

111
111
0#yntactic sugar1
thing <R '& thing R thing < '&
thing UR '& thing R thing U '&
thing WR '& thing R thing W '&
thing /R '& thing R thing / '&
thing WWR '& thing R thing WW '&
thing XR '& thing R thing X '&
,he operation of modifying a !alue is so common that Python: and some
other languages: ha!e short-cuts in their syntax to make the operations
shorter to write. ,hese operations are called 0augmented assignments1.
,his sort of short-cut for an operation which could already be written in the
language is sometimes called 0syntactic sugar1.

112
112
Deleting a name % &
+++ print(thin-)
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+
+++ thin- . 1
+++ print(thin-)
'
KaNeArror) naNe .thing. is not defined
nknown
!ariable
,here?s one last aspect of attaching names to !alues hat we need to
consider. )ow do we delete the attachment9
-irst of all: let?s see what it looks like when we refer to a name that isn?t
known to the system. ,he error message is @uite straightforward:
naNe .thing. is not defined
4f we then create the name and attach it to a !alue: the integer & in this
example: we can then use the name without error message.

113
113
Deleting a name % .
+++ print(thin-)
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+
+++ del thin-
+++ print(thin-)
'
KaNeArror) naNe .thing. is not defined
nknown
!ariable
Nnown
!ariable
,o delete the attachment we use the Python command 0del1. ,he command
del thing
returns us to the state where the name is no longer known.
Hou can delete multiple names with the slightly extended syntax
del thing'$ thing"$ thing3
,his is e@ui!alent to
del thing'
del thing"
del thing3
but slightly shorter.

114
114
"ommon mistake
a R '&
O R 8
a R a < O
O R a U O
a R '8
O R a U O
R 1# U 8
R '&
O Z 1& U 8 R 3
a has now changedB
2ater in the course: 0tuples1
#a$O* R #a<O$ aUO*
B
'hile we are looking at attaching names to !alues and changing those
!alues: we will take the time to re!iew a common 0rookie mistake1 especially
among people who do linear transformations.
#uppose we want to encode the mapping
we need to be careful not to use a 0half-transformed1 state in the second
half of the transformation. 4f we calculate the new !alue for one coordinate
we can?t Jtri!iallyK use it in the calculation of the new !alue of the second
coordinate.
2ater in this course when we look at 0tuples1 we will see a slick Python way
to fix this problem.
(
a
b
)

(
a+b
ab
)

115
115
Progress
Assignment
#trictly right to left
;e etc. 0syntactic sugar1
thing R thing < '&
thing R thing < '&
.nd &st
thing <R '&
Deletion del thing

116
116
/ur first 0real1 program
'.4'4"'3(6"383&Q(
$
KNOerS
python3 *qrt.py
!.&
'e ha!e to write s[rt.py
-irst: the maths.
,hen: the Python.
'e now ha!e enough to make a start on 0real programming1. 'e will need
some more Python elements but we can meet them as we need them rather
than up front.
'e are going to write a program that prompts for a number and then
calculates and prints out its s@uare root.
-irst we will re!iew the maths of calculating s@uare roots so that we know
what we are coding. ,hen we will do it in Python.

117
117
#@uare root of ..R by 0bisection1
04nter!al of uncertainty1
R.R too small for f.
..R too large for f.
R.R ^ f. ^ ..R
,he techni@ue we are going to use is called 0bisection1. 4f you know this
techni@ue you can relax for the next few slides. Please don?t snore. h
'e are going to go through it by hand for a few iterations because when we
come to implement it in Python it is important that any confusion is due to
the Python: and not the maths the Python is implementing.
,he trick is to identify a range of !alues that must contain the actual !alue
of f.. ,hat is: we identify a lower bound that is less than f. and an upper
bound that is greater than f..
'e then ha!e some way Jwhich we will explain in the following slidesK to
impro!e that estimate by reducing the length of that inter!al of uncertainty.
,o be precise: we will cut the uncertainty in half which is why the process is
called 0bisection1.
'e start by taking a lower bound of xeR: which is definitely lower than xef.
because yeR
.
eR^.: and an upper bound of xe.: which is definitely higher
than xef. because ye.
.
e8`..

118
118
#@uare root of ..R by bisection d &
7id-point: &.R
#&.& < ".&* / ".&
'.&
'.&WW"
'.&
#o: whatPs the trick for hal!ing the inter!al of uncertainty9
'e find the midpoint of the inter!al. 4n this case it?s ob!ious: the half-way
point between xeR and xe. is xe&.
,hen we s@uare it to find its corresponding !alue of y. 4n this case ye&
.
e&.

119
119
#@uare root of ..R by bisection d .
'.&WW" 7 ".&
&.R ^ f. ^ ..R
so change lower bound
#o what9
'ell: ye& is less than ye. so the corresponding x-!alue: xe& makes an
acceptable lower bound for the inter!al of uncertainty. And if we change our
lower bound to this !alue then our inter!al only runs from xe& to xe. with
total length &: rather than its original length ..
'e ha!e hal!ed our uncertainty.
4f we can do this trick multiple times then we will reduce the inter!al of
uncertainty !ery @uickly to a length so small as to be irrele!ant.

120
120
#@uare root of ..R by bisection d 5
7id-point: &.S
#'.& < ".&* / ".&
'.(
'.(WW"
"."(
#o we do it again. ,he new mid-point lies at xe&.S. ,his has a corresponding
y-!alue of ye...S.

121
121
#@uare root of ..R by bisection d 8
'.(WW" + ".&
so change upper bound
&.R ^ f. ^ &.S
ye...S is greater than ye. so we can use the corresponding x-!alue of
xe&.S as our new upper bound. +ow the inter!al of uncertainty is hal!ed in
length again to be g.

122
122
#@uare root of ..R by bisection d S
7id-point: &..S
#'.& < '.(* / ".&
'."(
'."(WW"
'.(6"(
'e find the new mid-point again: xe&..S. #@uaring this gi!es the
corresponding y-!alue ye&.SY.S.

123
123
#@uare root of ..R by bisection d Y
'."(WW" 7 ".&
so change lower bound
&..S ^ f. ^ &.S
ye&.SY.S is less than ye. so we change the lower bound. /ur inter!al of
uncertainty now has length u.

124
124
#@uare root of ..R by bisection d [
7id-point: &.5[S
#'."( < '.(* / ".&
'.38(
'.38(WW"
'.9Q&6"(
And again3

125
125
#@uare root of ..R by bisection d X
'.38(WW" 7 ".&
so change lower bound
&.5[S ^ f. ^ &.S
3to gi!e an inter!al of length v.

126
126
6xercise Y
&.5[S ^ f. ^ &.S
One more iteration.
-ind the mid-point.
#@uare it.
"ompare the s@uare to ..R.
Do you chane the
lower or upper bound!
. minutes
Please make sure that you understand the principle and do one more
iteration by hand.

127
127
nderstanding before Programming
Apologies for spending so long on the maths but this is a general situation.
Hou must understand the situation before you can program it.

128
#o now letPs start the implementation of this process in Python.
'e will do exactly the same maths: but this time with Python syntax.
-irst we set the end points for the inter!al of uncertainty and attach names
to the two x-!alues.
,he names lower and pper are attached to the end points:
lower R &.&
pper R ".&
'e establish the x-!alue of the mid-point and attach the name Niddle to it:
Niddle R #lower<pper*/"
,his is exactly where we started last time: but we ha!e attached Python
names to the !alues.
128
And now using PythonB
lower R &.&
pper R ".&
Niddle R #lower<pper*/"

129
129
And now using Python d .
NiddleWW" 7 ".&
Hre
lower R Niddle
print#lower$ pper*
".& '.&
+ext: we find the y-!alue corresponding to the mid-point Jby s@uaring the
x-!alue &.RK and ask if it is less than ..R: the number whose s@uare root we
are looking for.
NiddleWW" 7 ".&
*ecall that this will return a Python boolean !alue: Hre or >alse.
,he s@uared !alue is &.R which is less than ..R Ji.e. we get HreK so we
raise the lower limit of the inter!al to the mid-point.
lower R Niddle
4n this example we print the x-!alue at each end of the inter!al to track our
progress.

130
130
And now using Python d 5
Niddle R #lower<pper*/"
print# NiddleWW"* Niddle$
"."( '.(
#o we do it again.
'e re-calculate the x-!alue for the mid-point. +ote that because we
changed the !alue the name lower was attached to the Python instruction is
identical to the one we ga!e first time round:
Niddle R #lower<pper*/"
'e do some additional printing to track progress.

131
131
And now using Python d 8
NiddleWW" 7 ".&
>alse
pper R Niddle
print#lower$ pper*
'.( '.&
Again: we ask if the mid-point?s y-!alue Ji.e. its x-!alue s@uaredK is abo!e or
below our target of ..R:
NiddleWW" 7 ".&
and this time get a boolean >alse. Because the !alue is greater than ..R
Jour test e!aluates to >alseK we change the !alue of the upper bound of the
inter!al by attaching the name upper to the x-!alue of the mid-point:
pper R Niddle
,he !alues being handled are exactly the same as they were when we did it
as 0raw maths1 but this time they ha!e names.

132
132
And now using Python d S
Niddle R #lower<pper*/"
print# NiddleWW"* Niddle$
'.(6"( '."(
'e now do a third iteration.

133
133
And now using Python d Y
NiddleWW" 7 ".&
Hre
lower R Niddle
print#lower$ pper*
'.( '."(
,his time the test e!aluates to Hre so we change lower.

134
134
And now using Python d [
Niddle R #lower<pper*/"
print# NiddleWW"* Niddle$
'.9Q&6"( '.38(
-ourth iteration.

135
135
And now using Python d X
NiddleWW" 7 ".&
Hre
lower R Niddle
print#lower$ pper*
'.( '.38(
And another Hre so we change lower again.
And thatPs enough of stepping through it manually.

136
136
2ooking at the Python code
lower R &.&
pper R ".&
Niddle R #lower<pper*/"
print#Niddle$ NiddleWW"*
NiddleWW" 7 ".&
lower R Niddle pper R Niddle
9
print#lower$ pper*
2et?s look at the Python code we ha!e used.
'e started by initiali_ing our inter!al of uncertainty:
lower e R.R
upper e ..R
,hen we started the operations we would repeat by calculating the x-!alue
of the mid-point:
Niddle R #lower<pper*/"
'e s@uared this and compared the s@uared y-!alue with ..R: our target
!alue:
NiddleWW" 7 ".&
and: based on whether this e!aluated to ,rue or -alse we ran either:
lower R Niddle
or:
pper R Niddle
,hen we ran the iteration again.

137
137
2ooking at the Python structures
lower R &.&
pper R ".&
Niddle R #lower<pper*/"
print#Niddle$ NiddleWW"*
NiddleWW" 7 ".&
lower R Niddle pper R Niddle
9
print#lower$ pper*
#et up
2oop
"hoice
#tructurally: we need to be able to do two things beyond our current
knowledge of Python. 'e need to be able to run certain instructions time
and time again J0looping1K and we need to be able to choose one of two
different actions depending on whether a boolean !alue is Hre or >alse.

138
138
2ooping
Before
2oop test
2oop body
After

#hould the
loop run
JagainK9
'hat is
run each
loop9
'e will address looping first.
A loop has a number of components.
#trictly not part of the loop are the 0before1 and 0after1 sections but these
gi!e context and may use !alues needed by the loop.
,he loop itself must ha!e some sort of test to indicate whether the loop
should run again or whether the looping can stop and control can pass to
the 0after1 code.
,hen there must be the set of instructions that will be run each time the loop
repeats. 'e call this the 0body1 of the loop.

139
139
2oop example: "ount from & to &R
nNOer R '
nNOer 7R '&
print#nNOer*
nNOer <R '
print#.Mone-.*

Before
2oop test
2oop body
After

2et?s consider an example that?s simpler than our s@uare root loop: counting
from & to &R.
/ur 0before1 block initiali_es the attachment of a name nNOer to a !alue ':
nNOer R '
/ur test sees if nNOer is attached to a !alue less than or e@ual to '& Jour
final !alueK:
nNOer 7R '&
*ecall that this e!aluates to a boolean !alue.
4f the test e!aluates to Hre then we run the loop body. ,his has two lines:
the first to print the !alue of nNOer and the second to increase it by one:
print#nNOer*
nNOer <R '
4f the test e!aluates to >alse then we don?t loop and exit the structure. 'e
ha!e a pointless print statement as a place-holder for more substanti!e
code in serious scripts:
print#.Mone-.*
,his is what we want to encode in Python.

140
140
2oop example: "ount from & to &R
nNOer R '
nNOer 7R '&
print#nNOer*
nNOer <R '
print#.Mone-.*

nNOer R '
while
print#nNOer*
nNOer <R '
print#.Mone-.*
) nNOer 7R '&

,his is how we encode the structure in Python. 'e will examine it element
by element: but at first glance we obser!e a 0while1 keyword and a colon
on either wise of the test and the loop body being indented four spaces.

141
141
2oop test: "ount from & to &R
nNOer R '
while
print#.Mone-.*
) nNOer 7R '&
0while1 keyword
loop test
colon
print#nNOer*
nNOer <R '

'e will start by looking at what we ha!e done to the test. ,he test itself is
nNOer 7R '
which is a Python expression that e!aluates to a boolean: Hre or >alse.
'e precede the test expression with the Python keyword 0while1. ,his is
what tells Python that there?s a loop coming. 4t must be directly followed by
an expression that e!aluates to a Boolean.
'e follow the test expression with a colon. ,his is the marker that the
expression is o!er and must be the last element on the line.
+ote that the test e!aluates to ,rue for the loop to be run and -alse for the
loop to @uit. 'e are testing for 0shall the loop keep going1 not 0shall the loop
stop1. Python tests for while: not until.

142
142
2oop body: "ount from & to &R
nNOer R '
while
print#.Mone-.*
) nNOer 7R '&
loop body
indentation
print#nNOer*
nNOer <R '

,he loop body: the code that is repeated: appears on the lines following the
0while line1. Both its lines are indented by four spaces each.
+ote that the 0after1 section is not indented.

143
143
nNOer R '
while nNOer 7R '& )
print#nNOer*
nNOer <R '
print#.Mone-.*
2oop example: "ount from & to &R
while'.py
$
'
"
3
4
(
6
8
9
Q
'&
Mone-
python3 while1.py
$
-irst let?s check that this really works. 4n the file while'.py in your home
directories you will find exactly the code shown in the slide. *un it and watch
Python count from & to &R.

144
144
Python?s use of indentation
nNOer R '
while nNOer 7R '& )
p

print#nNOer*
nNOer <R '
-our spaces? indentation
indicate a 0block1 of code.
,he block forms
the repeated lines.
,he first unindented line
marks the end of the block.
rint#.Mone-.*
,he four spaces of indentation are not cosmetic. A se@uence of lines that
ha!e the same indentation form blocks in Python and can be thought of as a
single unit of code. 4n this case both lines get run JagainK or neither of them
do.
,he indented block is ended by the first line that follows it with no
indentation.

145
145
c.f. 0legalese1
&
&JaK
&JbK
&JbKJiK
&JbKJiiK
&JbKJiiiK
&JcK
.
5

4f this seems a little alien consider the 0legalese1 of complex documents.
,hey ha!e paragraphs: sub-paragraphs and sub-sub-paragraphs etc.: each
indented relati!e to the one containing them.

146
146
/ther languages
#hell
"
while ...
do
...
...
done
while ...
\
...
...
]
do ... done
\ ... ]
#yntax
#yntax
...
...
"larity
"larity
7arking blocks of code is one of the places where computing languages
differ from one another.
#ome ha!e special words that appear at the start and end of blocks like 0do1
and 0done1. /thers use !arious forms of brackets like 0\1 and 0]1.
4nterestingly: programmers in these languages typically also indent code
within the blocks for !isual clarity. Python simply uses the indentation for its
core syntax rather than Fust for ease of reading.
Purely for interest: the #hell and " !ersions of while'.py are also in your
home directory as while'.sh and while'./.

147
147
Progress
while ... ) Oefore
while test )
action
1
action
2
action
3
afterwards
test to keep looping
code blocks
indentation

148
148
6xercise [
S minutes
-or each script:
Predict what it will do.
*un the script.
'ere you right9
while".py
while3.py
while4.py
while(.py

,o kill a running script: "trl " ;


while6.py

149
149
&.S &.5[S
Back to our s@uare root example
&.R ..R
&.R
R.R ..R
..R
&.R &.S
R.S
&..S &.S
R..S
R.&.S
Vg
Vg
Vg
Vg
uncertainty
&.RV&R
c&S
tolerance
'hat we get
'hat we want
+ow let?s return to our s@uare root example. 'e ha!e a loop the body of
which hal!es the length of the inter!al of uncertainty. 'e need to put this
into a Python loop so we need a corresponding loop test.
/ne typical approach is to test to see if the inter!al is longer than some
acceptable !alue. 4n this case we will demand that the inter!al ha!e length
no longer than &R
-&S
. J4t will take S& hal!ings to get from an initial length of
..R to something less than &R
-&S
.K
A common name for an 0acceptable uncertainty1 is a 0tolerance1: the amount
of uncertainty we are prepared to tolerate.

150
150
Neep looping while 3 9
tolerance ` uncertainty
while n/ertainty + toleran/e )

Do stuff.
'e need a Python test for this. *ecall that Python needs a test that
e!aluates to Hre for the loop body to run. /ur test then is 1is the current
uncertainty larger than the acceptable tolerance91
'e will set a name: toleran/e: to ha!e the !alue '.&eU'(: calculate an
uncertainty each loop and perform the test
n/ertainty + toleran/e
4f this is Hre then we need to keep going.
4f it is >alse then we can stop.

151
151
#@uare root: the loop
lower R &.&
pper R ".&
toleran/e R '.&eU'(
n/ertainty R pper U lower
while n/ertainty + toleran/e )
Niddle R #lower < pper*/"
n/ertainty R pper U lower
print#lower$ pper*
9
#et up
2oop
"hoice
#o: if we return to our basic structure we can now see how Python?s while
syntax fits in.
'e establish a tolerance.
'e establish an initial uncertainty.
'e test for
n/ertainty + toleran/e
as the loop test.
'e recalculate the uncertainty at the end of the loop block for use in the
next round of the test.
All we ha!e to do now is to add in the choice block.

152
152
"hoosing

NiddleWW" 7 ".&
lower R Niddle pper R Niddle
9

"hoice
NiddleWW" 7 ".& Hre >alse or
Hre
>alse
lower R Niddle
pper R Niddle
/nce again we ha!e a test followed by some actions. ,his time: howe!er:
the test doesn?t decide whether or not to run a block of code again: but
rather which of two blocks of code to run once.
/ur test % a Python expression that e!aluates to a boolean % is simply:
NiddleWW" 7 ".&
and if this e!aluates to Hre then we change the lower bound:
lower R Niddle
and if it e!aluates to >alse then we change the upper bound:
pper R Niddle
6ither way: once one or the other has run we mo!e on and do not return to
the test.

153
153
#imple example
te!t R inpt#.KNOerS .*
nNOer R int#te!t*
if nNOer X " RR &)
print#.ABen nNOer.*
else)
print#.Cdd nNOer.*
print#.Hhat was fn-.*
ifthenelse'.py
$
KNOerS
ABen nNOer
Hhat was fn
python3 i'thenel*e1.py
$
KNOerS
Cdd nNOer
Hhat was fn
python3 i'thenel*e1.py
"
#
Again: we will look at an example that demonstrates Fust the structure.
,here is a script in your home directories called ifthenelse'.py which
illustrates the structure on its own.
7athematical note:
,he script tests for a number being e!en by using the 0remainder1 operator
0X1 to calculate the remainder if we di!ide by . and testing for that remainder
being R.

154
154
if3then3 else3 % &
if
else )
print#.ABen nNOer.*
pper R Niddle
) nNOer X " RR &
if keyword
,est
"olon
print#.Hhat was fn-.*
,he first line of the test looks !ery similar to the while syntax we ha!e
already seen. 4n this case: howe!er: it uses a new keyword: 0if1.
,he if keyword is followed by the test: a Python expression that e!aluates
to a boolean.
,he line ends with a colon.

155
155
if3then3 else3 % .
if
else )
print#.ABen nNOer.*
pper R Niddle
) nNOer X " RR &
*un if test is "rue
4ndentation
print#.Hhat was fn-.*
,he test line is immediately followed by the block of code that is run if the
test e!aluates as Hre.
Because it is a block of code it is indented by four spaces to mark it as a
block. ,his example has a single line: but the block can be as long as you
want.
,his block is sometimes called the 0then-block1 because 0if the test is Hre
then run this block1.

156
156
if3then3 else3 % 5
if
else )
print#.ABen nNOer.*
pper R Niddle
) nNOer X " RR &
else) keyword
*un if test is False
4ndentation
print#.Hhat was fn-.*
After the then-block comes another new keyword: 0else)1. ,his is not
indented and is le!el with the 0if1 to indicate that it is not part of the then-
block.
4t is then followed by a second block of code: know as the 0else-block1. ,his
is the code that is run if the test e!aluates as >alse.
Again: because it is a block of code it is indented.
,he else keyword and its corresponding block are optional. Hou can do
nothing if the test returns >alse. ,he then-block is compulsory.

157
157
if3then3 else3 % 8
if
else )
print#.ABen nNOer.*
pper R Niddle
) nNOer X " RR &
*un afterwards
regardless of test
print#.Hhat was fn-.*
After the else-block the script continues. ,he print line is unindented so is
not part of the else-block. ,his line is run regardless of the result of the test.

158
158
/ur s@uare root example
Niddle R #lower < pper*/"
if
else )
print#lower$ pper*
lower R Niddle
pper R Niddle
Before
) NiddleWW" 7 ".&
After
if3 block
2et?s return to our s@uare root example.
)ere we ha!e the creation of a mid-point x-!alue followed by an if-test on it:
Niddle R #lower<pper*/"
if NiddleWW" 7 ".&)
,his switches between two single-line code blocks. 4f the test e!aluates to
Hre then the then-block is run:
lower R Niddle
and if it e!aluates to >alse then the else-block is run:
else)
pper R Niddle
After one or other is run the print statement is always run:
print#lower$ pper*
All we ha!e to do now is to fit it inside our while loop.

159
159
Progress
if ... ) Oefore
if test )
action
1
action
2
else)
action
3
afterwards
else)
choice of two
code blocks
indentation

160
160
6xercise X
S minutes
-or each script:
Predict what it will do.
*un the script.
'ere you right9
ifthenelse".py
ifthenelse3.py
ifthenelse4.py
ifthenelse(.py


161
161
Back to our example
lower R &.&
pper R ".&
toleran/e R '.&eU'(
n/ertainty R pper U lower
while n/ertainty + toleran/e )
Niddle R #lower < pper*/"
n/ertainty R pper U lower
print#lower$ pper*
if NiddleWW" 7 ".& )
else )
pper R Niddle
lower R Niddle
Doubly
indented
if starts
indented
#o how do we embed an if-test with its two code blocks inside a while-loop
as the loop?s body9
,he body of the while-loop is indented four spaces. #o we start the if-test
indented four spaces and make its indented blocks doubly indented.

162
162
2e!els of indentation
lower R &.&
pper R ".&
toleran/e R '.&eU'(
n/ertainty R pper U lower
while n/ertainty + toleran/e )
Niddle R #lower < pper*/"
n/ertainty R pper U lower
print#lower$ pper*
if NiddleWW" 7 ".& )
else )
pper R Niddle
lower R Niddle

8 spaces
X spaces
#o if our standard indentation is four spaces then the doubly indented
sections are indented eight spaces.
,his is a simple example with only two le!els of indentation. Python can
snest? blocks much further than this.

163
163
,rying it out
toleran/e R '.&eU'(
lower R &.&
pper R ".&
n/ertainty R pper U lower
while n/ertainty + toleran/e )
Niddle R #lower < pper*/"

if NiddleWW" 7 ".&)
lower R Niddle
else)
pper R Niddle
print#lower$ pper*
n/ertainty R pper U lower
s[rt'.py
$
'.& ".&
'.& '.(
'."( '.(
'.38( '.(
'.38( '.438(
'.4&6"( '.438(
'.4&6"( '.4"'98(
...
'.4'4"'3... '.4'4"'3...
python3 *qrt1.py
h
,he file s[rt'.py in your home directories contains the code as described
in the slide. 4t produces a !ery nice approximation to the s@uare root of ..

164
164
#cript for the s@uare root of ".&
lower R &.&
toleran/e R '.&eU'(
n/ertainty R pper U lower
while n/ertainty + toleran/e )
Niddle R #lower < pper*/"
n/ertainty R pper U lower
print#lower$ pper*
pper R !.&
if NiddleWW" 7 !.& )
else )
pper R Niddle
lower R Niddle

f..R
f..R
#o now we ha!e the script for the s@uare root of .. ,he next thing to do is to
generali_e it to produce s@uare roots of any number.

165
165
4nput target
te!t R inpt#.KNOerS .*
nNOer R float#te!t*
if NiddleWW" 7 nu,=er )
3
/b!iously we ha!e to input the number whose s@uare root we want. 'e
ha!e already seen how to do this and to con!ert it from a string into a
floating point number:
te!t R inpt#.KNOerS .*
nNOer R float#te!t*
/nce we ha!e the number the test
NiddleWW" 7 ".&
is straightforwardly extended to
NiddleWW" 7 nNOer

166
166
4nitial bounds9
# ` &.R &.R ^ $# ^ #
&.R ` # &.R ` $# ` #
lower R >
pper R >
if...then...else...
'e ha!e to set initial bounds for our inter!al of uncertainty.
,his is where it is important that you think about the problem before coding.
4f the number whose s@uare root is sought is less than & then the s@uare
root is bigger than the number and less than &. 4f it is larger than & then its
s@uare root is less than the number and bigger than &.
4n Python terms this means we can test for the number being less than &
and set the bounds accordingly.

167
167
4nitial bounds
if nNOer 7 '.& )
lower R nNOer
pper R '.&
else )
lower R '.&
pper R nNOer
4t looks like this.

168
168
Aeneric s@uare root script9
te!t R inpt#.KNOerS.*
nNOer R float#te!t*
if nNOer 7 '.&)
lower R nNOer
pper R '.&
else)
lower R '.&
pper R nNOer
toleran/e R '.&eU'(
n/ertainty R pper U lower
while n/ertainty + toleran/e)
Niddle R #lower<pper*/".&
if NiddleWW" 7 nNOer)
lower R Niddle
else)
pper R Niddle
n/ertainty R pper U lower
print#lower$ pper*
ser input
4nitiali_ation
Processing
/utput
s[rt".py
,his gi!es us enough of a script to see the o!erarching structure of a script:
'e start with getting the data we need from the outside world. J0input1K
,hen we set up any initial state we need based on that. J0initiali_ation1K
,hen we do our processing.
-inally we re!eal our results. J0output1K
,ypically the processing phase takes longest to run: but note that: as here: it
is often not the maFority of the lines of code.

169
169
e!it#*
+egati!e numbers9
+eed to catch negati!e numbers
if nNOer 7 &.&)
print#.KNOer Nst Oe positiBe-.*
>uit immediately
ielsei is optional
'e can impro!e our code. A step missing from the pre!ious script is 0input
!alidation1 where we check that the input makes sense. 'e ought to check
that we ha!e not been asked to generate the s@uare root of a negati!e
number.

170
170
0"hained1 tests
te!t R inpt#.KNOerS.*
nNOer R float#te!t*
if nNOer 7 &.&)
print#.KNOer Nst Oe positiBe-.*
e!it#*
if nNOer 7 '.&)
lower R nNOer
pper R '.&
else)
lower R '.&
pper R nNOer
...
ser input
4nput !alidation
4nitiali_ation
,he input !alidation phase comes straight after the input itself.

171
171
elif
0"hained1 tests % syntactic sugar
te!t R inpt#.KNOerS.*
nNOer R float#te!t*
if nNOer 7 &.&)
print#.KNOer Nst Oe positiBe-.*
e!it#*
nNOer 7 '.&)
lower R nNOer
pper R '.&
else)
lower R '.&
pper R nNOer
...
elif: 0else if1
s[rt3.py
)owe!er: it can be integrated with the initiali_ation phase: and often is. After
all: if you can?t initiali_e from the input then the input isn?t !alid.
,his leads us to a multi-stage test of the number whose s@uare root we
want:
4s it less than R9
4f not: is it less than &9
4f not then3
Python has an extension to the simple if3else3 test to allow for the 0if
not then is it31 situation.
0elif1 introduces a test and a corresponding block of code. ,he code is
called only if the pre!ious if3 test failed and its own test passes.

172
172
'ithout elif3
te!t R inpt#.KNOerS.*
nNOer R float#te!t*
if nNOer 7 &.&)
print#.KNOer is negatiBe..*
else)
if nNOer 7 '.&)
print#.KNOer is Oetween ^ero and one..*
else)
if nNOer 7 ".&)
print#.KNOer is Oetween one and two..*
else)
if nNOer 7 3.&)
print#.KNOer is Oetween two and three..*
else)
print#.KNOer is three or Nore..*
#tacked clauses get unwieldy
,o take an extreme example: consider this multi-le!el test. ,he continual
nesting inside the else clauses causes the whole script to drift to the right.

173
173
'ith elif3
te!t R inpt#.KNOerS.*
nNOer R float#te!t*
if nNOer 7 &.&)
print#.KNOer is negatiBe..*
elif nNOer 7 '.&)
print#.KNOer is Oetween ^ero and one..*
elif nNOer 7 ".&)
print#.KNOer is Oetween one and two..*
elif nNOer 7 3.&)
print#.KNOer is Oetween two and three..*
else)
print#.KNOer is three or Nore..*
Applying elif causes e!erything to slide back into place.

174
174
Progress
+ested structures
if 3 )
3
elif 3 )
3
elif 3 )
3
else)
3
while 3 )
if 3 )
"hained tests
,esting inputs to scripts
e!it#*

175
175
6xercise Z
S minutes
e!er/iseQ.py
&. 6dit the s@uare root script to catch negati!e numbers.
Only do the second part after
you ha%e the first part wor&in!
.. 6dit the s@uare root script to ask for the tolerance.
,he tolerance must be bigger than SV&R
c&Y
.
,est for that.

176
176
"omments
'e ha!e written our first real Python script
'hat did it do9
Why did it do it9
+eed to annotate the script
s[rt3.py is a real program.
+ow imagine you pass it to someone else or put it away for twel!e months
and come back to it forgetting how you wrote it in the first place.
"hances are that the reader of your script might like some hints as to what it
is doing and why.
0"omments1 in computer programs are pieces of text that describe what ios
going on without getting in the way of the lines of code that are executed.

177
177
Python comment character
,he 0hash1 character
2ines starting with 0=1 are ignored
Partial lines starting 0=1 are ignored
sed for annotating scripts
=
a.k.a. 0pound1: 0number1: 0sharp1
Python: in common with most other scripting languages: uses the hash
character to introduce comments. ,he hash character and e!erything
beyond it on the line is ignored.
J#trictly speaking the musical sharp character 0 1 is not the same as 0=1 but
people get !ery sloppy with similar characters these days. ,his isn?t at all
rele!ant to Python but the author is an annoying pedant on the correct use
of characters. And don?t get him started on people who use a hyphen when
they should use an en-dash or em-dash.K

178
178
Python commenting example
_ @/ript to /al/late s[are roots Oy Oise/tion
_ #/* PoO Mowling "&'". Li/ensed nder GPL B3.&
te!t R inpt#.KNOerS.*
nNOer R float#te!t* _ Keed a real nNOer
_ Hest nNOer for Balidity$
_ set initial Oonds if C`.
if nNOer 7 &.&)
print#.KNOer Nst Oe nonUnegatiBe-.*
e!it#*
elif nNOer 7 '.&)
lower R nNOer
pper R '.&
else)
lower R '.&
pper R nNOer
,his is what a commented script looks like.

179
179
/n a real nix system3
_-/sr/Oin/python3
_ @/ript to /al/late s[are roots Oy Oise/tion
_ #/* PoO Mowling "&'". Li/ensed nder GPL B3.&
te!t R inpt#.KNOerS.*
nNOer R float#te!t* _ Keed a real nNOer
7agic line for executable files
$
instead of
'u=+r.py
$ python3 'u=+r.py
Hou may encounter a 0hash pling0 first line in many imported Python scripts.
,his is part of some 0nix magic1 that lets us simplify our command lines.
'e can?t demonstrate it here because the 7"# file ser!er doesn?t support
nix semantics.

180
180
Progress
"omments
=
0=1 character

181
181
6xercise &R
. minutes
"omment your s@uare root script from exercise Z.

182
182
*ecap: Python types so far
'hole numbers
-loating point numbers
,ext
Booleans
-&.[
5.&8&SZ.YS5SXZ[Z5
.Hhe /at sat on the Nat..
,rue -alse
"omplex numbers J&.R ; ..RFK
'e are about to introduce a new Python type: so we will take a moment to
remind ourseo!es of the !arious Python types we ha!e met already.

183
183
2ists
[ .hydrogen.$ .heliN.$ .lithiN.$ .OerylliN.$
.Ooron.$ :$ .thoriN.$ .prota/tiniN.$ .raniN. ]
[ U3.'4'(Q"6(3(9Q8Q3$ U'.(8&8Q63"68Q49Q66$
&.&$ '.(8&8Q63"68Q49Q66$ 3.'4'(Q"6(3(9Q8Q3 ]
[ "$ 3$ ($ 8$ ''$ '3$ '8$ 'Q ]
,he new Python type we are going to meet is called a 0list1.

184
184
'hat is a list9
A sequence of !alues
4ndi!idual !alue identified
by position in the se@uence
,he names of the elements
0helium1 is the name of the
second element
Dalues stored in order Atomic number order
hydroen' helium' lithium' beryllium' (' protactinium' uranium
#o what is a list9
A list is simply a se@uence of !alues stored in a specific order with each
!alue identified by its position in that order.
#o for an example consider the list of names of the elements up to uranium.

185
185
'hat is a list9
A sequence of !alues
4ndi!idual !alue identified
by position in the se@uence
,he prime numbers
less than sixty
[ is the fourth prime
Dalues stored in order +umerical order
)' *' +' 7' 11' 1*' 17' 1,' )*' ),' *1' *7' -1' -*' -7' +*' +,
/r the list of primes up to YR.
+ote that a list must be finite.

186
186
"reating a list in Python
+++ pri,e* . ? !, 3, 1, #, 11, 13, 1#, 12@
+++ pri,e*
["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q]
+++ type(pri,e*)
7/lass .list.+
,he whole list
A Python type
A literal list
#o how might we do this in Python9
'e will create a list in Python of the primes less than .R. 'e can do this in a
single line as shown.
A list in Python is a single Python obFect: albeit with multiple contents: and
has its own type: unsurprisingly called 0list1.

187
187
)ow Python presents lists
[ ] 'Q '8 $ '3 $ '' $ 8 $ ( $ 3 $ $ "
#@uare brackets
at the ends
"ommas between items
Python presents Jand acceptsK lists as a series of !alues separated by
commas: surrounded by s@uare brackets.

188
188
#@uare brackets
priNes R ["$ 3$ ($ 8$ ''] 2iteral list
'e are going to meet s@uare brackets used fr a lot of things so 4 will build
up a summary slide of their !arious uses. )ere is use &.

189
189
Python counts from .ero
[ ] 'Q '8 $ '3 $ '' $ 8 $ ( $ 3 $ $ "
8 6 ( 4 3 " ' &
0index1
0!alue1
'e still need to get at indi!idual items in the list. 6ach is identified by its
position in the list.
Python: in common with many programming languages Jbut not allK starts its
count from zero. ,he leading element in the list is 0item number _ero1. ,he
one that follows it is 0item number one1 and so on. ,his number: the position
in the list counting from _ero: is called the 0index1 into the list. ,he plural of
0index1 is 0indices1.
,o keep yourself sane: we strongly recommend the language 0item
number 51 instead of 0the fourth item1.

190
190
2ooking things up in a list
+++ pri,e* . ? !, 3, 1, #, 11, 13, 1#, 12@
[ ] 'Q '8 $ '3 $ '' $ 8 $ ( $ 3 $ $ "
8 6 ( 4 3 " ' &
+++ pri,e*
"
+++
'8
@ & ?
index
pri,e* @ 7 ?
s@uare brackets
#o: how do we get 0item number S1 from a list9
'e can follow the list Jor: more usually: a name attached to the listK with the
index in s@uare brackets.

191
191
#@uare brackets
priNes R ["$ 3$ ($ 8$ ''] 2iteral list
priNes[3] 4ndex into list
And this is the second use of s@uare brackets.

192
192
"ounting from the end
+++ pri,e* . ? !, 3, 1, #, 11, 13, 1#, 12@
[ ] 'Q '8 $ '3 $ '' $ 8 $ ( $ 3 $ $ "
8 6 ( 4 3 " ' &
+++
'Q
pri,e* @ 31 ?
getting at the last item
U' U" U3 U4 U( U6 U8 U9
Python has a trick for getting at the last element of the list. +egati!e indices
are also !alid and count backwards from the end of the list. ,ypically the
only case of this that is used in paractice is that the index U' gets the last
element of the list.

193
193
4nside !iew of a list
list
9
int
'Q
3
priNes
int
'8
int
3
int
"
primesjRk
primesj&k
primesjYk
primesj[k
'e?!e seen these box diagrams for simple Python types already. ,he
structures for lists are a little more complicated but only a little. ,he list type
records how long it is and an ordered set of references to the actual obFects
it contains.

194
194
2ength of a list
priNes
list
9
+++ len
9
(pri,e*)
R
[
7aximum
index is [
len#* function:
length of list
+ote that the length of a list is the number of items it contains. ,he largest
legitimate index is one less than that because indices count from _ero.

195
195
"hanging a !alue in a list
+++ d+t+ . ?'+lph+', '=et+', '-+,,+'@
+++ d+t+?!@
.gaNNa.
+++ d+t+?!@ . 'A'
+++ d+t+?!@
.G.
+++ d+t+
[.alpha.$ .Oeta.$ .G.]
,he list
4nitial !alue
"hange !alue
"heck change
"hanged list
#o far we ha!e created lists all in one go by @uoting a literal list. 'e can use
the indexing notation Js@uare bracketsK to change items in a list too.

196
196
"hanging a !alue in a list % &
+++ d+t+ . ?'+lph+', '=et+', '-+,,+'@
list
3
str
( a l p h a
str
4 O e t a
str
( g a N N a
*ight to left
'e can track what happens in that example in some detail. 'e will start with
the first line: defining the initial list.
As e!er: Python assignment is done right to left. ,he right hand side is
e!aluated as a list of three items: all of themstrings.

197
197
"hanging a !alue in a list % .
+++ d+t+ . ?'+lph+', '=et+', '-+,,+'@
data
list
3
str
( a l p h a
str
4 O e t a
str
( g a N N a
*ight to left
,his then has the name 0data1 attached to it.

198
198
"hanging a !alue in a list % 5
+++ d+t+?!@ . 'A'
*ight to left
data
list
3
str
( a l p h a
str
4 O e t a
str
( g a N N a
str
' G
+ew !alue
+ow we come to the second line which changes one of these list items.
,he right hand side is e!aluated as a string containing a single characters.
,hat obFect gets created.

199
199
"hanging a !alue in a list % 8
+++ d+t+?!@ . 'A'
*ight to left
data
list
3
str
( a l p h a
str
4 O e t a
str
( g a N N a
str
' G
+o longer
referenced
,he assignment causes the reference within the string to be changed to
refer to the new string and to stop referring to the pre!ious one: 0gaNNa1.
4n this case there are now no references to the 0gaNNa1 string.

200
200
"hanging a !alue in a list % S
+++ d+t+?!@ . 'A'
*ight to left
data
list
3
str
( a l p h a
str
4 O e t a
str
' G
Python then clears out the memory used for that old string so that it can
reuse it for something else. ,his process is called 0garbage collection1 in
computing.

201
201
*emo!ing an entry from a list % &
+++ del d+t+?1@
data
list
3
str
( a l p h a
str
4 O e t a
str
( g a N N a
data[&]
data[']
data["]

'e can remo!e entries from the list too with the 0del1 keyword: Fust as we
remo!ed names. ,he del keyword remo!es the reference from the list.

202
202
*emo!ing an entry from a list % .
+++ del d+t+?1@
data
list
"
str
( a l p h a
str
4 O e t a
str
( g a N N a
data[&]
data[']
+o longer
referenced
,his lea!es the string 0Oeta1 no longer referenced by anything.

203
203
*emo!ing an entry from a list % 5
+++ del d+t+?1@
data
list
"
str
( a l p h a
str
( g a N N a
data[&]
data[']
And garbage collection kicks in again.

204
204
*unning off the end
list
9
int
'Q
3
priNes
int
'8
int
3
int
"
primesjXk
'e ha!e remarked on a couple of occasions that the largest !alid index is a
number one less than the length of the list.
#o what happens if you ask for an index greater than the largest legal
!alue9

205
205
*unning off the end
+++ len(pri,e*)
9
+++ pri,e*?#@
'Q
+++ pri,e*?"@
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+
Fnde!Arror) list inde! ot of range
,ype of error Description of error
Hou get an error unsurprisingly.
,he type of the error is an 04ndex6rror1 % something went wrong with an
index.
,he error message specifies that the index asked for was outside the !alid
range.

206
206
*unning off the end
+++ pri,e*?"@ . !3
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+
Fnde!Arror) list assignNent inde! ot of range
#ame type
of error
#imilar description of error
but with 0assignment1
+ote that we can?t use indicies beyond the limit to extend a list either.

207
207
Progress
2ists
index
"ount from _ero
2ength
/!er-running
["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q]
priNes[4]
priNes[&]
len#priNes*
priNes[9]
Deletion del priNes[6]

208
208
6xercise &&
S minutes
,rack what is happening to this list at each stage.
nu,=er* . ?1, #, 11, 13, 1#, 12, !2, 31@ +++
nu,=er*?1@ . 3 +++
del nu,=er*?3@ +++
nu,=er*?3@ . 3# +++
nu,=er*?0@ . nu,=er*?1@ +++
Do this by hand. After each line: work out what you think numbers will be
and then print it to see if you were right.
,he script e!er/ise''.py will tell you if you were right.

209
209
)ow can we add to a list9
list
9
int
'Q
3
int
'8
int
"

list
Q
int
'Q
3
int
'8
int
"
int
"3
9
#ame list
6xtra item
+ew length
#o: how can we extend a list9

210
210
Appending to a list
+++ pri,e*
["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q]
+++ pri,e*
+++ pri,e*
["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q$
(!3) +ppend .
,he list is now updated
] "3
A function built into a list
,his is the Python syntax for appending an item to the end of a list. Hou
won?t recognise the syntaxO it is something new.

211
211
priNes.append#* 9
+++ pri,e* (!3) +ppend .
,he list
A connecting dot
append#*
,he !alue to append
All lists ha!e this
function built in.
#o we need to look at this new construction.
'e ha!e the list: 0priNes1: followed by a dot which acts as a connector.
,his is followed by the name of a function: 0append1. ,his function is not a
standard Python function like print#* or len#*. 4nstead it is a function
that is 0built in1 to the list itself. ,he list has its own function which appends
to that list.
Alternati!ely: think of 0priNes.append#*1 as a function that appends to
priNes.

212
212
07ethods1
(arguments) object function .
a function that has
special access to
the obFect?s data.
Beha!es Fust
like a function
,hese built in functions are called 0methods1 or: more precisely: 0methods of
the obFect1 are used all o!er Python and are a general concept across an
entire type of programming called 0obFect oriented programming1.

213
213
sing the append#* method
+++ print(pri,e*)
["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q]
+++ pri,e* (!3) +ppend .
+++ pri,e* (!2) +ppend .
+++ pri,e* (31) +ppend .
+++ pri,e* (3#) +ppend .
+++ print(pri,e*)
["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q$ "3$ "Q$ 3'$ 38]

,he function doesn?t
return any !alue.
4t modifies
the list itself.

'e can use the append#* method repeatedly to extend the list as far as we
want.

214
214
/ther methods on lists: reBerse#*
+++ nu,=er* . ?0, #, 1, 1@
+++ nu,=er*.reBer*e()
+++ print(nu,=er*)
['$ ($ 8$ 4]

,he function doesn?t
return any !alue.
4t modifies
the list itself.
append#* is not the only method built into lists.
-or example reBerse#* takes the list and re!erses its contents.
+ote that it doesn?t return a re!ersed list as a !alueO t doesn?t return
anything at all.
4t silently re!erses the content of the list itself.
Also note that it takes no argumentO the brackets on the end of the function
are empty.

215
215
/ther methods on lists: sort#*
+++ nu,=er* . ?0, #, 1, 1@
+++ nu,=er*.*ort()
+++ print(nu,=er*)
['$ 4$ ($ 8]
+umerical order.

,he function does not
return the sorted list.
4t sorts the
list itself.
#imilarly: the sort#* method doesn?t return a sorted list but silently sorts
the list internally.

216
216
/ther methods on lists: sort#*
+++ -reeC . ?'+lph+', '=et+', '-+,,+', 'delt+'@
+++ -reeC.*ort()
+++ print(-reeC)
[.alpha.$ .Oeta.$ .delta.$ .gaNNa.]
Alphabetical order
of the words.
7ore or less any type can be sorted. ,ext sorting carries all the cautions
about the complexities of collation that we co!ered under comparisons.

217
217
/ther methods on lists: insert#*
+++ -reeC . '-+,,+', ?'+lph+',
R & .
+++ -reeC.in*ert(
'delt+'@
'here to insert 'hat to insert
'=et+' 1, )
+++ -reeC
[.alpha.$ .gaNNa.$ .delta.] .Oeta.$
&
Displaced
R
,he append#* method sticks an item on the end of a list. 4f you want to
insert an item elsewhere in the list we ha!e the insert#* method.
,he insert#* method takes two arguments:
,he first is the item to be inserted.
,he second is in index where it should go. ,his does not replace the original
item but rather 0shuffles up1 all the items beyond it by one place to make
room.

218
218
/ther methods on lists: reNoBe#*
+++ nu,=er* . ?#, 0,
+++ nu,=er*.re,oBe
+++ print(nu,=er*)
[8$ 4$
#, !, 1, 0@ ",
(")
8$ "$ ($ 4]
c.f. del nNOers["]
alue to remo!e
!ndex to remo!e
,here is a reNoBe#* method.
,his is passed a !alue to remo!e from the list. 4t then remo!es that !alue
from the list: where!er it is in the list.
"ontrast with with del where you had to know the index to remo!e.

219
219
/ther methods on lists: reNoBe#*
+++
+++ nu,=er*.re,oBe
+++ print(nu,=er*)
[8$
(0)
print(nu,=er*)
[8$ 8$ "$ ($ 4$ 4]
8$ "$ ($ 4]
/nly the first instance is remo!ed
,here are two instances of 8.
4f the !alue appears more than once in a list then only the first instance is
remo!ed.
,rying to remo!e something that isn?t there will lead to an error.

220
220
'hat methods are there9
+++ help(nu,=er*)
,elp on list oOTe/t)
/lass list#oOTe/t*
...
a append#...*
a L.append#oOTe/t* UU append oOTe/t to end
...
Pagination:

B
next page
back one page
>
@uit
,hat?s a lot of methods: and it?s only some of them. )ow can we know all of
them9
Hou can always ask for help on any Python obFect and you will be told all
about the methods it possesses. 4t is a !ery formal documentation but the
information is there.
4ncidentally: Python uses a program to paginate its help output. press the
space bar to mo!e on one page: 0B1 to mo!e back a page and 0>1 to 6uit.

221
221
)elp on a single method
+++ help(nu,=er*.+ppend)
,elp on OiltUin fn/tion append)
append#...*
L.append#oOTe/t* UU append oOTe/t to end
Hou can also get help on a single method which is often simpler to deal with.

222
222
#orting a list redux
+++ -reeC . ?'+lph+', '=et+', '-+,,+', 'delt+'@
+++ -reeC.*ort()
+++ print(-reeC)
[.alpha.$ .Oeta.$ .delta.$ .gaNNa.]
*ecall: greek.sort#*
sorts the list 0in place1.
'e noted that the sortJK method sorts the list itself. 6xperience shows that
sorting is one of those operations where people want a sorted copy of the
list @uite often.

223
223
#orting a list redux: 0sortedJK1
+++ -reeC . ?'+lph+', '=et+', '-+,,+', 'delt+'@
+++ print(*orted(-reeC))
+++ print(-reeC)
[.alpha.$ .Oeta.$ .gaNNa.$ .delta.]
sorted#* function
returns a sorted list3
[.alpha.$ .Oeta.$ .delta.$ .gaNNa.]
3and lea!es the
list alone
,o assist with this: Python 5 offers a standalone function called sorted#*
which makes a copy of the list and sorts that copy: lea!ing the original
unchanged.

224
224
Adding to a list redux: 0;1
+++ pri,e*
["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q]
+++ pri,e*
["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q$
?!3, !2, 31@ (
"3$ "Q$ 3']
"oncatenation
operator
2ist to add
,he list method we saw first appended a single item to the end of a list.
'hat happens if we want to add a whole list of items at the end9
4n this regard: lists are like strings. ,he 0<1 operator performs concatenation
and creates a new list which is one concatenated after the other.

225
225
"oncatenation
+++ newli*t
+++
+++ pri,e*
. pri,e* ( ?!3, !2, 31@
pri,e* . pri,e* ( ?!3, !2, 31@
"reate a new list
pdate the list
?!3, !2, 31@ (.
Augmented assignment
'e can use this to update a list in place. +ote that the augmented
assignment operator 0<R1 also works and is more than syntactic sugar this
time. 4t is actually more efficient than the long hand !ersion because it
updates the list in place rather than creating a new one.

226
226
"reating lists from text % &
+++ li*t('Hello')
[.,.$ .e.$ .l.$ .l.$ .o.]
str
( , e l l o
list
(
str
' ,
str
' e
str
' l
str
' l
str
' o
'e ought to look at a couple of ways to create lists from text.
,he first is to simply con!ert a string into a list with the list#* function.
JAs with all Python types: there is a function of the same name as the type
that con!erts into the type.K
Applying list#* to a string gi!es a list of the characters in the string.

227
227
"reating lists from text % .
+++ 'Hello, world!'
[.,ello$.$ .world-.]
list
"
, e l l o $ w o r l d - '3
str
str
6 , e l l o $
str
6 w o r l d -
.*plit()
Built in method
#plits on spaces
,he string type has methods of its own. /ne of these is splitJK which returns
a list of the components of the string as separated by white space.
,he split#* method can take an argument identifying other characters to
split on. 4f you want to get into more complex splitting of text we recommend
you in!estigate regular expressions or format-specific techni@ues Je.g. for
comma-separated !alues.

228
228
Progress
07ethods1
append#iteN*
reBerse#*
sort#*
insert#inde!$iteN*
reNoBe#iteN*
"oncatenation
<
<R
object.method#arguments*
['$"$3] < [4$($6]
priNes <R ["Q$ 3']
#orting list.sort#*
sorted#list*
)elp help#object*
help#object.method*

229
229
6xercise &.
S minutes

230
230
4s an item in a list9 % &
+++ odd* . ?3, 1, #, 2@ Does not include .
+++ odd*.re,oBe(!)
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+
ValeArror)
)ard error
list.reNoBe#!*) ! not in list
x must be in the
list before it can
be remo!ed
,ry to remo!e .

*ecall that a list?s remo!eJK method will gi!e an error if the !alue to be
remo!ed is not in the list to start with.
'e need to be able to test for whether an item is in a list or not.

231
231
4s an item in a list9 % .
+++ odd* . ?3, 1, #, 2@
+++ ! in odd*
>alse
+++ 3 in odd*
Hre
+++ ! not in odd*
Hre
Python uses the keyword 0in1 for this purpose. 4t can be used on its own or
as part of 0not in1. 0value in list1 e!aluates to a boolean: Hre or
>alse.

232
232
Precedence
!44y !4y !5y !6y !(y !3y (! 3!
!..y !:y !:.y !!.y !9y !9.y
not ! ! or y ! +nd y
-irst
2ast
! not in y ! in y
,he list now contains
e!ery operator we
meet in this course.
,hese operators fit naturally into the order of precedence. 'hile Python
does contain other operators that belong in this list: we will not be meeting
them in this introductory course.

233
233
#afe remo!al
if nNOer in nNOers )
nNOers.reNoBe#nNOer*
while nNOer in nNOers )
nNOers.reNoBe#nNOer*
'hat?s the
difference9
'e now ha!e a safe way to remo!e !alues from lists: testing before we
remo!e them.
>uick @uestion: 'hat?s the difference between the two code snippets in the
slide9

234
234
'orking through a list % &
e.g. Printing each element on a line
[.Hhe.$ ./at.$ .sat.$ .on.$ .the.$ .Nat..]
Hhe
/at
sat
on
the
Nat.
,here is an ob!ious thing to want to do with a list: and that is to work
through each item in a list: in order: and perform some operation or set of
operations on each item.
4n the most tri!ial case: we might want to print each item. ,he slide shows a
list of strings: probably from the split#* of a string. )ow do we print each
item one after the other9

235
235
'orking through a list % .
e.g. Adding the elements of a list
[4($ 86$ U"3$ Q&$ '(]
"&3
'hat is the sum of an empty list9 [] 9
Alternati!ely: we might want to accumulate the items in a list in some way.
-or example: we might want to sum the numbers in a list. ,his is another
example of applying an operation to each item in a list. ,his time the
operation is folding the list items? !alues into some final result.
4n this case we would probably need an initial !alue of the result that it takes
before any items get folded into it. 'hat is the sum of an empty list9 bero9
4s that an integer _ero: a floating point _ero: or a complex _ero9

236
236
'orking through a list % 5
e.g. #@uaring e!ery number in a list
[4$ 8$ U"$ Q$ ']
['6$ 4Q$ 4$ 9'$ ']
-inally: we might want to con!ert one list into another where each item in the
output list is the result of some operation on the corresponding item in the
input list.

237
237
,he 0for loop1 % &
words [.Hhe.$ ./at.$ .sat.$ .on.$ .the.$ .Nat..] R
for

) words in word
print#word*
name of list list
A new Python
looping construct
print: 'hat we want
to do with the list items.
Python has a construct precisely for stepping through the elements of a list.
,his is the third and final construct we will meet in this course. 'e ha!e
already seen if3 and while3 in this course. +ow we meet for3.
,his a looping construct: but rather than repeat while a test e!aluates to
Hre: it loops once for each item in a list. -urthermore it defines a name
which it attaches to one item after another in the list as it repeats the loop.

238
238
,he 0for loop1 % .
words [.Hhe.$ ./at.$ .sat.$ .on.$ .the.$ .Nat..] R
for

) words in word
print#word*
keywords
colon followed by
an indented block
'ePll look at the expression one step at a time.
,he expression is introduced by the 0for1 keyword.
,his is followed by the name of a !ariable. 'e will return to this in the next
slide.
After the name comes the keyword 0in1. 'e ha!e met this word in the
context of lists before when we tested for an itemPs presence in a list. ,his is
a different use. 'e arenPt asking if a specific !alue is in a list but rather we
are asserting that we are going to be processing those !alues that are in it.
After this comes the list itself: or more often the name of a list. All it has to
be is an expression that e!aluates to a list.
,he line ends with a colon.
,he lines following the colon are indented marking the block of code that is
to be run once for each item in the list.

239
239
word*
,he 0for loop1 % 5
words [.Hhe.$ ./at.$ .sat.$ .on.$ .the.$ .Nat..] R
for ) words in word
print#
Defining the loop %ariable
sing the loop !ariable

+ow letPs return to the name between 0for1 and 0in1.


,his is called the 0loop !ariable1. 6ach time the loop block is run this name
is attached to on item of the list. 6ach tim the loop is run the name is
attached to the next item in the list. ,he looping stops after the name has
been attached to the last item 4 nthe list.

240
240
,he 0for loop1 for printing
word*
words [.Hhe.$ ./at.$ .sat.$ .on.$ .the.$ .Nat..] R
for ) words in word
print#
for'.py
,here is a simple example of this in the file for'.py in your home
directories.
$ python3 'or1.py
Hhe
/at
sat
on
the
Nat.
$

241
241
,he 0for loop1 for adding
nNOers R [4($ 86$ U"3$ Q&$ '(]
for ) in
sN <R
sN R &
nNOer nNOers
print#sN*
nNOer
#et up before the loop
Processing in the loop
*esults after the loop

for".py
/ur second case was an 0accumulator1 adding the elements in a list.
)ere we establish an initial start !alue for our total of R and gi!e it the name
0sN1.
,hen we loop through the elements in the list: adding their !alues to the
running total as we mo!e through them.
,he unindented line after the loop block marks the end of the loop block and
is only run after all the looping is completed. ,his prints out the !alue of the
total now that all the numbers in the list ha!e been added into it.
$ python3 'or!.py
"&3
$

242
242
,he 0for loop1 for creating a new list
nNOers R [4$ 8$ U"$ Q$ ']
for ) in
s[ares.append#
s[ares R [ ]
nNOer nNOers
print#s[ares*
#et up before the loop
Processing in the loop
*esults after the loop
nNOerWW"*
for3.py
/ur third example made a new list from the elements of an old list. -or
example: we might want to take a list of numbers and produce the list of
their s@uares.
4n this case the usual process is that rather than ha!e an accumulator with
an initial !alue we start with an empty list and: as we loop through the input
!alues: we append#* the corresponding output !alues.
$ python3 'or3.py
['6$ 4Q$ 4$ 9'$ ']
$

243
243
,he loop !ariable persistsB
nNOers R [4$ 8$ U"$ Q$ ']
for ) in
s[ares.append#
s[ares R [ ]
nNOer nNOers
print#
nNOerWW"*
* nNOer
2oop !ariable only
meant for use in loopB
But it persistsB
,here is one nicety we should obser!e.
,he loop !ariable was created for the purpose of running through the
elements in the list. But it is Fust a Python name: no different from the ones
we establish by direct assignment. 'hile the for3 loop creates the name it
does not clean it up afterwards.

244
244
0for loop hygeine1
nNOers R [4$ 8$ U"$ Q$ ']
for ) in
s[ares.append#
s[ares R [ ]
nNOer nNOers
del
nNOerWW"*
nNOer Delete it after use
4t is good practice to delete the name after we ha!e finished using it. #o we
will follow our for3 loops with a del statement.
,his is not re@uired by the Python language but we recommend it as good
practice.

245
245
Progress
,esting items in lists
for loops
3 in ['$"$3$4]
sN R &
'or nNOer in ['$"$3$4]D
sN <R nNOer
del nNOer
Hre
loop !ariables for nu,=er in ['$"$3$4])
sN <R nu,=er
del nu,=er

246
246
6xercise &5
S minutes
'hat does this print9
nNOers R [&$ '$ "$ 3$ 4$ (]
sN R &
sN_so_far R []
for nNOer in nNOers)
sN <R nNOer
sN_so_far.append#sN*
print#sN_so_far*

247
247
0#ort-of-lists1
Python 0magic1:
,reat it like a list and it will
beha!e like a useful list
'hat can 0it1 be9
'e ha!e seen already that e!ery Python type comes with a function that
attempts to con!ert other Python obFects into that type. #o the list type
has a list#* function.
)owe!er: with lists Python goes further and puts a lot of work into making
this transparent and con!enient. 4n !ery many cases in Python you can drop
an obFect into a list construct and it will act as if it was a list: and a
con!enient list at that.

248
248
#trings as lists
*ecall:
list#.,ello.* [.,.$ .e.$ .l.$ .l.$ .o.]
for letter in ,
e
l
l
o
print#letter*
) .,ello.
Aets turned
into a list.
for4.py
-or example: we know that if we apply the list#* function to a string we
get the list of characters. But the Python 0treat it like a list1 magic means that
if we simply drop a string into the list slot in a for3 loop then it is treated as
exactly that list of characters automatically.
$ python 'or0.py
,
e
l
l
o
$

249
249
"reating lists of numbers
Built in to Python:
range#start$limit*
for nNOer in
print#nNOer*
) range#3$9* 3
4
(
6
8
X not included
,here are other Python obFects which: while not lists exactly: can be treated
like lists in a for3 loop. A !ery important case is a 0range1 obFect.
+ote that the range defined by 5 and X starts at 5 but ends one short. ,his is
part of the whole 0count from _ero1 business.

250
250
ranges of numbers
+ot actually lists: +++
range#&$(*
r+n-e(&,1)
But close enough: +++
[&$ '$ "$ 3$ 4]
li*t(r+n-e(&,1))
,reat it like a list and
it will beha!e like a list
#trictly speaking a range is not a list. But it is close enough to a list that
when you drop it into a for3 loop: which is its most common use by far:
then it beha!es like the list of numbers.

251
251
'hy not Fust a list9
7ost common use: for nNOer in
:
range#&$ '&&&&*)
4nefficient to make a
huge list Fust for this
0iterables1 : anything that can be treated like a list
list#iterable* 6xplicit list
#o why does the range#* function not Fust produce a list9
'ell: its most common use is in a for3 loop. /nly one !alue is re@uired at a
time. 4f the list was explicitly created t would waste computer memory for all
the items not in use at the time and computer time for creating them all at
once.
J,ruth be told: for the purposes of this course you wouldn?t notice.K

252
252
*anges of numbers again
range#'&* [&$ '$ "$ 3$ 4$ ($ 6$ 8$ 9$ Q]
range#3$ '&* [3$ 4$ ($ 6$ 8$ 9$ Q]
range#3$ '&$ "* [3$ ($ 8$ Q]
!ia list#*
#tart at R
6!ery n
th
number
range#'&$ 3$ U"* ['&$ 9$ 6$ 4] +egati!e steps
,he range#* function can be used with different numbers of arguments.
A single argument gi!es a list running from _ero to the number.
,wo arguments gi!es the lists we ha!e already seen.
A third argument acts as a 0stride1 and can be negati!e.

253
253
4ndices of lists
+++ pri,e* . ? !, 3, 1, #, 11, 13, 1#, 12@
[ ] 'Q '8 $ '3 $ '' $ 8 $ ( $ 3 $ $ "
8 6 ( 4 3 " ' &
+++ len(pri,e*)
+++ li*t(r+n-e(
9
[&$ '$ "$ 3$ 4$ ($ 6$ 8]
"))
!alid indices
+ow that we ha!e the range obFect we can mo!e on to one of the most
important uses of it.
#o far we ha!e used a for3 loop to step through the !alues in a list. -rom
time to time it is important to be able to step through the !alid indices of the
list.
/bser!e that if we apply the range#* function to a single number which is
the length of a list then we get a list of the !alid indices for that list.

254
254
Direct !alue or !ia the index9
priNes R ["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q]
for priNe in priNes)
print#priNe*
for inde! in range#len#priNes**)
print#priNes[inde!]*
6@ui!alent
#impler
'hat good is a list of !alid indices9
,here are two ways to step through the !alues in a list. /ne is directlyO this
is the method we ha!e met already. ,he second is to step through the
indices and to look up the corresponding !alue in the list.
,hese are e@ui!alent and the first method we ha!e already seen is shorter
to write. #o why bother with the second9

255
255
'orking with two lists: 0dot product1
list' R [ &.4] &.&$ &.3$
list" R [ &.6] &.($ &."$
Y Y Y
&."4 &.& &.&6 < < &.3
b
"onsider operations on two lists.
A concrete example might be the 0dot product1 of two lists. ,his is the sum
of the products of matching elements.
#o
jR.5: R.R: R.8k w jR..: R.S: R.Yk
e R.5VR.. ; R.RVR.S ; R.8VR.Y
e R.RY ; R.R ; R..8
e R.Y
)ow might we implement this in Python9

256
256
'orking with two lists: indices
list' R [&.3$ &.&$ &.4]
list" R [&."$ &.($ &.6]
for inde! in
sN R &.&
print#sN*
R & .
indices
) range#len#list'**
sN <R list'[inde!]Wlist"[inde!]
Dealing with
!alues from
both lists at
the same time.
'e can approach this problem by running through the !alid indices and
looking up the corresponding !alues from each list in the body of the for3
loop.

257
257
4terables
range#froN$to$stride*
+ot a list but 0close enough1
04terable1
,he range obFect is one of the most commonly met examples of an iterable:
something that isn?t a list but is 0close enough1.

258
258
iter
4
"
A little more about iterables % &
str
( a l p h a
str
4 O e t a
str
( g a N N a
str
( d e l t a
+++ -reeC . ?'+lph+', '=et+', '-+,,+', 'delt+'@
+++ -reeCEi . iter(-reeC)
+++ next(-reeCEi)
.alpha.
+++ next(-reeCEi)
.Oeta.
/ffset
'e will look a little more closely at iterables so that we can recognise them
when we meet them later.
4f we start with a list then we can turn it into an iterable with the iter#*
function.
An iterable ceated from a list is essentially the same as the list with a note of
how far through the list we ha!e read. ,his reference starts at _ero:
ob!iously.
Python pro!ides a ne!t#* function which can act on any iterable which
returns the next !alue Jor the first if we?!e not startedK and increments this
internal counter.

259
259
iter
4

A little more about iterables % .


str
( a l p h a
str
4 O e t a
str
( g a N N a
str
( d e l t a
+++ next(-reeCEi)
.gaNNa.
+++ next(-reeCEi)
.delta.
+++ next(-reeCEi)
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+

@topFteration
+ote that ne!t#* complains !igorously if we try to run off the end. -or this
course: where these errors are all fatal it means that we can?t use ne!t#*
directly. we don?t need toO we ha!e the for3 loop which handles the error
for us.

260
260
Progress
+on-lists as lists
04terables1
range#*
4ndices of lists
Parallel lists
range#liNit*
range#start$liNit*
range#start$liNit$step*
range#3$8* [3$4$($6]
for letter in .,ello.)
...
for inde! in range#len#things**)
greek_i R iter#greek*
ne!t#greek_i*

261
261
6xercise &8
S minutes
list' R [ &.4] &.&$ &.3$
list" R [ &.6] &.($ &."$
U&." U&.( &.'
"omplete e!er/ise'4.py
&.&4 &."( &.&' &.3
< <
Difference
#@uare
Add
,his exercise de!elops the Python to calculate the s@uare of the distance
between two 5D points. 'e could use our s@uare root Python from earlier to
calculate the distance itself but we will meet the 0real1 s@uare root function
later in this course so we?ll hold back from that for now.

262
262
2ist 0slices1
pri,e* . ?!, 3, 1, #, 11, 13, 1#, 12, !3, !2@ ```
pri,e* ```
["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q$ "3$ "Q]
pri,e*?3@ ```
8
pri,e*?3D2@ ```
[8$ ''$ '3$ '8$ 'Q$ "3]
,he list
An item
"art of the list
,here is one last piece of list Pythonry we need to see.
Python has a syntax for making copies of parts of lists: which it calls 0slices1.
4f: instead of a simple index we put two indices separated by a colon then
we get the sub-list running from the first index up to but excluding the
seocnd index.

263
263
#lices % &
priNes R ["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q$ "Q$ 3']
5 Z
[8$ priNes[3)Q]
4tem Z not
included
"3$
''$ '3$ '8$ 'Q$ "3]
priNes[ ] Q ) 3
to
from
p to but not
including3
,he last index is omitted as part of the 0count from _ero1 thing.

264
264
#lices % .
priNes 8$ ''$ '3$ '8$ 'Q$ "Q$ 3'] "3$
priNes[ ] Q ) 3 [8$ ''$ '3$ '8$ 'Q$ "3]
["$ 3$ ($
priNes[ ] Q ) ["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q$ "3]
priNes[ ] ) 3 [8$ ''$ '3$ '8$ 'Q$ "3$ "Q$ 3']
priNes[ ] ) ["$ 3$ ($ 8$ ''$ '3$ '8$ 'Q$ "3$ "Q$ 3']
'e can omit either or both of the numbers. 7issing the first number means
0from the start1 and missing the second means 0right up to the end1.

265
265
#lices % 5
priNes 8$ ''$ '3$ '8$ 'Q$ "Q$ 3'] "3$
priNes[ ] Q ) 3 [8$ ''$ '3$ '8$ 'Q$ "3]
["$ 3$ ($
priNes[ ) Q ) 3 [8$ '3$ 'Q ] ] "
priNes[ ) Q ) 3 ] 3 [8$ '8 ]
'e can also add a second colon which is followed by a stride: Fust as with
range#*.

266
266
list
3
alphaOet
letters
"opies and slices % &
letter* . ?'+','=',''@ ```
str
' a
str
' O
str
' /
+lph+=et . letter* ```
#lices allow us to make copies of entire lists.
4f we use simple name attachment then we Fust get two names for the same
list.

267
267
list
3
alphaOet
letters
"opies and slices % .
letter*?&@ . 'F' +++
str
' I
str
' O
str
' /
print(+lph+=et) +++
[.I.$ .O.$ ./.]
"hanging an item in the list !ia one name shows up !ia the other name.

268
268
letters alphaOet
list
3
"opies and slices % 5
letter* . ?'+','=',''@ +++
str
' a
str
' O
str
' /
+lph+=et . letter*?D@ +++
list
3
#lices are
copies.
#lices are copies: though: so if we attach a name to a slice from a list d
e!en if that slice is the entire list % then we ha!e two separate lists each
with their own name attached.

269
269
"opies and slices % 8
letter*?&@ . 'F' +++
print(+lph+=et) +++
#lices are
copies.
[.a.$ .O.$ ./.]
letters
alphaOet
list
3
str
' a
str
' O
str
' /
list
3
str
' F
#o changes in one don?t show in the other because they are not the same
list.

270
270
Progress
#lices
iteNs[froN)to]
iteNs[)to]
iteNs[froN)]
iteNs[)]
iteNs[froN)to)stride]
iteNs[)to)stride]
iteNs[froN))stride]
iteNs[))stride]
6nd-limit excluded
#lices are copies

271
271
6xercise &S
5 minutes
Predict what this Python will do.
,hen run it.
'ere you right9
e!er/ise'(.py
foo R [4$ 6$ "$ 8$ 3$ '$ Q$ 4$ "$ 8$ 4$ 6$ &$ "]
Oar R foo[3)'")3]
Oar["] <R foo[4]
foo[&] R Oar[']
print#Oar*

272
272
-iles
.t!t
.dat
./sB
*eading 'riting
4nput /utput
+ow we will look at something completely different that will turn out to be
Fust like a list: -iles.
'e want our Python scripts to be able to read in and write out files of text or
data.
'e will consider reading files first and writing them second.

273
273
*eading a text file
-ile name
-ile obFect
-ile contents
.treasre.t!t.
Oook
.HGAI@EGA F@LIKM.
string
file
string
0opening1 the file
reading from the file
-inished with the file
0closing1 the file
*eading from a file in!ol!es four operations bracketing three phases.
'e start with a file name. ,his is a string of characters.
4 want to be pedantic about something in this course: a file name is not a
file. A file is a lump of data in the computer?s long-term store. A file name is a
short piece of text.
'e link a file name to a file by a process called 0opening the file1. ,his takes
the file name and creates a Python file obFect which will act as our conduit to
the file proper.
'e will use this file obFect to read data from the file into the Python script.
'hen we are done reading data out of the file J!ia the file obFectK we will
signal to both python and the operating system that we are done with it by
0closing1 it. ,his disconnects us from the file and we would ha!e to re-open it
if we wanted more data.

274
274
/pening a text file
+++ =ooC ) 'r' , 'tre+*ure.txt' ( open .
*ead-only jtextk
-ile name
Python function
Python file obFect
0mode1
Oook * .treasre.t!t. # open R
*ead-only is
the default
'e will start with opening a file.
'e start with Fust the file name. ,his is passed into the openJK function with
a second argument: .r.: indicating that we only want to read the file.
,he function hooks into the operating system: which looks up the file by
name: checks that we ha!e permission to read it: records the fact that we
are reading it: and hands us back a handle d the file obFect % by which we
can access its contents.

275
275
*eading from a file obFect
+++ line1 =ooC .
-ile obFect
-irst line of file
+++ line1
. 6n. HGAI@EGA F@LIKM
4ncludes the
0end of line1
next( )
0next line: please1
+ow that we ha!e this hook into the file itself: how do we read the data from
it9
-ile obFects are iterators: so we can apply the nextJK function to them to get
the next line: starting with the first.

276
276
-ile obFect are iterable
+++ line! next(=ooC) .
#econd line of file
+++ line!
.6n.
+++ line3 next(=ooC) .
+++ line3
.PIGH CKA6n.
A blank line
,hird line of file
+ote that a 0blank1 line actually contains the end of line character. 4t has
length &: and is not an empty string: length R.

277
277
"losing the file
+++ .lo*e() =ooC
7ethod built in to file obFect
-rees the file for other
programs to write to it.
'hen we are done reading the data we need to signal that we are done with
it. Python file obFects ha!e a /lose#* method built into them which does
precisely this.

278
278
,he file obFect % &
+++ =ooC
7_io.He!tFCJrapper
en/odingR.EH>U9.+
naNeR.treasre.t!t.
,ext 4nput//utput
-ile name
"haracter encoding:
how to represent
letters as numbers.
,--X means 0"# ,ransformation -ormat % X-bit1.
"# means 01ni!ersal "haracter #et. ,his is defined by 4nternational
#tandard 4#//46" &RY8Y: 4nformation technology d ni!ersal multiple-octet
coded character set J"#K. -or more information than you could possibly
want on this topic !isit the nicode web pages: www.ni/ode.org.

279
279
,he file obFect % .
file
"Q treasre.t!t EH>U9
HGAI@EGA F@LIKM

PIGH CKA

Hhe Cld P//aneer

Pointer to the file


on the file system
0offset1: how far into
the file we ha!e read
-ile name
,ext encoding
,he Python file obFect contains a lot of different bits of information. ,here are
also lots of different sorts of file obFect: but we are glossing o!er that in this
introductory course.
'hat they share is a reference into the operating system?s file system that
identifies the specific file and acts as the declaration to the operating system
that the Python process is using the file.
,hey also share an 0offset1. ,his is a number that identifies how far into the
file the program has read so far. ,he ne!t#* function reads from the offset
to the next new line and increases the offset to be the distance into the file
of the new line character.
,he file obFect also records the name it was opened from and the text
encoding it is using to con!ert bytes in the file to characters in the program.

280
280
*eading through a file
,reat it like a list and
it will beha!e like a list
list#file_object* 2ist of lines in the file
+++ =ooC . open('tre+*ure.txt', 'r')
+++ line* . li*t(=ooC)
+++ print(line*)
Ai!en that a file is an iterable: we can smply con!ert it into a list and we get
the list of lines.

281
281
*eading a file mo!es the offset
B
+++ =ooC . open('tre+*ure.txt', 'r')
+++ line*E+ . li*t(=ooC)
+++ print(line*E+)
+++ line*E= . li*t(=ooC)
+++ print(line*E=)
[] 6mpty list
)uge output 3
+ote: howe!er: that the act of reading the file to get the lines reads through
the file: so doing it twice gi!es an empty result second time round.

282
282
*eading a file mo!es the offset
+++ =ooC
+++ line*E+ .
+++ print(line*E+)
+++
+++ print(line*E=)
[]
3
-ile obFect starts with offset at start.
. open('tre+*ure.txt', 'r')
/peration reads entire file from offset.
li*t(=ooC)
line*E= . li*t(=ooC)
/ffset changed to end of file.
/peration reads entire file from offset.
#o therePs nothing left to read.
recall that the reading starts at the offset and reads forwards d to the end of
the file in this example. 4t also mo!es the offset to what was last read. #o
the offset is changed to refer to the end of the file.

283
283
*esetting the offset
+++ =ooC
+++ line*E+ .
+++ print(line*E+)
+++
+++
3
. open('tre+*ure.txt', 'r')
li*t(=ooC)
line*E= . li*t(=ooC)
+++ print(line*E=)
=ooC.*eeC(&) #et the offset explicitly
'e can deliberately change the offset. -or text files with lines of different
lengths this can be more complex that you would imagine. ,he only safe
!alue to change the offset to is _ero which takes us back to the start of the
file.

284
284
/lder file obFect methods
+++ =ooC
+++ =ooC.re+dline()
.HGAI@EGA F@LIKM6n.
. open('tre+*ure.txt', 'r')
+++ =ooC.re+dline*()
[.6n.$ .PIGH CKA6n. 3 ]
,here are other ways to read in the data. 6arlier !ersions of Python only
supported a couple of built-in methods. Hou may still see these in other
people?s scripts but we don? recommend writing them in scripts that you
create.

285
285
,ypical way to process a file
Oook R open#.treasre.t!t.$ .r.*
for line in Oook )
3
,reat it like a list3
Being able to read a single line of a file is all !ery well. "on!erting an entire
book into a list of its lines might pro!e to be unwieldy.
'hat is the typical way to do it9
Ai!en that files can be treated like lists the easiest way to process each line
of a file is with a for3 loop.

286
286
6xample: lines in a file
Oook R open#.treasre.t!t.$ .r.*
n_lines R &
for line in Oook )
n_lines <R '
print#n_lines*
2ine count
*ead each line of the file
4ncrement the count
Print out the count
Oook./lose#*
-or example: we could Fust increment a counter for each line to count the
number of lines.

287
287
6xample: characters in a file
Oook R open#.treasre.t!t.$ .r.*
n_/hars R &
for line in Oook )
n_/hars
print#n_/hars*
len#line*
+umber of characters on the line
4ncrease the count by that many
<R
Oook./lose#*
'e could measure the length of the line and increment the counter by the
number of characters in the line to count the total number of characters in
the file.

288
288
Progress
/pening file to read
*eading file
"losing file
-ile offset
Oook R open#filenaNe$ .r.*
Oook./lose#*
Oook.seek#&*
for line in Oook)
...

289
289
6xercise &Y
S minutes
"omplete a script to count
lines: words and characters
of a file.
e!er/ise'6.py
/nce this script is complete you will ha!e written an e@ui!alent of the
standard Jalbeit simpleK nix command line tool 0wc1.

290
290
'riting files
-ile name
Data to write
-ile obFect
.treasre.t!t.
Oook
.HGAI@EGA F@LIKM.
string
file
string
0opening1 the file
writing to the file
-inished with the file
0closing1 the file
6nough of reading files *obert 2ouis #tephenson has prepared for us. 2et?s
write our own.
,his is again a three phase process. 'e will open a file for writing: write to it
and then close it.

291
291
/pening a text file for writing
+++ output ) 'w' , 'output.txt' ( open .
/pen for
writing jtextk
B
,his will truncate
an existing file
/pening a file for writing is the same as opening it for reading except that
the mode is .w. for writing.
4f the file already exists then this o!erwrites it. ,he file gets truncated to _ero
bytes long because you ha!en?t written to it yet.

292
292
'riting to a file obFect % &
+++ .write output
7ethod built in
to file obFect
-ile obFect
(line1)
Data being written
A writeable file obFect has a method writeJK which takes a text string
Jtypically but not necessarily a lineK and writes it to the file.

293
293
'riting to a file obFect % .
+++ .write output ('+lph+ ,ypical use: whole line.
4ncludes 0end of line1
%n')
+++ .write output ('=e')
+++ .write output ('t+%n')
Doesn?t ha!e
to be whole lines
+++ .write output ('-+,,+%ndelt+%n')
"an be multiple lines
)ow the data is chopped up between writes is up to you.

294
294
"losing the file obFect
+++ .lo*e() output Dital for written files
4t also has a closeJK method.

295
295
4mportance of closing
Data 0flushed1 to disc on closure.
Python script -ile obFect -ile system
write 0flush1
B
"losing files is e!en more important for written files that read ones.
4t is only when a file is closed that the data you ha!e written to the Python
file obFect is definitely sent to the operating system?s file. ,his is a process
called 0flushing the file to disc1.
'riting to disc is slow by computing standards so: for efficiency reasons:
systems like Python tend to wait until they ha!e at least a certain amount of
data for a file before they flush it to disc. 4f your program exists before
flushing then the data may be lost. "losing a file signals that there will be no
more data coming for it so Python flushes whate!er it has in hand to the disc
as part of the closure process.

296
296
4mportance of closing promptly
B
-iles locked for other access
open jPwPk open jPrPk

J7ore a problem for 'indows than nixK


,here?s more to it than Fust flushing: though. )olding a file open signals to
the underlying computer operating system that you ha!e an interest in the
file. )ow the operating system reacts to this !aries from system to system:
but 7icrosoft 'indowsx will lock a file so that if you ha!e it open for writing
nobody else can open it for reading: e!en if you don?t plan to write any more
to it than you ha!e already.

297
297
'riting non-text !alues
+++ output.write('/oo!%n')
'riting text JstrK
(
+++ output.write(0!) 'riting non-text JintK
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+
HypeArror) Nst Oe str$ not int
write#* only accepts text

,here is one last issue to address with writing data to files.


4nlike the print#* function: the write#* function can only handle text
arguments. ,he print#* function automatically con!erts non-text !aluesO
write#* does not. ,herefore: we must do the con!ersion oursel!es.

298
298
'riting non-text !alues
+++ output.write(
"on!ert to text: str#*
"
+++ output.write('%n') 6xplicit end-of-line
'
*tr(0!))
,ext formatting Jlater in the courseK
pro!ides a more elegant solution.
'e do this simply by calling the str#* function which con!erts JalmostK
anything directly into text.
'e also need to explicitly add on the new line character to indicate the end
of the line with the data on it.
2ater in this course we will see a system Python has for generating
formatted text. ,his will pro!ide a more elegant solution but: until then: we
will make do with str#* and 6n.

299
299
Progress
/pening files for writing
6xplicit ends of lines
Oook R open#filenaNe$ .w.*
Oook.write#.6n.*
'riting data Oook.write#str#data**
'riting text Oook.write#te!t*
"losing the file is important Oook./lose#*

300
300
6xercise &[
S minutes
,he script e!er/ise'8.py prints
a series of numbers ending in &.
"hange the script to write to a file called
otpt.t!t instead of printing to the console.

301
301
-unctions
y = f(x)

302
302
-unctions we ha!e met
print#line*
open#filename$ mode*
range#from$ to, stride*
float#thing*
int#thing*
iter#list*
str#thing*
len#thing*
type#thing*
inpt#prompt*
+ot that manyB 0,he Python 'ay1:
4f it is appropriate to an obFect:
make it a method of that obFect.
Oool#thing*
ord#char*
/hr#number*
list#thing*
,his is the complete set of Python functions that we ha!e met to date.
Actually it?s surprising how few there are: not how many. Python?s
philosophy leads to functions that only make sense for a particular sort of
obFect being methods of that obFect: not free-standing functions.
'e are now going to write our own functions.

303
303
Why write our own functions9
3 read
3 test
3 fix
3 impro!e
3 add to
3 write
6asier to 3
0#tructured
programming1
3 de!elop
'hy9
7o!ing our scripts? functionality into functions and then calling those
functions is going to make e)erything better. ,his is the first step towards
0structured programming1 which is where programming goes when your
scripts get too long to write in one go without really thinking about it.

304
304
Defining a function
(y
1
, y
2
, y
3
) (x
1
, x
2
, x
3
, x
4
, x
5
) = f
Identify the inputs
Identify the processing
Identify the outputs
#o what do we need to do9
'ell any functions starts by defining what inputs it needs: what it does with
those inputs to generate the results and exactly what results/outputs it
generates.

305
305
A function to define: total#*
#um a list
j&: .: 5k
j[: -8: &: Y: Rk
j k
Y
&R
R
06dge case1
,o gi!e oursel!es a simple but concrete example to keep in mind we will set
oursel!es the challenge of writing a function that sums the elements of a list.
,his may sound tri!ial but immediately raises some interesting cases that
need to be considered.
'hat is the sum of an empty list9 bero9 4s that an integer _ero or a floating
point _ero9 J/r a complex _ero9K
'e will say it should sum to an integer _ero.

306
306
Defining a Python function % &
def ) # : * total colon
inputs
name of function
define a function called 3
'e will plunge straight into the Python.
,he Python keyword to define a function is 0def1.
,his is followed by the name of the function: 0total1 in this case.
,his is followed by a pair of round brackets which will contain all the input
!alues for the function.
-inally there is a colon to mark the end of the line and the beginning of the
body of the function.

307
307
Defining a Python function % .
def total# *) nNOers
name for the input
,his name is
internal to
the function.
/ur function takes a single input: the list of numbers to be summed.
'hat goes inside the brackets on the def line is the name that this list will
ha!e inside the function?s definition. ,his is the 0x1 in maths. ,his internal
names is typically unrelated to the name the list has in the main body of the
script.
4t is always a good idea to name your inputs Jand other !ariablesK
meaningfully. Please try to a!oid calling them 0x1: 0y1: or 0z1.
'e will call ours 0nNOers1.

308
308
Defining a Python function % 5
def total#nNOers*) "olon followed by indentation

As e!er with Python a colon at the end of a line is followed by an indented


block of code. ,his will be the body of the function where we write the
Python that defines what the function actually does with the inputJsK it is
gi!en.

309
309
Defining a Python function % 8
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
0Body1 of function
-or our function this is particularly simple.

310
310
Defining a Python function % 8
def total# *) nNOers
sN_so_far
for
sN_so_far <R nNOer
R &
in nNOers) nNOer
,hese !ariables exist only
within the function?s body.
,he nNOers name we specified on the def line is !isible to Python only
within the function definition. #imilarly any names that get created within the
function body exist only within that function body and will not be !isible
outside. +or will they clash with any other uses of those names outside the
function body.
4n our example code the name 0nNOers1 is defined in the def line: the
0sN_so_far1 name is defined explicitly in the function body and the
0nNOer1 name is defined by the for3 loop as its loop !ariable.
+one of these interact with the Python outside the function definition.

311
311
Defining a Python function % S
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
,his !alue
is returned
return this !alue
-inally we need to specify exactly what !alue the function is going to return.
'e do this with another Python keyword: 0retrn1. ,he !alue that follows
the retrn keyword is the !alue returned by the function.
'hen Python reaches the retrn statement in a function definition it hands
back the !alue and ends the execution of the function body itself.

312
312
Defining a Python function % Y
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
And that$s it%
nindented
after this
And that?s all that is in!ol!ed in the creation of a Python function.

313
313
Defining a Python function % [
And that$s it%
All internal names cleaned up +o need for del
All internal names internal +o need to a!oid reusing names
+ote that because of this isolation of names we don?t ha!e to worry about
not using names that are used elsewhere in the script.
Also: as part of this isolation all these function-internal names are
automatically cleared when the function finishes. 'e do not need to worry
about deleting them.

314
314
sing a Python function % &
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
print#total#['$ "$ 3]**
,he list we
want to add up
'e use this function we ha!e defined in exactly the same way as we would
use a function pro!ided by Python.

315
315
sing a Python function % .
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
print#total#['$ "$ 3]**
,he function we
ha!e Fust written

316
316
sing a Python function % 5
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
print#total#['$ "$ 3]**
Printing out
the answer

317
317
sing a Python function % 8
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
print#total#['$ "$ 3]**
total'.py
$ python3 tot+l1.py
6
nb: nix prompt
,he file total&.py in your home directories contains exactly the code you see
here.

318
318
sing a Python function % S
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
print#total#['$ "$ 3]**
print#total#[8$U4$'$6$&]**
print#total#[]**
total".py
$ python3 tot+l!.py
6
'&
&
se the function
multiple times

319
319
Progress
-unctions
0#tructured programming1
Defining a function
*eturning a !alue
def fn/tion#inpt*)
...
retrn otpt

320
320
6xercise &X
S minutes

321
321
*eminder about indices
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
def total#nNOers*)
sN_so_far R &
for inde! in range#len#nNOers**)
sN_so_far <R nNOers[inde!]
retrn sN_so_far
6@ui!alent
total3.py
total".py
2et?s @uickly remind oursel!es about how we can uses indices for lists rather
than !alues from lists directly.
'e found this particularly useful when we were tra!ersing more than one list
at once.

322
322
'ant a function to add two lists of the same length term-by-term:
6xample of multiple inputs
j&: .: 5k jS: [: 8k jY: Z: [k (
j&R: -Sk j&S: &8k j.S: Zk (
j&&: &&: -.: .: [k j5: [: 8: &: [k jX: 8: -Y: &: Rk (
,wo inputs
#o how do we build functions that take in more than one input at once9

323
323
-unctions with multiple inputs
def add_lists#
sN_list R []
for
sN
sN_list.append#sN*
retrn sN_list
*) O_list $ a_list
) range#len#a_list** in inde!
O_list[inde!] < a_list[inde!] R
7ultiple inputs are
separated by commas
,he Python syntax for multiple inputs is much the same as it is for a
mathemtical function: we separate the inputs by commas.

324
324
-unctions with multiple inputs
def add_lists#
sN_list R []
for
sN
sN_list.append#sN*
retrn sN_list
*) O_list $ a_list
) range#len#a_list** in inde!
O_list[inde!] < a_list[inde!] R
'e ha!e
two lists3
3so we ha!e
to use indexing
+ote that functions that take in more than one list typically need to use
indices.

325
325
7ultiple outputs
'rite a function to find minimum and maximum !alue in a list
j&: .: 5k
j&R: -Sk
j5: [: 8: &: [k
,wo outputs
& (
-S (
& (
5
&R
[
But what if we want to return multiple !alues9
'e can write a function that determines the minimum !alue in a list: and we
can write a function that returns the maximum. 'hat do we do if we want to
find both9

326
326
-inding Fust the minimum
def Nin_list#a_list*)
Nin_so_far R a_list[&]
for
if a 7 Nin_so_far)
retrn
) a_list in a
Nin_so_far R a
Nin_so_far *eturning a single !alue
2ist cannot be emptyB
Ninlist.py
#o here?s the function that determines the minimum !alue in a list3

327
327
-inding Fust the maximum
def Na!_list#a_list*)
Na!_so_far R a_list[&]
for
if a + Na!_so_far)
retrn
) a_list in a
Na!_so_far R a
Na!_so_far *eturning a single !alue
/nly real change
Na!list.py
3and Fust the maximum.

328
328
-inding both
def NinNa!_list#a_list*)
Na!_so_far R a_list[&]
for
if a + Na!_so_far)
retrn what?
) a_list in a
Na!_so_far R a
Nin_so_far R a_list[&]
if a 7 Nin_so_far)
Nin_so_far R a
,his is the real @uestion
"ombining the bodies of these two functions is @uite straightforward.
But what do we return9

329
329
*eturning both
def NinNa!_list#a_list*)
Na!_so_far R a_list[&]
for
if a + Na!_so_far)
retrn
) a_list in a
Na!_so_far R a
Nin_so_far R a_list[&]
if a 7 Nin_so_far)
Nin_so_far R a
Nin_so_far$ Na!_so_far A pair of !alues
NinNa!list.py
,wo return two !alues we simply put them both after the retrn statement
separated by a comma: Fust as we would ha!e done with the inputs.

330
330
0,uples1
e.g. Nin_Bale Na!_Bale $
Nin_Bale aBg_Bale $ Na!_Bale $
Pair
,riple
/ften written with parentheses:
Nin_Bale Na!_Bale $
Nin_Bale aBg_Bale $ Na!_Bale $
#
# *
*
"ommas
,hese sets of !alues separated by commas Jbut not in s@uare brackets to
make a listK are called 0tuples1 in Python. #ometimes they are written with
round brackets around them to make it clearer that they come together. But
it?s the comma that is the acti!e ingredient making them a tuple: not the
brackets.

331
331
sing tuples to return !alues
#Nin_Bale Na!_Bale* $ retrn
#NiniNN
4n the function definition def 3
sing the function
R NinNa!_list#Bales* Na!iNN* $
4f we return a pair of !alues in a tuple: we can also attach a pair of names to
them as a tuple too.

332
332
sing tuples to attach names
alpha R Oeta $ (6 $ '"
alpha R
Oeta (6
'"
R
# * # *
'e can do this outside the context of functions returning !alues: of course.
'e can do it anywhere.

333
333
#wapping !alues
+++ +lph+ . 1!
+++ =et+ . 17
+++ (+lph+, =et+) . (=et+, +lph+)
+++ print(+lph+)
(6
+++ print(=et+)
'"
#wapping !alues
Because the entire right hand side is e!aluated before the left hand side is
considered this lets us use tuples for some particularly useful tricks. perhaps
the most useful is swapping two !alues.

334
334
Assignment works right to left
alpha R '"
Oeta R (6
#alpha$ Oeta* R #Oeta$ alpha*
#tage &: #Oeta$ alpha* #(6$ '"*
#tage .: #alpha$ '"* #(6$ R Oeta*
,he !alues associated with the names are e!aluated first. ,hen the names
get reattached to those !alues: regardless of what names they might ha!e
had before.

335
335
*ecall this 0gotcha1:
a R '&
O R 8
a R a < O
O R a U O
a R '8
O R a U O
R 1# U 8
R '&
O Z 1& U 8 R 3
a has now changedB
B
'e can also use it to help us with our 0change of coordinates1 example.

336
336
Again: assignment works right to left
a R '&
O R 8
#a$ O* R #a < O$ a U O*
#tage &: #a<O$ aUO* #'&<8$ '&U8* #'8$ 3*
#tage .: #a$ 3* #'8$ R O*
,his works in exactly the same way.

337
337
Progress
7ultiple inputs
7ultiple outputs
0,uples1
#imultaneous assignment
def thing#in
'
$ in
"
$ in
3
*)
retrn #ot
'
$ ot
"
$ ot
3
*
#a$ O$ /*
#a$ O* R #a<O$ aUO*

338
338
6xercise &Z
&R minutes
,he script e!er/ise'Q.py is an answer to exercise &Y.
6dit it to turn it into:
&. the definition of a function file_stats#* that takes a file
name and returns a triple #n_lines$ n_words$ n_/hars*
.. a call to that function for file name treasre.t!t
5. a print of that triple.

339
339
/ne obFect or many9
0a pair of obFects1
two obFects
one obFect
,uples tend to blur the boundary between multiple obFects and a single
obFect.

340
340
,uples as single obFects % &
+++ x . !&
+++ type(x)
+++
+++
y . 3.10
type(y)
7/lass .int.+
7/lass .float.+
+++ G . (!&, 3.10)
+++ type(G)
7/lass .tple.+
/ne name l "air of !alues
A single obFect
'e can treat a tuple as a single obFect. 4t has a type called : 0tple1
unsurprisingly.

341
341
,uples as single obFects % .
+++ G . (!&, 3.10)
+++ print(G)
#"&$ 3.'4*
+++ w . G
+++ print(w)
#"&$ 3.'4*
#ingle name l #ingle tuple
'e can manipulate the tuple as a single obFect @uite happily.

342
342
#plitting up a tuple
+++ print(G)
#"&$ 3.'4*
+++ (+,=) . G ,wo names l #ingle tuple
+++ print(+)
"&
+++ print(=)
3.'4
But a tuple is fundamentally made of separable pieces and can be split up.

343
343
)ow tuples are like lists
+++ G . (!&, 3.10)
+++ G?1@
3.'4
4ndices
+++ len(G)
"
2ength
+++ G ( (1&, !.1#)
#"&$ 3.'4$ '&$ ".'8*
"oncatenation
,uples are a lot like lists at first glance.

344
344
)ow tuples are not like lists
+++ G . (!&, 3.10)
+++ G?&@ . 1&
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+
HypeArror) .tple. oOTe/t does not
spport iteN assignNent
04mmutable1
,hey ha!e one critical difference: though. A tuple is 0immutable1. Hou cannot
change indi!idual elements in a tuple. Hou get the whole tuple and you can?t
fiddle with it.

345
345
Progress
,uples as single obFects thing R #a$ O$ /*
#plitting up a tuple #!$ y$ ^* R thing
,uples as lists thing[&]
len#thing*
thing < thing
4mmutability thing[&] R '&


346
346
-unctions we ha!e written so far
total#list*
add_lists#list
1
$list
2
*
NinNa!_list#list*
,o date we ha!e written a small number of functions oursel!es.
/nce we become serious Python programmers using the computer for our
day Fob then we would expect to write many more.

347
347
*eusing functions within a script
def s[are#liNit*)
...
...
s[ares_a R s[are#34*
...
fiBe_s[ares R s[ares#(*
...
s[ares_O R s[ares#(6*
...
/ne definition
7ultiple uses in
the same file
Easy%
'ithin a script reusing a function is easy. 'e simply call the function
whene!er we want it.

348
348
...
s[ares_a R s[ares#34*
...
...
fiBe_s[ares R s[ares#(*
...
*eusing functions between scripts9
def s[ares#liNit*)
...
/ne definition
&ow'
...
s[ares_O R s[ares#(6*
...
7ultiple uses in
multiple files
But what happens if we want to use a function in more than one script9

349
349
07odules1
def
...
s[are#liNit*
fiBe R s[ares#(*
) ...
...
Definition se
/odule: a container of functions
def
...
/Oes#liNit*)
Python has a mechanism to assist with this called 0modules1. A module is a
collection of functions Jand other materialK which can then be imported into a
script and used within that script. 4f we can write our own module with our
own functions then we can import them into our own scripts.

350
350
def s[ares#liNit*)
answer R []
for n in range#&$liNit*)
answer.append#nWW"*
retrn answer
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
te!t R inpt#.KNOerS .*
nNOer R int#te!t*
s[ares_n R s[ares#nNOer*
total_n R total#s[ares_n*
print#total_n*
7odules: a worked example % &a
sN_s[ares.py
#tarts empty
tils.py
'e will start with a file called sN_s[ares.py which uses two functions to
add up the s@uares of numbers from _ero to some limit. 'e want to transfer
those function definitions into a different file which we will call tils.py
Jwhich starts emptyK but still be able to use them in our original file.

351
351
7odules: a worked example % &b
$ python3 *u,E*qu+re*.py
KNOerS 1
3&
$ python3 *u,E*qu+re*.py
KNOerS #
Q'
e R ; & ; 8 ; Z ; &Y
e R ; & ; 8 ; Z ; &Y ; .S ; 5Y
<ust to pro!e 4?m not fibbing: here it is working before we mo!e anything
about.

352
352
te!t R inpt#.KNOerS .*
nNOer R int#te!t*
s[ares_n R s[ares#nNOer*
total_n R total#s[ares_n*
print#total_n*
7odules: a worked example % .a
def s[ares#liNit*)
answer R []
for n in range#&$liNit*)
answer.append#nWW"*
retrn answer
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
tils.py
sN_s[ares.py
7o!e the definitions
into the other file.
sing the text editor we mo!e the definitions from sN_s[ares.py to
tils.py.

353
353
7odules: a worked example % .b
$ python3 *u,E*qu+re*.py
KNOerS 1
Hra/eOa/k #Nost re/ent /all last*)
>ile =sN_s[ares.py=$ line 4$ in 7Nodle+
s[ares_n R s[ares#nNOer*
KaNeArror) naNe .s[ares. is not defined
Because we ha!e JreKmo!ed its definition.
nsurprisingly: this breaks sN_s[ares.py.

354
354
7odules: a worked example % 5a
iNport tils
te!t R inpt#.KNOerS .*
nNOer R int#te!t*
s[ares_n R s[ares#nNOer*
total_n R total#s[ares_n*
print#total_n*
def s[ares#liNit*)
answer R []
for n in range#&$liNit*)
answer.append#nWW"*
retrn answer
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
tils.py
sN_s[ares.py
import: 7ake
a reference to
the other file.
iNport tils
and not
iNport tils.py
'e need to import the functioned defined in tils.py into
sN_s[ares.py.
-irst: we add the instruction 0iNport tils1 to the top of the
stN_s[ares.py file.
+ote that we import 0tils1: not 0tils.py1.

355
355
7odules: a worked example % 5b
$ python3 *u,E*qu+re*.py
KNOerS 1
Hra/eOa/k #Nost re/ent /all last*)
>ile =sN_s[ares.py=$ line 4$ in 7Nodle+
s[ares_n R s[ares#nNOer*
KaNeArror) naNe .s[ares. is not defined
#till can?t find the functionJsK.
/n its own this is not sufficient.

356
356
7odules: a worked example % 8a
iNport tils
te!t R inpt#.KNOerS .*
nNOer R int#te!t*
s[ares_n R tils.s[ares#nNOer*
total_n R tils.total#s[ares_n*
print#total_n*
sN_s[ares.py
utils.3: 4dentify
the functions
as coming from
the module.
s[ares#*
tils.s[ares#*
total#*
tils.total#*
'e ha!e to indicate to Python that these functions it is looking for in
sN_s[ares.py come from the tils module. ,o do this we include
0tils.1 at the start of their names.

357
357
7odules: a worked example % 8b
$ python3 *u,E*qu+re*.py
KNOerS 1
3&
$ python3 *u,E*qu+re*.py
KNOerS #
Q'
'orking againB
h
And now it works.

358
358
Progress
#haring functions between scripts
07odules1
4mporting modules
sing functions from modules
iNport module
module.fn/tion#*

359
359
6xercise .R
S minutes
,he script exercise.R.py is an answer to exercise&Z.
7o!e the function file_stats#* from exercise&Z.py
into utils.py and edit exercise&Z.py so that it still works.

360
360
,he Python philosophy
Nath
sys
string
A small core
language 3
3 plus lots
of modules
01atteries
included2
'e ha!e met the maFority of the Python language alreadyB But ob!iously
Python has facilities to do much more than we ha!e seen so far. ,he trick is
that Python comes with a large number of modules of its own which ha!e
functions for performing no end of useful things.
,his philosophy is called 0batteries included1. Hou probably already ha!e the
module you need to do your specialist application.

361
361
6xample: the 0math1 module
+++ i,port
+++ ,+th.
'.4'4"'3(6"383&Q('
,+th 2oad in the 0Nath1 module.
*un the s[rt#* function3
3 from the Nath module.
!.&) *qrt(
2et?s see an example of an 0included battery1. At the !ery start of this course
we write oursel!es a s@uare root program. +ow let?s see what Python offers
as an alternati!e.
'e import the 0Nath1 module. J+o trailing 0s1O this is the American spelling.K
4n the Nath module is a s[rt#K function. 'e can access this as
Nath.s[rt#*.
7ost of the fundamental mathematical operations can be found in the Nath
mo'e will see how to find out exactly what is in a module in a few slides?
time.

362
362
iNport module as alias
+++ i,port ,+th
+++ ,+th.
'.4'4"'3(6"383&Q('
+++ i,port ,+th +*
+++ ,
'.4'4"'3(6"383&Q('
*qrt(!.&)
,oo long to keep typing9
,
.*qrt(!.&)
0Alias1
,here are those who obFect to typing. 4f 0Nath1 is too long then we can use
an aliasing trick to gi!e the module a shorter name.
J,he problem is rarely with Nath. ,here is a built-in module called
0Nltipro/essing1 though which might get tiresome.K

363
363
Don?t do these
+++ 'ro, ,+th i,port *qrt
+++ *qrt(!.&)
'.4'4"'3(6"383&Q('
+++ 'ro, ,+th i,port 4
+++ *qrt(!.&)
'.4'4"'3(6"383&Q('
B
BB
(uch better
to track the
module.
python does permit you to do slightly more than that. Hou can suppress the
name of the module altogether.
Hou are beginners so please take it from an old hand on trust that this turns
out to be a !ery bad idea. Hou want to keep track of where your functions
came fromB

364
364
'hat system modules are there9
sys
os
string
re
/sB argparse
weOOrowser
Nath
/Nath
/olorsys
pi/kle
datetiNe
eNail
getpass
gloO
htNl
http
io
Tson
logging
randoN
signal
s[lite3
sOpro/ess
teNpfile
ni/odedata
nittest !Nl
Python 5...5 comes with o!er .SR modules.
,here are many modules that come with Python.

365
365
0Batteries included1
+++ help(',odule*')
Please wait a NoNent while F gather a list
of all aBailaOle Nodles...
CMGC% Oinas/ii inspe/t shle!
OdO iNportliO shelBe
Anter any Nodle naNe to get Nore help. Cr$
type =Nodles spaN= to sear/h for Nodles whose
des/riptions /ontain the word =spaN=.
.Y5 modules
+ot @uite this simple
,o find out exactly what modules come with your !ersion of Python ask the
help system.
A word of warning: though. ,he text at the bottom 06nter any module
name31 is not @uite right.
4f you gi!e the help#* command with no argument then you are dropped
into an interacti!e help system. ,here you can type the name of a module or
type 0Nodles spaN1: etc.
+++ help()
Jel/oNe to Python 3.'- Hhis is the online help tility.
3
help+ ,odule* *u=proe**
,ere is a list of Nat/hing Nodles. Anter any Nodle
naNe to get Nore help.
sOpro/ess U sOpro/ess U @Opro/esses with a//essiOle
F/C streaNs
help+ quit
+++

366
366
Additional downloadable modules
nNpy
s/ipy psy/opg"
%y@DLdO
/!_ora/le
iON_dO
pyodO/
3umerical
Postgre#>2
7y#>2
/racle
DB.
Databases
pyNss[l #>2 #er!er NatplotliO
4raphics
But: of course: there?s ne!er the particular module you want. ,here are
modules pro!ided by people who want Python to interoperate with whate!er
it is they are offering.
,here are three sets of additional modules that you may end up needing to
know about.
,he numerical and scientific world has a collection of modules called
+umerical Python J0nNpy1K and 0scientific python1 J1s/ipy1K which contain
enormous amounts of useful functions and types for numerical processing.
6!ery database under the sun offers a module to let Python access it.
-inally there is a module to offer !ery powerful .D graphics for data
!isualisation and presentation.

367
367
An example system module: sys
iNport sys
print#sys.argB*
argB.py
$ python3 +r-B.py one two three
[.argB.py.$
$ python3 +r-B.py 1 ! 3
[.argB.py.$ .3.] .".$ .'.$
Always strings
.three.] .two.$ .one.$
R & . 5 index
'e will take a brief look at another commonly used module to illustrate
some of the things Python has hidden away in its standard set.
,he 0sys1 module contains many systems-y things. -or example: it contains
a list called sys.argB which contains the arument %alues passed on the
command line when the script was launched.
+ote two things:
&. that item _ero in this list is always the name of the script itself:
.. the items are always strings

368
368
sys.e!it#*
e!it#* 'hat we ha!e been using
sys.e!it 'hat we should use #rc*
0*eturn "ode1: an integer
R: 6!erything was /N
QR: #omething went wrong
Also tucked away in the sys module is the sys.e!it#* function.
p to this point we ha!e been using the e!it#* function to @uit our scripts
early. )owe!er this function is something of a filthy hack and sys.e!it#*
pro!ides superior @uitting and an extra facility we will be able to make use
of.
,he sys.e!it#* function takes an integer argument. ,his is the program?s
0return code1 which is a !ery short message back to the operating system to
indicate whether the program completed successfully or not. A return code
of R means 0success1. A non-_ero return code means failure. #ome
programs use different non-_ero codes for different failures but many
Jmost9K simply use a !alue of & to mean 0something went wrong1.
4f your script simply stops because it reached the end then Python does an
automatic sys.e!it#&*.

369
369
An example system module: sys
But also:
sys.path
sys.Bersion
sys.Nodles
sys.stdin
sys.stdot
sys.stderr
Directories Python searches for modules
Dersion of Python
All modules currently imported
'here input inputs from
'here print prints to
'here errors print to
3and there?s moreB
sys.float_info All the floating point limits
And there?s plenty more3

370
370
7odules in Python
0)ow do 4 do
I in Python91
0'hat?s the Python
module to do I91
0'here do 4 find
Python modules91
#o the Python philosophy places a lot of functionality into its modules.
,his means that we ha!e to be able to find modules and know what they can
do.

371
371
-inding modules
Python:
PyP4:
Built-in modules
Python Package Index
#ciPy: 5cientific Python modules
#earch: 0Python5 module for I1
#ome useful *2s:
http)//do/s.python.org/py3k/pyUNodinde!.htNl
,his contains the list of all the 0batteries included1 modules that come with
Python. -or each module it links through to their documentation.
http)//www.s/ipy.org/Hopi/al_@oftware
http)//nNpy.s/ipy.org/
#cientific Python contains !ery many subFect-specific modules for Python.
7ost depend on the +umerical Python module nNpy.
http)//pypi.python.org/pypi Jdo check for Python5 packagesK
,his is the semi-official dumping ground for e!erything else.
http)//www.google./o.k/
And for e!erything else there?s Aoogle Jwho are big Python users: by the
wayK.

372
372
)elp with modules
+++ i,port ,+th
+++ help(,+th)
KI%A
Nath
MA@CGFPHFCK
Hhis Nodle is always aBailaOle. Ft proBides
a//ess to the NatheNati/al fn/tions defined
Oy the C standard.
3
4 promised information on how to find out what is in a module. )ere it is.
/nce a module has been imported you can ask it for help.

373
373
)elp with module functions
3
>EKCHFCK@
a/os#!*
Getrn the ar/ /osine #Neasred in
radians* of !.
3
+++ ,+th.+o*(1.&)
&.&
,he help will always include information on e!ery function in the module3

374
374
)elp with module constants
MIHI
e R ".8'9"9'9"94(Q&4(
pi R 3.'4'(Q"6(3(9Q8Q3
3
3
+++ ,+th.pi
3.'4'(Q"6(3(9Q8Q3
3and e!ery data item.

375
375
)elp for our own modules9
def s[ares#liNit*)
answer R []
for n in range#&$liNit*)
answer.append#nWW"*
retrn answer
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
tils.py
+++ i,port util*
+++ help(util*)
KI%A
tils
>EKCHFCK@
s[ares#liNit*
total#nNOers*
>FLA
/hoNe/y((&/tils.py
Basic help already
pro!ided by Python
'hat help can we get from our own module9
By now you should ha!e a tils.py file with some functions of your own in
it. ,he help simply lists the functions the module contains and the file it is
defined in.

376
376
Adding extra help text
def s[ares#liNit*)
answer R []
for n in range#&$liNit*)
answer.append#nWW"*
retrn answer
def total#nNOers*)
sN_so_far R &
for nNOer in nNOers)
sN_so_far <R nNOer
retrn sN_so_far
tils.py
+++ help(util*)
KI%A
tils
+++ i,port util* -resh start
===@oNe tility fn/tions
froN the Python for
IOsolte Peginners /orse
===
>EKCHFCK@
s[ares#liNit*

total#nNOers*
MA@CGFPHFCK
@oNe tility fn/tions
froN the Python for
IOsolte Peginners /orse
But we can do better than that.
4f we simply put a Python string Jtypically in long text triple @uotesK at the top
of the file before any used Python Jbut after comments is fineK then this
becomes the description text in the help.
+ote: Hou need to restart Python and re-import the module to see changes.

377
377
Adding extra help text to functions
===@oNe tility fn/tions
froN the Python for
IOsolte Peginners /orse
===
def s[ares#liNit*)
answer R []
for n in range#&$liNit*)
answer.append#nWW"*
retrn answer
tils.py
===Getrns a list of
s[ares froN ^ero to
liNitWW".
===
+++ help(util*)
KI%A
tils
MA@CGFPHFCK
...
+++ i,port util* -resh start
>EKCHFCK@
s[ares#liNit*
Getrns a list of
s[ares froN ^ero to
liNitWW".
4f we put text immediately after a def line and before the body of the
function it becomes the help text for that function: both in the module-as-a-
whole help text3

378
378
Adding extra help text to functions
===@oNe tility fn/tions
froN the Python for
IOsolte Peginners /orse
===
def s[ares#liNit*)
answer R []
for n in range#&$liNit*)
answer.append#nWW"*
retrn answer
tils.py
===Getrns a list of
s[ares froN ^ero to
liNitWW".
===
+++ help(util*.*qu+re*)
+++ i,port util* -resh start
s[ares#liNit*
Getrns a list of
s[ares froN ^ero to
liNitWW".
3and in the function-specific help text.

379
379
Progress
Python a small language3
3with many: many modules
#ystem modules
7odules pro!ide help
-oreign modules
Doc strings
-unctionality 7odule
help#module*
help#module.function*

380
380
6xercise .&
S minutes
Add help text to your tils.py file.

381
381
*ecap: 2ists ( 4ndices
list
3
Position .
Position &
Position R
greek R [.alpha.$ .Oeta.$ .gaNNa.]
str
( a l p h a
str
4 O e t a
str
( g a N N a
greek[&]
greek[']
greek["]
'e ha!e one last Python type to learn about. ,o gi!e it some context: we will
recap the list type that we ha!e spent so much time using.
A list is basically an ordered se@uence of !alues. ,he position in that
se@uence is known as the index.

382
382
04ndex in % Dalue out1
list
index !alue
' greek .Oeta. [']
7ust be
a number
4f we now forget about the internals of a list: though: we can think of it as
0some sort of Python obFect1 that takes in a number Jthe indexK and spits out
a !alue.

383
383
/ther 0indices1: #trings9
dictionary
6nglish #panish
./at.
.dog.
.Nose.
.gato.
.perro.
.ratcn.
dictionary
"an we generalise on this idea by mo!ing away from the input Jthe indexK
needing to be a number9
"an we model a dictionary where we take in a string Ja word in 6nglish: sayK
and gi!e out a different string Jthe corresponding word in #panish: sayK.
J+ote: the author is fully aware that translation is not as simple as this. ,his
is Fust a toy example.K

384
384
/ther 0indices1: ,uples9
dictionary
J#: yK /bFects
#"$(*
#4$(*
.Hreasre.
.>ortress.
dictionary
/r: perhaps: pairs of numbers Jx:yK in and items on a map out9

385
385
Python 0dictionaries1
+++ enEtoEe* . H '+t'D'-+to' , 'do-'D'perro' I
+++ enEtoEe*?'+t'@
.gato.
Python does ha!e exactly such a general purpose mapper which it calls a
0di/t1: short for 0dictionary1.
)ere is the Python for establishing a J!ery smallK 6nglish to #panish
dictionary that knows about two words.
'e also see the Python for looking up a word in the dictionary.
'e will re!iew this syntax in some detail3

386
386
"reating a dictionary d &
.dog.).perro. \ ] $ ./at.).gato.
"urly brackets
"omma
PcatP l PgatoP PdogP l PperroP
-irst we will look at creating a dictionary. 4n the same way that we can create
a list with s@uare brackets: we can create a dictionary with curly ones.
6ach item in a dictionary is a pair of !alues separated by a colo
,hey are separated by commas.n.

387
387
"reating a dictionary d .
.dog. \ ] $ ./at. .gato. ) .perro. )
PcatP PgatoP
0key1 0!alue1
:
:
,he pairs of items separated by colons are known as the 0key1 and 0!alue1.
,he key is what you put in Jthe 6nglish word in this exampleK that you look
up in the dictionary and the !alue is what you get out Jthe translation into
#panish in this exampleK.

388
388
sing a dictionary d &
+++ enEtoEe* . H '+t'D'-+to' , 'do-'D'perro' I
+++ enEtoEe*?'+t'@
.gato.
"reating the dictionary
sing the dictionary
+ow we ha!e seen how to create a JsmallK dictionary we should look at how
to use it.

389
389
sing a dictionary d .
en_to_es ] ./at. [ .gato.
dictionary key !alue
56uare brackets
,o look something up in a dictionary we pass it to the dictionary in exactly
the same way as we passed the index to a list: in square brackets. "urly
brackets are Fust for creating a dictionaryO after that it? s@uare brackets
again.

390
390
7issing keys
+++ enEtoEe* . H '+t'D'-+to' , 'do-'D'perro' I
+++ enEtoEe*?'do-'@
.perro.
+++ enEtoEe*?',ou*e'@
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+
`eyArror) .Nose. 6rror message

,he e@ui!alent to shooting off the end of a list is asking for a key that?s not in
a dictionary.

391
391
Dictionaries are one-way
B
+++ enEtoEe* .
+++ enEtoEe*?'do-'@
.perro.
+++ enEtoEe*?'perro'@
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+
`eyArror)

.perro.
2ooking for a &ey
H I 'do-'D , '+t'D 'perro' '-+to'
Also note that dictionaries are one.way.

392
392
Adding to a dictionary
+++ enEtoEe*
+++ enEtoEe*?',ou*e'@ . 'r+tJn'
+++ enEtoEe*?',ou*e'@
.ratcn.
. H '+t'D'-+to' , 'do-'D'perro' I
4nitial dictionary has no PmouseP
Adding PmouseP to the dictionary
Adding key-!alue pairs to a dictionary is a lot easier than it is with lists. 'ith
lists we needed to append on the end of a list. 'ith dictionaries: because
there is no inherent order: we can simply define them with a simple
expression on the left hand side.

393
393
*emo!ing from a dictionary
+++ print(enEtoEe*)
\.Nose.) .ratcn.$
+++ del enEtoEe*?
+++ print(enEtoEe*)
\.Nose.) .ratcn.$ ./at.) .gato.]
./at.) .gato.] .dog.) .perro.$
@ 'do-'
'e can use del to remo!e from a dictionary Fust as we did with lists.

394
394
Progress
Dictionaries Ney Dalue
T key
&
:!alue
&
: key
.
:!alue
.
: key
5
:!alue
5
U
di/tionary[key] Bale 2ooking up !alues
di/tionary[key] R Bale #etting !alues
del di/tionary[key] *emo!ing keys

395
395
6xercise ..
S minutes
"omplete exercise...py to create
an 6nglish to -rench dictionary.
cat chat
dog chien
mouse souris
snake serpent

396
396
'hat?s in a dictionary9 % &
+++ enEtoEe*
\.Nose.) .ratcn.$ .dog.) .perror.$ ./at.) .gato.]
+++ enEtoEe*.Cey*()
di/t_keys
+++ enEtoEe*.B+lue*()
di/t_Bales
<ust treat them like lists
/rders
match
#[.Nose.$ .dog.$ ./at.]*
#[.ratcn.$ .perro.$ .gato.]*
Jor con!ert them to listsK
,o date we ha!e created our own dictionaries. 4f we are handed one how do
we find out what keys and !alues are in it9
Dictionaries support two methods which return the sort-of-lists of the keys
and !alues. 'e mention them here only for completeness.
Don?t forget that you can always con!ert a sort-of-list into a list with the
list#* function.

397
397
'hat?s in a dictionary9 % .
+++ enEtoEe*
di/t_iteNs#[#.Nose.$ .ratcn.*$ #.dog.$ .perro.*$
#./at.$ .gato.*]*
+++ 'or (en-li*h, *p+ni*h) in enEtoEe*.ite,*()D
... print(*p+ni*h, en-li*h)
...
ratcn Nose
perro dog
gato /at
7ost useful method .ite,*()
JNey:DalueK pairs/tuples
By far the best way to get at the contents of a dictionary is to use the
iteNs#* method which generates a sort-of-list of the key-!alue pairs as
tuples. *unning a for3 loop o!er this list is the easiest way to process the
contents of a directory.

398
398
'hat?s in a dictionary9 % 5
+++ li*t
[#.Nose.$.ratcn.*$ #.dog.$.perro.*$#./at.$.gato.*]
"ommon simplification
(enEtoEe*.ite,*())
Don?t be afraid to con!ert it explicitly into a list. nless you dictionary is huge
you won?t see any problem with this.

399
399
Aetting the list of keys
dictionary
list of
keys
list#*
\.the.) "$ ./at.) '$ .sat.) '$ .on.) '$ .Nat.) ']
[.on.$ .the.$ .sat.$ .Nat.$ ./at.]
nfortunately when you con!ert a dictionary directly into a list you get the list
of keys not the list of KJkey:!alueK pairs. ,his is a shame but is a compromise
for back compatibility with pre!ious !ersions.

400
400
4s a key in a dictionary9
+++ enEtoEe*?'*n+Ce'@
Hra/eOa/k #Nost re/ent /all last*)
>ile =7stdin+=$ line '$ in 7Nodle+
`eyArror) .snake. 'ant to a!oid this
+++ '*n+Ce' in enEtoEe*
>alse
'e can test for it
Because of this con!ersion to the list of keys we can ask if a key is in a
dictionary using the in keyword without ha!ing to know its corresponding
!alue.

401
401
6xample: "ounting words % &
words R [.the.$./at.$.sat.$.on.$.the.$.Nat.]
/onts R \.the.)"$./at.)'$.sat.)'$.on.)'$.Nat.)']
2et?s ha!e a serious worked example.
'e might be gi!en a list of words and want to count the words by how many
times they appear in the list.

402
402
6xample: "ounting words % .
words R [.the.$./at.$.sat.$.on.$.the.$.Nat.]
/onts R \]
for word in words)
Do something
#tart with an empty dictionary
'ork through all the words
'e start by creating an empty dictionary. 4t?s empty because we ha!en?t
read any words yet.
,hen we loop through the list of words using a standard for3 loop.
-or each word we ha!e to do something to increment the count in the
dictionary.

403
403
6xample: "ounting words % 5
words R [.the.$./at.$.sat.$.on.$.the.$.Nat.]
/onts R \]
for word in words)
/onts[word] <R '

,his will not work


/onter'.py
nfortunately a simply increment of the !alue in the dictionary isn?t enough.

404
404
'hy doesn?t it work9
/onts R \.the.)'$ ./at.)']
/onts[.the.] <R '
/onts[.sat.] <R '

/onts[.the.] R < ' /onts[.the.]


,he key must already
be in the dictionary.
/onts[.sat.] R < ' /onts[.sat.]
Ney is not in
the dictionaryB
'e cannot increment a !alue that isn?t there. ntil the program meets a
word for the first time it has no entry in the dictionary: and certainly not an
entry with numerical !alue R.

405
405
6xample: "ounting words % 8
words R [.the.$./at.$.sat.$.on.$.the.$.Nat.]
/onts R \]
for word in words)
if word in /onts)
/onts[word] <R '
else)
Do something
+eed to add the key
#o we ha!e to test to see if the word is already in the dictionary to increment
it if it is there and to do something else if it is not. +ote how we use the 0if
key in dictionary1 test.

406
406
6xample: "ounting words % S
words R [.the.$./at.$.sat.$.on.$.the.$.Nat.]
/onts R \]
for word in words)
if word in /onts)
/onts[word] <R '
else)
/onts[word] R '
/onter".py
print#/onts*
,hat something else is to create it with its initial !alue of & Jbecause we ha!e
met the word once nowK.

407
407
6xample: "ounting words % Y
$ python3 ounter!.py
\.on.) '$ .the.) "$ .sat.) '$ .Nat.) '$ ./at.) ']
Hou cannot predict the order of the
keys when a dictionary prints out.
B
Dictionaries are unordered entities. Hou cannot predict the order that the
keys will appear when you print a dictionary or step through its keys.

408
408
6xample: "ounting words % [
print#/onts*
iteNs R list#di/tionary.iteNs#**
iteNs.sort#*
for #key$ Bale* in iteNs)
print#key$ Bale*

,oo ugly
Better
/onter3.py
#imply printing a dictionary gi!es ugly output.
'e can pull out the Jkey:!alueK pairs and print them indi!idually if we want.
+otice the use of pulling out the items: con!erting them into a list and then
sorting them.

409
409
6xample: "ounting words % X
$ python3 ounter3.py
/at '
Nat '
on '
sat '
the "

410
410
Progress
,esting keys in dictionaries
"reating a list of keys
if key in di/tionary)
...
keys R list#di/tionary*
4nspection methods di/tionary.keys#*
di/tionary.Bales#*
di/tionary.iteNs#*

411
411
6xercise .5
&R minutes
"omplete exercise.5.py to write
a function that re!erses a dictionary.
\
\
.perro.] .dog.) .gato.$ ./at.) .ratcn.$ .Nose.)
).dog.] .perro. ./at.$ .gato.) .Nose.$ .ratcn.)

412
412
-ormatted output
$ python3 ounter3.py
/at '
Nat '
sat '
the "
on ' glyB
/at
Nat
on
sat
the
'
'
'
'
"
'e want data
nicely aligned
'e ha!e one last topic to co!er. ,he output from our word counter is not as
pretty as it might be. ,he last topic we will co!er is Python text formatting.
-ull details of the formatting system can be found online at
do/s.python.org/py3k/liOrary/string.htNl_forNatspe/

413
413
,he formatJK method
+++
.!!!Iyyy'&&^^^.
'xxxHIyyyHIGGG'.'or,+t('F', 1&&)
.
.
^^^ \] yyy \] !!! .
. ^^^ '&& yyy I !!!
4n Python 5 the string type has a method called forNat#* which takes
arguments and returns another string which is the original with the method?s
arguments inserted into it in certain places. ,hose places are marked with
curly brackets in the string.
"urly brackets are otherwise @uite normal characters. 4t?s only the
forNat#* method that cares about them.
4n its simplest form: the forNat#* method replaces each pair of curly
brackets with the corresponding argument.

414
414
#tring formatting % &
+++
.!!!Iyyy.
'xxxHD1*Iyyy'.'or,+t('F')
.
.
yyy \)(s] !!! .
. yyy I !!!
\)(s]
s % substitute a string
S % pad to + spaces
Jleft aligns by defaultK
,he real fun starts when we put something inside those curly brackets.
,hese are the formatting instructions.
,he simplest examples start with a colon followed by some layout
instructions. J'e will see what comes in front of the colon in a few slides
time.K ,he number indicates how many spaces to allocate for the insertion
and the letter that follows tells it what type ob obFect to expect. 0s1 stands for
string.

415
415
#tring formatting % .
+++
.!!!Iyyy.
'xxxHD91*Iyyy'.'or,+t('F')
.
.
yyy \)7(s] !!! .
. yyy I !!!
\)7(s]
^ % align to the left J7K
By default strings align to the left of their space. 'e can be explicit about
this by inserting a left angle bracket: which you can think of as an arrow
head pointing the direction of the alignment.

416
416
#tring formatting % 5
+++
.!!!Iyyy.
'xxxHD:1*Iyyy'.'or,+t('F')
.
.
yyy \)+(s] !!! .
. yyy I !!!
\)+(s]
` % align to the right J8K
4f we want right aligned strings then we ha!e to use the alignment marker.

417
417
4nteger formatting % &
+++
.!!!'"3yyy.
'xxxHD1dIyyy'.'or,+t(1!3)
.
.
yyy \)(d] !!! .
. yyy '"3 !!!
\)(d]
d % substitute an integer
S % pad to + spaces
Jright aligns by defaultK
JdigitsK
4f we change the letter to a 0d1 we are telling the forNat#* method to insert
an integer J0digits1K. ,hese align to the right by default.

418
418
4nteger formatting % .
+++
.!!!'"3yyy.
'xxxHD:1dIyyy'.'or,+t(1!3)
.
.
yyy \)+(d] !!! .
. yyy '"3 !!!
\)+(d]
` % align to the right J8K
'e can be explicit about this if we want.

419
419
4nteger formatting % 5
+++
.!!!'"3yyy.
'xxxHD:1dIyyy'.'or,+t(1!3)
.
.
yyy \)7(d] !!! .
. yyy '"3 !!!
\)7(d]
^ % align to the left J7K
And we ha!e to be explicit to o!erride the default.

420
420
4nteger formatting % 8
+++
.!!!&&'"3yyy.
'xxxHD&1dIyyy'.'or,+t(1!3)
.
.
yyy \)&(d] !!! .
. yyy &&'"3 !!!
\)&(d]
R % pad with _eroes
4f we precede the width number with a _ero then the number is padded with
_eroes rather than spaces and alignment is automatic.

421
421
4nteger formatting % S
+++
.!!!<'"3yyy.
'xxxHD(1dIyyy'.'or,+t(1!3)
.
.
yyy \)<(d] !!! .
. yyy <'"3 !!!
\)&(d]
; % always show sign
4f we put a plus sign in front of the number then its sign is always shown:
e!en if it is positi!e.

422
422
4nteger formatting % Y
+++
.!!!<&'"3yyy.
'xxxHD(&1dIyyy'.'or,+t(1!3)
.
.
yyy \)<&(d] !!! .
. yyy <&'"3 !!!
\)&(d]
; % always show sign
R % pad with _eroes
And we can combine these.

423
423
4nteger formatting % [
+++
.!!!'$"34yyy.
'xxxHD1,dIyyy'.'or,+t(1!30)
.
.
yyy \)($d] !!! .
. yyy '$"34 !!!
\)($d]
: % &:RRRs
Adding a comma between the width and the 0d1 adds comma breaks to
large numbers.

424
424
-loating point formatting % &
+++
.!!! '."&yyy.
'xxxHD1.!'Iyyy'.'or,+t(1.!)
.
.
yyy \)(."f] !!! .
. yyy '."& !!!
\)(."f]
f % substitute a float
S % + places in total
.. % ) places after the point
-loating point numbers are slightly more complicated. ,he width parameter
has two parts: separated by a decimal point. ,he first number is the width of
the entire number JFust as it is for strings and integersK. ,he number after the
decimal point is the number of decimal points of precision that should be
included in the formatted output.

425
425
-loating point formatting % .
+++
.!!!'."&&&&&yyy.
'xxxHD'Iyyy'.'or,+t(1.!)
.
.
yyy \)f] !!! .
. yyy '."&&&&& !!!
\)f]
\).6f]
,he default is to ha!e six decimal points of precision and to make the field
as wide as it needs to be.

426
426
/rdering and repeats % &
+++
.d
'K ) 1.!3 1!3, '+=', K'.'or,+t( HD'I K HDdI K HD*I
d. '."3&&&& d '"3 d aO/
R & .
R & .
R & .
+++ 'K ) 1.!3 1!3, '+=', K'.'or,+t( H!D'I K H1DdI K H&D*I
.d d. '."3&&&& d '"3 d aO/
R & .
R & .
6@ui!alent
'hat comes before the colon9
,his is a selection parameter detailing what argument to insert.
,he arguments to forNat#* are gi!en numbers starting at _ero. 'e can
put these numbers in front of the colon.

427
427
/rdering and repeats % .
+++ 'K ) 1.!3 1!3, '+=', K'.'or,+t( H!D'IKH1DdI K H&D*I
.d d '."3&&&& d '"3 d aO/
R & .
R & .
.
+++ 'K ) 1.!3 1!3, '+=', K'.'or,+t( K H1DdI K H&D*I
.d d '"3 d aO/
R &
R & .
d.
H1DdI
'"3
&
'e can also use them to change the order that items appear in or to ha!e
them appear more than once Jor not at allK.

428
428
-ormatting in practice
$ python3 ounter0.py
/at
Nat
on
sat
the
'
'
'
'
"
...
forNatting R .\)3] \)'].
for #word$ nNOer* in iteNs)
print#forNatting.forNat#word$nNOer**
$
,he script /onter4.py is the same as counter5.py but with the new
formatting for its output.

429
429
Progress
string.forNat#args* -ormatting
+umbered parameters
#ubstitutions
\&] \'] \"]
\)+6s]
\)<&6d]
\)<&'".8f]

430
430
6xercise .8
S minutes
"omplete exercise.8.py
to format the output as shown:
eoe Q
@aNantha 4(
%ethselah Q6Q
[#eoe$Q*$ #@aNantha$4(*$ #%ethselah$Q6Q*]

431
431
And thatPs itB JAnd 0it1 is a lotBK
,ext
Prompting
+umbers
Arithmetic
"omparisons
Booleans
Dariables
Deleting names
0while1 loop
0if1 test
4ndented blocks
2ists
4ndices
/bFect methods
Built-in help
0for1 loops
0,reat it like a list31
Dalues direct/!ia index
*eading files
'riting files
-unctions
0#tructured programming1
,uples
0for1 loops
7odules
Dictionaries
-ormatting
And congratulationsB
Hou ha!e completed an introductory course on Python. 'ell done.
4t is only an introductory course and there is more. But do not let that
dishearten youO Fust take a look at what you ha!e accomplished. Hou now
ha!e a firm grounding to go further with Python or to start learning other
programming languages. JBut the author would like you to stick with
Python.K

432
432
But waitB ,here?s more3
Ad!anced topics: #elf-paced introductions to modules
/bFect-oriented programming in Python
4f you do want more Python the "# offers a selection of self-paced courses
on some additional language features and on !arious Python modules to let
you learn how to use Python for a specific purpose. 'e also offer a taught
course introducing you to the world of obFect-oriented programming where
you get to write your own methods and types.

433
433
,ext
Prompting
+umbers
Arithmetic
"omparisons
Booleans
Dariables
Deleting names
0while1 loop
0if1 test
4ndented blocks
2ists
4ndices
/bFect methods
Built-in help
0for1 loops
0,reat it like a list31
Dalues direct/!ia index
*eading files
'riting files
-unctions
0#tructured programming1
,uples
0for1 loops
7odules
Dictionaries
-ormatting
"ongratulationsB
#o thank you and congratulations again.
Python 3 formatting codes
Use of the format() method:
>>> '{:4s} {:3d}'.format('Dave', 27)
'Dave27'
>>>
The symbol is used to represent a space.
Strings
hello
{:s} hello
{:10s} hello
{:<10s} hello
{:>10s} hello
Integers
1,234 -1,234
{:d} 1234 -1234
{:10d} 1234 -1234
{:<10d} 1234 -1234
{:>10d} 1234 -1234
{:+10d} +1234 -1234
{:010d} 0000001234 -000001234
{:+010d} +000001234 -000001234
{:10,d} 1,234 -1,234
{:+10,d} +1,234 -1,234
Floating point
3141!"2#!3!$"7"3 -12
{:f} 3141!"3 -1200000
{:10f} 3141!"3 -1200000
{:10!f} 3141!" -120000
{:<10!f} 3141!" -120000
{:>10!f} 3141!" -120000
{:+10!f} +3141!" -120000
{:010!f} 0003141!" -00120000
{:+010!f} +003141!" -00120000

You might also like