An Introduction To Python For Absolute Beginners
An Introduction To Python For Absolute Beginners
Bob Dowling
University Information Services
[email protected]
http://www.ucs.cam.ac.uk/docs/course-notes/unix-courses/PythonAB 1
But first…
Fire escapes Toilets
No drinks or snacks
Notes
in the room, please.
Signing in
Feedback
2
Course outline ― 1
Who uses Python & what for
What sort of language it is
Text
Names for values
Reading in user data
Numbers
Conversions
Comparisons
Truth & Falsehood
3
Course outline ― 2
Assignment
Names
Loops
if… else…
Indentation
Comments
4
Course outline ― 3
Lists
Indices
Lengths
Changing items
Extending lists
Methods
Creating lists
Testing lists
Removing from lists
for… loop
Iterables
Slices
5
Course outline ― 4
Files
Reading & writing
Tuples
Modules
System modules
External modules
Dictionaries
Formatted text
6
Who uses Python?
On-line games
Web services
Applications
Science
Instrument control
Embedded systems
en.wikipedia.org/wiki/List_of_Python_software
7
What sort of language is Python?
Compiled Interpreted
8
Running Python ― 1
9
Running Python ― 2
Unix prompt
Unix command
Introductory blurb
$ python3
Python 3.2.3 (default, May 3 2012, 15:54:42)
[GCC 4.6.3] on linux2
Python prompt
10
Quitting Python
>>> exit()
Any one
>>> quit()
of these
>>> Ctrl + D
11
A first Python command
Python prompt
Python command
12
Python commands
Python “function”
Round brackets
― “parentheses”
print('Hello, world!')
Function’s “argument”
13
Python text
Quotation marks
'Hello, world!'
The body
of the text
!
part of the text itself.
14
Quotes?
print Command
'print' Text
15
Python scripts
File in home directory print('Hello, world!')
Unix prompt
Unix command
to run Python
$ Unix prompt 16
Editing Python scripts — 1
17
Editing Python scripts — 2
18
Progress
Interactive Python
Python scripts
print() command
19
Exercise 1
2 minutes
20
A little more text
www.unicode.org/charts/ hello2.py
21
Getting characters
˘
ğ Character Selector
“LATIN SMALL
LETTER G \u011f
WITH BREVE”
22
Text: a “string” of characters
Class: string
Length: 13
Letters
str 13 H e l l o , ␣ w o r l d !
23
Text: “behind the scenes”
str 13 72 101 108 108 111 44 32 … 100 33
>>> ord('ğ')
287
28710
>>> chr(287)
'ğ'
ğ 24
Adding strings together: +
hello3.py
>>> 'Hello, ' + 'world!'
'Hello, world!'
>>>
25
Pure concatenation
>>> 'Hello,␣' + 'world!'
'Hello, world!'
27
Python strings: input & output
'Hello, world!'
Single or double
quotes on input.
"Hello, world!"
Create same
string object.
str 13 H e l l o , ␣ w o r l d !
28
Uses of single & double quotes
29
Why we need different quotes
✘
File "<stdin>", line 1
print('He said 'hello' to her.')
^
SyntaxError: invalid syntax
30
Adding arbitrary quotes
>>> print('Hello, ↵
✘
File "<stdin>", line 1
print('Hello,
^
SyntaxError: EOL while
scanning string literal “EOL”: End Of Line
32
Inserting “special” characters
>>> print('Hello,\nworld!')
Hello, Treated as
world! a new line.
\n Converted into a
single character.
str 13 H e l l o , ↵ w o r l d !
>>> len('Hello,\nworld!')
13 len() function: gives
the length of the object
33
The backslash
Special Ordinary \' '
\" "
Ordinary Special \n ↵
\t ⇥
34
\n: unwieldy for long text
'SQUIRE TRELAWNEY, Dr. Livesey, and the\n
rest of these gentlemen having asked me\n
to write down the whole particulars\nabou
t Treasure Island, from the\nbeginning to
the end, keeping nothing\nback but the b
earings of the island,\nand that only bec
ause there is still\ntreasure not yet lif
ted, I take up my\npen in the year of gra
ce 17__ and go\nback to the time when my
father kept\nthe Admiral Benbow inn and t
he brown\nold seaman with the sabre cut f
irst\ntook up his lodging under our roof.'
Single
line 35
Special input method for long text
'''SQUIRE TRELAWNEY, Dr. Livesey, and the
rest of these gentlemen having asked me
to write down the whole particulars
about Treasure Island, from the
beginning to the end, keeping nothing
back but the bearings of the island,
and that only because there is still
treasure not yet lifted, I take up my
pen in the year of grace 17__ and go
back to the time when my father kept
the Admiral Benbow inn and the brown
old seaman with the sabre cut first
took up his lodging under our roof.'''
Triple Multiple
quotes lines 36
Python’s “secondary” prompt
>>> '''Hello,
... world'''
Python asking for more
of the same command.
37
It’s still just text!
>>> 'Hello,\nworld!'
'Hello\nworld'
Python uses \n to represent
line breaks in strings.
>>> '''Hello,
... world!'''
38
Your choice of input quotes:
Four inputs:
'Hello,\nworld!' "Hello,\nworld!"
'''Hello, """Hello,
world!''' world!"""
Same result:
str 13 H e l l o , ↵ w o r l d !
39
Progress
International text
print()
Concatenation of strings
Special characters
Long strings
40
Exercise 2
coffee
café
caffè
Kaffee
é \u00e8 AltGr + ; e
'Hello, world!'
>>> type(message)
<class 'str'>
message str 13 H e l l o , ␣ w o r l d !
42
Attaching names to values
message = 'Hello, world!'
print(message)
>>> type(print)
print function
message str 13 H e l l o , ␣ w o r l d !
43
Reading some text into a script
message = input('Yes?␣')
print(message)
input('Yes?␣')
Boo! print(message)
44
Can't read numbers directly!
$ python3 input2.py number = input('N?␣')
print(number + 1)
✘
N? 10
input2.py
string integer 45
input(): strings only
$ python3 input2.py number = input('N?␣')
print(number + 1)
✘
N? 10
input2.py
input('N?␣') str 2 1 0
≠ int 10
46
Some more types
>>> type(42)
>>> type(3.14159)
>>> int('␣-100␣')
str 6 ␣ - 1 0 0 ␣
-100
int -100
>>> int('100-10')
✘
ValueError:
invalid literal for int() with base 10: '100-10'
48
Converting text to floats
>>> float('␣10.␣')
10.0
49
Converting between ints and floats
>>> float(10)
10.0
>>> int(10.9)
10 Truncates
fractional part
>>> int(-10.9)
-10
50
Converting into text
'10'
'10.0'
51
Converting between types
52
Reading numbers into a script
text = input('N?␣')
number = int(text)
$ python3 input3.py print(number + 1)
N? 10
11
53
Stepping through our script — 1
text = input('N?␣')
str 3 N ? ␣ number = int(text)
print(number + 1)
54
Stepping through our script — 2
text = input('N?␣')
str 3 N ? ␣ number = int(text)
print(number + 1)
input function
55
Stepping through our script — 3
text = input('N?␣')
number = int(text)
print(number + 1)
input function
text str 2 1 0
56
Stepping through our script — 4
text = input('N?␣')
number = int(text)
print(number + 1)
input function
text str 2 1 0
int function
int 10
57
Stepping through our script — 5
text = input('N?␣')
number = int(text)
print(number + 1)
input function
text str 2 1 0
int function
number int 10
58
Stepping through our script — 6
text = input('N?␣')
number = int(text)
print(number + 1)
number int 10
59
Stepping through our script — 7
text = input('N?␣')
number = int(text)
print(number + 1)
+ function
int 11
60
Stepping through our script — 6
text = input('N?␣')
number = int(text)
print(number + 1)
number int 10
int 11
print function 61
Progress
Names Values name = value
Types strings
integers
3 minutes
63
Integers
ℤ {… -2, -1, 0,
1, 2, 3, 4 …}
64
Integer addition & subtraction
>>> 20+5
25
“No surprises”
65
Integer multiplication
There is no “×” on the keyboard. Linux:
AltGr + Shift + ,
Use “*” instead
>>> 20␣*␣5
100
Still no surprises
66
Integer division
There is no “÷” on the keyboard. Linux:
AltGr + Shift + .
Use “/” instead
>>> 20␣/␣5
4.0 This is a floating point number!
Surprise!
67
Integer division gives floats !
Fractions Floats sometimes
!
Consistency Floats always
>>> 20␣/␣40
0.5
>>> 20␣/␣30
0.6666666666666666
68
Integer powers
There is no “42” on the keyboard.
69
Integer remainders
e.g. Is a number even or odd?
Use “%”
>>> 4␣%␣2
0
>>> 5␣%␣2
1
>>> -5␣%␣2
1 Remainder is always non-negative
70
How big can a Python integer be?
>>> 2**2
4
>>> 4**2
16
>>> 16**2
256
>>> 256**2
65536
>>> 65536**2
4294967296
71
How big can a Python integer be?
>>> 4294967296**2
18446744073709551616
>>> 18446744073709551616**2
340282366920938463463374607431768211456
>>> 340282366920938463463374607431768211456**2
1157920892373161954235709850086879078532699846
65640564039457584007913129639936
>>> 115792089237316195423570985008687907853269
984665640564039457584007913129639936**2
1340780792994259709957402499820584612747936582
0592393377723561443721764030073546976801874298
1669034276900318581864860508537538828119465699
72
46433649006084096
How big can a Python integer be?
10443888814131525066917527107166243825799642490473837803842334832839
53907971557456848826811934997558340890106714439262837987573438185793
60726323608785136527794595697654370999834036159013438371831442807001
18559462263763188393977127456723346843445866174968079087058037040712
84048740118609114467977783598029006686938976881787785946905630190260
94059957945343282346930302669644305902501597239986771421554169383555
98852914863182379144344967340878118726394964751001890413490084170616
There is no limit!
75093668333850551032972088269550769983616369411933015213796825837188
09183365675122131849284636812555022599830041234478486259567449219461
70238065059132456108257318353800876086221028342701976982023131690176
78006675195485079921636419370285375124784014907159135459982790513399
61155179427110683113409058427288427979155484978295432353451706522326
Except for
90613949059876930021229633956877828789484406160074129456749198230505
71642377154816321380631045902916136926708342856440730447899971901781
machine
46576347322385026725305989979599609079946920177462481771844986745565
memory
92501783290704731194331655508075682218465717463732968849128195203174
57002440926616910874148385078411929804522981857338977648103126085903
00130241346718972667321649151113160292078173803343609024380470834040
3154190336
73
Big integers
2
C / C++
Fortran
4
16
int
INTEGER*4 256
long 65536
INTEGER*8
4294967296
long long
INTEGER*16 18446744073709551616
ℝ
✗ 1.0
0.33333333
3.14159265
2.71828182 75
Basic operations
>>> 20.0 + 5.0 >>> 20.0 - 5.0
25.0 15.0
76
Floating point imprecision
>>> 1.0 / 3.0
0.3333333333333333
≈ 17 significant figures
77
Hidden imprecision
>>> 0.1
!
0.1
1.8446744073709552 e+19
1.8446744073709552 ×1019
79
Floats are not exact
>>> 4294967296.0**2 Floating point
1.8446744073709552e+19
1.8446744073709552×1019 18446744073709552000
- 18446744073709551616
384
80
How big can a Python float be? ― 2
>>> 1.8446744073709552e+19**2
3.402823669209385e+38
>>> 3.402823669209385e+38**2
1.157920892373162e+77
81
Floating point limits
1.2345678901234567 × 10N
17 significant figures
Positive values:
4.94065645841×10-324 < N < 8.98846567431×10307
82
Complex numbers
ℑ
ℂ
z2
z
ℜ
>>> (1.25+0.5j)**2
(1.3125+1.25j)
83
Progress
Arithmetic + - * / ** %
Integers No limits!
Limited precision
Complex numbers
84
Exercise 4
1. 223 ÷ 71
2. (1 + 1/10)10
3. (1 + 1/100)100
4. (1 + 1/1000)1000
3 minutes
85
Comparisons
5 < 10 ✔
5 > 10 ✘
86
Comparisons
87
True & False
>>> type(True)
<class 'bool'> “Booleans”
5 + 10 15 int
int int
bool ✓ True
Only two values
bool ✗ False
89
Six comparisons
Maths Python
≠ !=
< <
> >
≤ <=
≥ >=
90
Equality comparison & assignment
= name = value
== value1 == value2
91
Textual comparisons
True
True
True
92
Ordering text is complicated
Python inequalities use Unicode character numbers.
Alphabetical order?
German: z<ö
Swedish: ö<z
93
“Syntactic sugar”
0 < number
number < 10
>>> number = 5
True
94
Converting to booleans
float() Converts to floating point numbers
<class 'float'>
int() Converts to integers
<class 'int'>
str() Converts to strings
<class 'str'>
0 False Zero
1 True Non-zero
12 True
96
-1 True
Boolean operations
bool
? bool
bool
97
Boolean operations ― “and”
bool
and bool
bool
99
Boolean operations ― “or”
bool
or bool
bool
101
Boolean operations ― “not”
102
Boolean operations ― “not”
False
True
103
Ambiguity in expressions
3+6/3
✘ ✔
(3 + 6) / 3 3 + (6 / 3)
3 5
104
Division before addition
3+6/3
Division first
3+ 2
Addition second
5
105
“Order of precedence”
First
not x x and y x or y
106
Last
Progress
Comparisons == != < > <= >=
3. 60 - 45 / 5 + 10 == 1
3 minutes
108
Names and values: “assignment”
alpha = 100
110
Simple evaluations
>>> beta = 100 + 20
1. 100 + 20 RHS
2.
int 120
3. LHS
beta int 120
111
Changing value — 1
>>> gamma = 1
>>> gamma = 2
112
Changing value — 2
RHS
>>> gamma = 1
int 1
113
Changing value — 3
LHS
>>> gamma = 1
gamma int 1
114
Changing value — 4
RHS
>>> gamma = 1
gamma int 1
>>> gamma = 2
int 2
115
Changing value — 5
LHS
>>> gamma = 1
gamma int 1
>>> gamma = 2
int 2
116
Changing value — 6
garbage collection
✘
>>> gamma = 1
gamma int 1
>>> gamma = 2
int 2
117
Changing value — 7
>>> gamma = 1
gamma
>>> gamma = 2
int 2
118
Changing value — a subtlety
✘
>>> gamma = 1
gamma int 1
>>> gamma = 2
119
Names on the RHS — 1
>>> delta = alpha + 40
alpha + 40 RHS
1.
alpha
2.
3.
int 140
120
Names on the RHS — 2
>>> delta = alpha + 40
LHS
4. delta int 140
121
Same name on both sides — 0
Starting
delta int 140 position
>>> print(delta)
140
122
Same name on both sides — 1
RHS
>>> delta = delta + 10
1. delta + 10
2. delta
3.
int 140 function + int 10
4.
int 150
123
Same name on both sides — 2
LHS
>>> delta = delta + 10
int 150
✗
7.
delta No longer
int 140
used.
126
Deleting a name ― 1
>>> print(thing)
>>> print(thing)
1
127
Deleting a name ― 2
>>> print(thing)
1 Known
variable
>>> del thing
>>> print(thing)
129
Our first “real” program
130
Square root of 2.0 by “bisection”
“Interval of uncertainty”
1.0**2
1.0
Mid-point: 1.0
132
Square root of 2.0 by bisection — 2
2 2
midpoint < √2
1.5**2
2.25
Mid-point: 1.5
134
Square root of 2.0 by bisection — 4
1.25**2
1.5625
Mid-point: 1.25
136
Square root of 2.0 by bisection — 6
1.375**2
1.890625
Mid-point: 1.375
138
Square root of 2.0 by bisection — 8
2 minutes
140
1.375 < √2 < 1.5
Understanding before Programming
141
And now using Python!
lower = 0.0
upper = 2.0
middle = (lower+upper)/2
142
And now using Python — 2
True
lower = middle
print(lower, upper)
1.0 2.0
143
And now using Python — 3
middle = (lower+upper)/2
print(middle, middle**2)
1.5 2.25
144
And now using Python — 4
False
upper = middle
print(lower, upper)
1.0 1.5
145
And now using Python — 5
middle = (lower+upper)/2
print(middle, middle**2)
1.25 1.5625
146
And now using Python — 6
True
lower = middle
print(lower, upper)
1.25 1.5
147
And now using Python — 7
middle = (lower+upper)/2
print(middle, middle**2)
1.375 1.890625
148
And now using Python — 8
True
lower = middle
print(lower, upper)
1.375 1.5
149
Looking at the Python code
lower = 0.0
upper = 2.0
middle = (lower+upper)/2
print(middle, middle**2)
✔ ? ✘
lower = middle upper = middle
middle = (lower+upper)/2
print(middle, middle**2)
Choice
middle**2 < 2.0
✔ ? ✘
lower = middle upper = middle
Before
Should the
Loop test
loop run
✘ ✔ (again)?
What is
Loop body run each
loop?
After
152
Loop example: Count from 1 to 10
Before number = 1
✘ ✔ ✘ ✔
print(number)
Loop body number += 1
After print('Done!')
153
Loop example: Count from 1 to 10
number = 1 number = 1
✘ ✔
print('Done!') print('Done!')
154
Loop test: Count from 1 to 10
number = 1
“while” keyword
loop test
while number <= 10 : colon
␣␣␣␣ print(number)
␣␣␣␣ number += 1
print('Done!')
155
Loop body: Count from 1 to 10
number = 1
␣␣␣␣ print(number)
␣␣␣␣ number += 1 loop body
indentation
print('Done!')
156
Loop example: Count from 1 to 10
$ python3 while1.py
number = 1
1
while number <= 10 : 2
3
print(number)
4
number += 1
5
6
print('Done!') 7
8
9
while1.py 10
Done!
$
157
Python’s use of indentation
number = 1
1
1(a)
1(b)
1(b)(i)
1(b)(ii)
1(b)(iii)
1(c)
2
3
159
Other languages
C while ...
{ { ... } Syntax
␣␣␣␣...
␣␣␣␣... ␣␣␣␣... Clarity
}
160
Progress
while ... : before
while test :
test to keep looping ␣␣␣␣action1
␣␣␣␣action2
␣␣␣␣action3
code blocks
afterwards
␣␣␣␣indentation
161
Exercise 7
while6.py
×½
1.0 2.0
1.0
What we want
×½
1.0 1.5
0.5
×½
1.25 1.5
0.25
×½
1.375 1.5
0.125 What we get 163
Keep looping while … ?
uncertainty > tolerance
164
Square root: the loop
tolerance = 1.0e-15 Set up
lower = 0.0
upper = 2.0
uncertainty = upper - lower
Loop
while uncertainty > tolerance :
print(lower, upper)
165
uncertainty = upper - lower
Choosing
Choice
middle**2 < 2.0
✔ ? ✘
lower = middle upper = middle
167
if…then… else… ― 1
if keyword
Test
if number % 2 == 0 : Colon
else :
168
if…then… else… ― 2
if number % 2 == 0 :
169
if…then… else… ― 3
if number % 2 == 0 :
170
if…then… else… ― 4
if number % 2 == 0 :
else :
171
Our square root example
middle = (lower + upper)/2 Before
else: if test :
␣␣␣␣action1
␣␣␣␣action2
choice of two else:
code blocks ␣␣␣␣action3
afterwards
␣␣␣␣indentation
173
Exercise 8
5 minutes
174
Back to our example
tolerance = 1.0e-15
lower = 0.0
upper = 2.0
uncertainty = upper - lower
sqrt1.py
☺ 177
Script for the square root of 2.0
tolerance = 1.0e-15
lower = 0.0
upper = 2.0 √2.0
uncertainty = upper - lower
179
Initial bounds?
lower = ?
upper = ?
if...then...else...
180
Initial bounds
181
Generic square root script?
text = input('Number?␣')
number = float(text)
User input
tolerance = 1.0e-15
uncertainty = upper - lower
"else" is optional
183
“Chained” tests
...
184
“Chained” tests ― syntactic sugar
text = input('Number?␣')
number = float(text)
...
185
sqrt3.py
Without elif…
text = input('Number?␣')
number = float(text)
text = input('Number?␣')
number = float(text)
187
Progress
Nested structures while … :
if … :
Chained tests if … :
…
elif … :
…
Testing inputs to scripts elif … :
…
else:
…
exit() 188
Exercise 9
Only attempt each part after exercise9.py
you have the previous part working!
10 minutes
189
Comments
190
Python comment character
#
a.k.a. “pound”, “number”, “sharp”
191
Python commenting example
#!/usr/bin/python3
$ fubar.py
instead of
$ python3 fubar.py
193
Progress
Comments
“#” character
#
194
Exercise 10
2 minutes
195
Recap: Python types so far
[ -3.141592653589793, -1.5707963267948966,
0.0, 1.5707963267948966, 3.141592653589793 ]
197
What is a list?
hydrogen, helium, lithium, beryllium, …, protactinium, uranium
A literal list
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19] The whole list
>>> type(primes)
<class 'list'> A Python type
200
How Python presents lists
Square brackets
at the ends
201
Square brackets
202
Python counts from zero
“index” 0 1 2 3 4 5 6 7
203
Looking things up in a list
>>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19]
0 1 2 3 4 5 6 7
205
Counting from the end
>>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19]
0 1 2 3 4 5 6 7
-8 -7 -6 -5 -4 -3 -2 -1
int 3 primes[1]
primes
…
int 17 primes[6]
int 19 primes[7]
207
Length of a list
list
>>> len(primes)
8 8
0 len() function:
length of list
primes
Maximum
7
index is 7
208
Changing a value in a list
>>> data = ['alpha', 'beta', 'gamma'] The list
list
3 str 5 a l p h a
str 4 b e t a
str 5 g a m m a
210
Changing a value in a list ― 2
Right to left
>>> data = ['alpha', 'beta', 'gamma']
list
3 str 5 a l p h a
data
str 4 b e t a
str 5 g a m m a
211
Changing a value in a list ― 3
Right to left
>>> data[2] = 'G'
list
3 str 5 a l p h a
data
str 4 b e t a
str 5 g a m m a
list
3 str 5 a l p h a
data
str 4 b e t a
str 5 g a m m a
No longer
str 1 G referenced
213
Changing a value in a list ― 5
Right to left
>>> data[2] = 'G'
list
3 str 5 a l p h a
data
str 4 b e t a
str 1 G
214
Removing an entry from a list ― 1
>>> del data[1]
list
3 str 5 a l p h a data[0]
data
✗ str 4 b e t a data[1]
str 5 g a m m a data[2]
215
Removing an entry from a list ― 2
>>> del data[1]
list
2 str 5 a l p h a data[0]
data
No longer
str 4 b e t a
referenced
str 5 g a m m a data[1]
216
Removing an entry from a list ― 3
>>> del data[1]
list
2 str 5 a l p h a data[0]
data
str 5 g a m m a data[1]
217
Running off the end
list
8 int 2
int 3
primes
…
int 17
int 19
218
primes[8]
Running off the end
>>> len(primes)
8
>>> primes[7]
19
>>> primes[8]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
219
Type of error Description of error
Running off the end
>>> primes[8] = 23
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
220
Progress
index primes[4]
Length len(primes)
Over-running primes[8]
221
Exercise 11
2 >>> numbers[1] = 3
4 >>> numbers[3] = 37
int 2 int 2
… ? …
int 17 int 17
int 19 int 19
The list
A connecting dot
225
“Methods”
Behaves just
like a function
>>> print(primes)
[2, 3, 5, 7, 11, 13, 17, 19]
>>> primes.append(23)
The function doesn’t
return any value.
>>> primes.append(29)
>>> primes.append(31)
It modifies
>>> primes.append(37)
the list itself.
>>> print(primes)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] 227
Other methods on lists: reverse()
>>> numbers.reverse()
The function doesn’t
return any value.
>>> print(numbers)
It modifies
[1, 5, 7, 4]
the list itself.
228
Other methods on lists: sort()
>>> numbers.sort()
The function does not
return the sorted list.
>>> print(numbers)
It sorts the
[1, 4, 5, 7]
list itself.
Numerical order.
229
Other methods on lists: sort()
>>> greek.sort()
>>> print(greek)
Alphabetical order
of the words.
230
Other methods on lists: insert()
0 1 2
>>> greek
0 1
Displaced 231
Other methods on lists: remove()
>>> print(numbers)
[7, 4, 7, 2, 5, 4]
>>> print(numbers)
[7, 4, 7, 2, 5, 4]
There are two instances of 4.
>>> numbers.remove(4)
>>> print(numbers)
[7, 7, 2, 5, 4]
class list(object)
...
| append(...)
| L.append(object) -- append object to end
...
append(...)
L.append(object) -- append object to end
235
Sorting a list redux
>>> print(greek)
236
Sorting a list redux: “sorted()”
>>> primes
238
Concatenation
Create a new list
Augmented assignment
239
Creating lists from text ― 1
str 5 H e l l o str 1 l
str 1 l
str 1 o
240
Creating lists from text ― 2
Built in method
>>> 'Hello, world!'.split()
str 13 H e l l o , ␣ w o r l d !
list
2 str 6 H e l l o ,
str 6 w o r l d !
241
Progress
“Methods” object.method(arguments)
append(item)
reverse()
sort()
insert(index,item)
remove(item)
Help help(object)
help(object.method)
Sorting list.sort()
sorted(list)
Concatenation
+ [1,2,3] + [4,5,6] 242
+= primes += [29, 31]
Exercise 12
5 minutes
243
Is an item in a list? ― 1
✗ x must be in the
list before it can
be removed
244
Is an item in a list? ― 2
>>> odds = [3, 5, 7, 9]
>>> 2 in odds
False
>>> 3 in odds
True
True 245
Precedence
First
x not in y x in y
if number in numbers :
numbers.remove(number)
What’s the
difference?
numbers.remove(number)
247
Working through a list ― 1
The
cat
sat
on
the
mat.
248
Working through a list ― 2
203
249
Working through a list ― 3
[4, 7, -2, 9, 1]
250
The “for loop” ― 1
keywords
252
The “for loop” ― 3
␣␣␣␣print(word)
␣␣␣␣print(word)
for1.py
260
The “for loop” for adding
261
print(total) Results after the loop
The “for loop” for creating a new list
262
print(squares) Results after the loop
The loop variable persists!
numbers = [4, 7, -2, 9, 1]
squares = [ ]
263
“for loop hygeine”
numbers = [4, 7, -2, 9, 1]
squares = [ ]
␣␣␣␣squares.append(number**2)
264
Progress
numbers = [0, 1, 2, 3, 4, 5]
total = 0
total_so_far = []
print(total_so_far) 5 minutes
266
“Sort-of-lists”
Python “magic”:
267
Strings as lists
Recall:
Built in to Python:
range(start,limit)
range(0,5)
[0, 1, 2, 3, 4]
Inefficient to make a
huge list just for this
271
Ranges of numbers again
via list()
range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Start at 0
range(3, 10) [3, 4, 5, 6, 7, 8, 9]
272
Indices of lists
>>> primes = [ 2, 3, 5, 7, 11, 13, 17, 19]
>>> len(primes)
>>> list(range(8))
0 1 2 3 4 5 6 7
274
Working with two lists: “dot product”
∙ × × ×
list2 = [ 0.2, 0.5, 0.6]
275
Working with two lists: indices
0 1 2
list1 = [0.3, 0.0, 0.4]
indices
list2 = [0.2, 0.5, 0.6]
sum = 0.0
sum += list1[index]*list2[index]
Dealing with
print(sum)
values from
both lists at
the same time.276
A little more about iterators ― 1
>>> greek = ['alpha', 'beta', 'gamma', 'delta']
'beta'
str 5 d e l t a
277
A little more about iterators ― 2
iter
>>> next(greek_i) str 5 a l p h a
4
'gamma'
✗ str 4 b e t a
>>> next(greek_i)
str 5 g a m m a
'delta'
str 5 d e l t a
>>> next(greek_i)
range() range(limit)
range(start,limit)
range(start,limit,step)
range(3,7) [3,4,5,6]
279
Parallel lists
Exercise 14
Complete exercise14.py
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29] The list
>>> primes[3]
7 An item
>>> primes[3:9]
[7, 11, 13, 17, 19, 23] Part of the list
281
Slices ― 1
from
Up to but not
to
including…
primes[3:9]
3 9
primes[3:9:3] [7, 17 ]
284
Copies and slices ― 1
list
str 1 a
letters 3
str 1 b
alphabet
str 1 c
285
Copies and slices ― 2
>>> letters[0] = 'A'
>>> print(alphabet)
list
str 1 A
letters 3
str 1 b
alphabet
str 1 c
286
Copies and slices ― 3
>>> letters = ['a','b','c'] Slices are
copies.
>>> alphabet = letters[:]
letters alphabet
list list
str 1 a
3 3
str 1 b
str 1 c 287
Copies and slices ― 4
>>> letters[0] = 'A' Slices are
copies.
>>> print(alphabet)
['a', 'b', 'c'] alphabet
letters
list list
str 1 A str 1 a
3 3
str 1 b
str 1 c 288
Progress
Slices
End-limit excluded
items[from:to] items[from:to:stride]
items[:to] items[:to:stride]
items[from:] items[from::stride]
foo = [4, 6, 2, 7, 3, 1, 9, 4, 2, 7, 4, 6, 0, 2]
bar = foo[3:12:3]
bar[2] += foo[4]
foo[0] = bar[1]
print(bar)
3 minutes
290
Diversion: Lists and strings
list() 5
str 1 e
str 5 H e l l o
str 1 l
str 1 l
str 1 o
291
Indexing into strings
'H'
'Hell'
292
Strings are immutable
293
Files
Input Output
.txt
.dat
.csv
Reading Writing
294
Reading a text file
File name
Read-only [text]
>>> book = open('treasure.txt', 'r') “mode”
Read-only is
the default
book = open('treasure.txt' ) 296
Reading from a file object
File object
>>> line1 = next(book)
299
The file object ― 1
<_io.TextIOWrapper
name='treasure.txt' File name
encoding='UTF-8'>
Character encoding:
how to represent
letters as numbers.
300
The file object ― 2
File name
Text encoding
TREASURE ISLAND↵
“offset”: how far into ↵
the file we have read PART ONE↵
☞ ↵
The Old Buccaneer↵
↵
Pointer to the file
on the file system
301
Reading through a file
Treat it like a list and
it will behave like a list
>>> print(lines)
302
Reading a file moves the offset
>>> book = open('treasure.txt', 'r')
!
>>> lines_a = list(book)
>>> print(lines_a)
… Huge output
>>> print(lines_b)
>>> print(lines_a)
306
Example: lines in a file
book = open('treasure.txt', 'r')
307
book.close()
Example: characters in a file
book = open('treasure.txt', 'r')
n_chars = 0
n_chars += len(line)
308
book.close()
Progress
309
Exercise 16
5 minutes
310
Writing files
Open for
writing [text]
Open for
appending [text]
313
Writing to a file object ― 1
File object
Method built in
to file object
>>> output.write(line1)
Number of
characters
actually written
>>> len(line1)
314
6
Writing to a file object ― 2
>>> output.write('ta\n')
3
>>> output.write('gamma\ndelta\n')
12
Can be multiple lines 315
Closing the file object
316
Importance of closing
!
Data “flushed” to disc on closure.
write “flush”
open ['w']
✗ open ['r']
318
(More a problem for Windows than Unix)
Writing non-text values
✗
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int
write() only accepts text
319
Writing non-text values
5 minutes
322
Functions
y = f(x)
323
Functions we have met
input(prompt) bool(thing)
len(thing) float(thing)
print(line) iter(list)
type(thing) list(thing)
chr(number) str(thing)
Not that many! “The Python Way”:
If it is appropriate to an object,
324
… write
… test
… fix
… improve
… add to
“Structured
programming”
… develop
325
Defining a function
326
A function to define: total()
Sum a list
[1, 2, 3] 6
[7, -4, 1, 6, 0] 10
[] 0 “Edge case”
327
Defining a Python function ― 1
define a function called …
name of function
inputs
def total( … ): colon
328
Defining a Python function ― 2
329
Defining a Python function ― 3
330
Defining a Python function ― 4
def total(numbers):
sum_so_far = 0
331
Defining a Python function ― 4
def total(numbers):
These variables exist only
sum_so_far = 0
within the function’s body.
for number in numbers:
sum_so_far += number
332
Defining a Python function ― 5
def total(numbers):
sum_so_far = 0
sum_so_far = 0
return sum_so_far
Unindented
after this 334
Defining a Python function ― 7
335
Using a Python function ― 1
def total(numbers):
sum_so_far = 0
return sum_so_far
print(total([1, 2, 3]))
The list we
want to add up
336
Using a Python function ― 2
def total(numbers):
sum_so_far = 0
return sum_so_far
print(total([1, 2, 3]))
The function we
have just written
337
Using a Python function ― 3
def total(numbers):
sum_so_far = 0
return sum_so_far
print(total([1, 2, 3]))
Printing out
the answer
338
Using a Python function ― 4
def total(numbers):
nb: Unix prompt
sum_so_far = 0
$ python3 total1.py
for number in numbers:
sum_so_far += number 6
return sum_so_far
print(total([1, 2, 3]))
total1.py
339
Using a Python function ― 5
def total(numbers):
sum_so_far = 0
$ python3 total2.py
for number in numbers:
sum_so_far += number 6
10
return sum_so_far 0
print(total([1, 2, 3]))
print(total([7,-4,1,6,0])) Use the function
print(total([])) multiple times
total2.py
340
Functions’ private names ― 1
def total(numbers):
sum_so_far = 0
return sum_so_far
data = [1, 2, 3]
data_sum = total(data) Main script
print(data_sum)
341
Functions’ private names ― 2
def total(numbers):
...
“namespace”
342
Functions’ private names ― 3
data = [1, 2, 3]
int 1
main script function
total
int 2
list 3
data
int 3 343
Functions’ private names ― 4
... = total(data) def total(numbers):
total
numbers
int 1
main script function
total
int 2
list 3
data
int 3 344
Functions’ private names ― 5
... = total(data) sum_so_far = 0
total
sum_so_far 0
int
numbers
int 1
main script function
total
int 2
list 3
data
int 3 345
Functions’ private names ― 6
... = total(data) return sum_so_far
total
sum_so_far 6
int
numbers
int 1
main script function
total
int 2
list 3
data
int 3 346
Functions’ private names ― 7
data_sum = total(data) return sum_so_far
total
sum_so_far 6
int
numbers
int 1
main script function
total
int 2
list 3
data
int 6
int 1
main script function
total
int 2
list 3
data
Functions
“Structured programming”
$ python3 exercise18.py
6
0
1
5 minutes
350
Reminder about indices
def total(numbers):
sum_so_far = 0
for number in numbers:
sum_so_far += number total2.py
return sum_so_far
Equivalent
def total(numbers):
sum_so_far = 0
for index in range(len(numbers)):
sum_so_far += numbers[index] total3.py
return sum_so_far
351
Example of multiple inputs
Want a function to add two lists of the same length term-by-term:
Two inputs
352
Functions with multiple inputs
Multiple inputs are
separated by commas
def add_lists(a_list, b_list):
sum_list = []
sum_list.append(sum)
return sum_list
353
Functions with multiple inputs
We have
two lists…
def add_lists(a_list, b_list):
sum_list.append(sum)
return sum_list
354
Multiple outputs
Write a function to find minimum and maximum value in a list
[1, 2, 3] 1 & 3
[3, 7, 4, 1, 7] 1 & 7
Two outputs
355
Finding just the minimum
def min_list(a_list): minlist.py
for a in a_list :
if a < min_so_far:
min_so_far = a
356
Finding just the maximum
def max_list(a_list): maxlist.py
max_so_far = a_list[0]
for a in a_list :
357
Finding both
def minmax_list(a_list):
min_so_far = a_list[0]
max_so_far = a_list[0]
for a in a_list :
if a < min_so_far:
min_so_far = a
if a > max_so_far:
max_so_far = a
358
return what? This is the real question
Returning both
def minmax_list(a_list): minmaxlist.py
min_so_far = a_list[0]
max_so_far = a_list[0]
for a in a_list :
if a < min_so_far:
min_so_far = a
if a > max_so_far:
max_so_far = a
359
return min_so_far, max_so_far A pair of values
“Tuples”
Commas
(min_value, max_value)
360
Using tuples to return values
def … In the function definition
361
Using tuples to attach names
alpha = 12
(alpha, beta) = ( 12, 56 )
beta = 56
362
Swapping values
>>> alpha = 12
>>> beta = 56
>>> print(alpha)
56
>>> print(beta)
12 363
Assignment works right to left
alpha = 12
beta = 56
364
Progress
“Tuples” (a, b, c)
365
Exercise 19
10 minutes
366
Tuples and lists: similarities
368
Tuples and lists: philosophy
Lists Tuples
Sequential: Simultaneous:
Concept of “next item” All items “at once”
Serial Parallel
total(list)
add_lists(list1,list2)
minmax_list(list)
370
Reusing functions within a script
def square(limit):
... One definition
...
squares_a = square(34)
...
squares_b = squares(56)
...
Easy! 371
Reusing functions between scripts?
def squares(limit):
... One definition
...
squares_a = squares(34)
Multiple uses in
...
... multiple files
five_squares = squares(5)
... ...
squares_b = squares(56)
...
How? 372
“Modules”
Definition Use
def total(numbers):
Starts empty sum_so_far = 0
for number in numbers:
sum_so_far += number
return sum_so_far
$ python3 sum_squares.py
Number? 5
30 = 0 + 1 + 4 + 9 + 16
$ python3 sum_squares.py
Number? 7
91 = 0 + 1 + 4 + 9 + 16 + 25 + 36
375
Modules: a worked example ― 2a
def squares(limit):
answer = []
for n in range(0,limit):
answer.append(n**2) text = input('Number? ')
return answer number = int(text)
squares_n = squares(number)
def total(numbers): total_n = total(squares_n)
sum_so_far = 0 print(total_n)
for number in numbers:
sum_so_far += number
return sum_so_far
sum_squares.py
utils.py
Move the definitions
into the other file.
376
Modules: a worked example ― 2b
$ python3 sum_squares.py
Number? 5
377
Modules: a worked example ― 3a
def squares(limit): import utils
answer = []
for n in range(0,limit):
answer.append(n**2) text = input('Number? ')
return answer number = int(text)
squares_n = squares(number)
def total(numbers): total_n = total(squares_n)
sum_so_far = 0 print(total_n)
for number in numbers:
sum_so_far += number
return sum_so_far
sum_squares.py
utils.py
import: Make
import utils a reference to
and not the other file.
378
import utils.py
Modules: a worked example ― 3b
$ python3 sum_squares.py
Number? 5
379
Modules: a worked example ― 4a
import utils
utils.total()
sum_squares.py
utils.…: Identify
the functions
as coming from
380
the module.
Modules: a worked example ― 4b
$ python3 sum_squares.py
Number? 5
30
$ python3 sum_squares.py
Number? 7
91
Working again!
☺
381
Progress
“Modules”
382
Exercise 20
5 minutes
383
The Python philosophy
A small core … plus lots
language … of modules
math
sys
“Batteries
included”
string 384
Example: the “math” module
385
import module as alias
1.4142135623730951
>>> m.sqrt(2.0)
1.4142135623730951 386
Don’t do these
!
Much better
>>> sqrt(2.0) to track the
module.
1.4142135623730951
>>> sqrt(2.0)
!!
1.4142135623730951
387
What system modules are there?
Python 3.2.3 comes with over 250 modules.
>>> help('modules')
numpy pyodbc
MySQLdb MySQL
cx_oracle Oracle
390
An example system module: sys
import sys $ python3 argv.py one two three
print(sys.argv)
['argv.py', 'one', 'two', 'three']
index 0 1 2 3
argv.py
$ python3 argv.py 1 2 3
Always strings
391
sys.exit()
0: Everything was OK
“How do I do
X in Python?”
“Where do I find
Python modules?”
394
Finding modules
>>> help(math)
NAME
math
DESCRIPTION
This module is always available. It provides
access to the mathematical functions defined
by the C standard.
… 396
Help with module functions
…
FUNCTIONS
acos(x)
Return the arc cosine (measured in
radians) of x.
…
>>> math.acos(1.0)
0.0
397
Help with module constants
…
DATA
e = 2.718281828459045
pi = 3.141592653589793
…
>>> math.pi
3.141592653589793
398
Help for our own modules?
def squares(limit): >>> import utils
answer = []
for n in range(0,limit):
answer.append(n**2)
>>> help(utils)
return answer
NAME
def total(numbers): utils
sum_so_far = 0
for number in numbers:
sum_so_far += number FUNCTIONS
return sum_so_far squares(limit)
total(numbers)
utils.py
Basic help already FILE
provided by Python /home/y550/utils.py
399
Adding extra help text
"""Some utility functions >>> import utils Fresh start
from the Python for
Absolute Beginners course
"""
>>> help(utils)
utils.py total(numbers)
Adding extra help text to functions
"""Some utility functions >>> import utils Fresh start
from the Python for
Absolute Beginners course
"""
>>> help(utils)
utils.py
Adding extra help text to functions
"""Some utility functions >>> import utils Fresh start
from the Python for
Absolute Beginners course
"""
>>> help(utils.squares)
402
utils.py
Progress
Python a small language… Functionality Module
System modules
Foreign modules
5 minutes
404
Recap: Lists & Indices
list
str 5 a l p h a greek[0]
3
405
“Index in ― Value out”
Must be
a number
1 greek[1] 'beta'
406
Other “indices”: Strings?
'cat' 'gato'
'mouse' 'ratón'
407
Other “indices”: Tuples?
(2,5) 'Treasure'
dictionary
(4,5) 'Fortress'
408
Python “dictionaries”
>>> en_to_es['cat']
'gato'
409
Creating a dictionary — 1
Curly brackets
Comma
{ 'cat':'gato' , 'dog':'perro' }
410
Creating a dictionary — 2
'cat' : 'gato'
{ 'cat':'gato' , 'dog':'perro' }
“key” : “value”
411
Using a dictionary — 1
'gato'
412
Using a dictionary — 2
Square brackets
413
Missing keys
✓
>>> en_to_es['dog']
'perro'
✗
>>> en_to_es['mouse']
✓
>>> en_to_es['dog']
'perro'
✗
>>> en_to_es['perro']
>>> en_to_es['mouse']
'ratón'
416
Removing from a dictionary
>>> print(en_to_es)
>>> print(en_to_es)
417
Progress
cat chat
dog chien
mouse souris
snake serpent
5 minutes
419
What’s in a dictionary? ― 1
>>> en_to_es
{'mouse': 'ratón', 'dog': 'perro', 'cat': 'gato'}
>>> en_to_es.keys()
dict_keys(['mouse', 'dog', 'cat'])
Orders
match
>>> en_to_es.values()
dict_values(['ratón', 'perro', 'gato'])
Just treat them like lists (or convert them to lists) 420
What’s in a dictionary? ― 2
>>> en_to_es.items() Most useful method
dict_items([('mouse', 'ratón'), ('dog', 'perro'),
('cat', 'gato')])
(Key,Value) pairs/tuples
>>> list(en_to_es.items())
[('mouse','ratón'), ('dog','perro'),('cat','gato')]
422
Getting the list of keys
list() list of
dictionary
keys
{'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
423
Is a key in a dictionary?
>>> en_to_es['snake']
424
Example: Counting words ― 1
words = ['the','cat','sat','on','the','mat']
counts = {'the':2,'cat':1,'sat':1,'on':1,'mat':1}
425
Example: Counting words ― 2
words = ['the','cat','sat','on','the','mat']
Do something
426
Example: Counting words ― 3
words = ['the','cat','sat','on','the','mat']
counts = {}
counter1.py
427
Why doesn’t it work?
counts = {'the':1, 'cat':1}
counts['the'] = counts['the'] + 1
Key is not in
✗
counts['sat'] += 1
the dictionary!
counts['sat'] = counts['sat'] + 1
428
Example: Counting words ― 4
words = ['the','cat','sat','on','the','mat']
counts = {}
if word in counts:
counts[word] += 1
else:
words = ['the','cat','sat','on','the','mat']
counts = {}
if word in counts:
counts[word] += 1
else:
counts[word] = 1 counter2.py
430
print(counts)
Example: Counting words ― 6
$ python3 counter2.py
✗
print(counts) Too ugly
items.sort()
$ python3 counter3.py
cat 1
mat 1
on 1
sat 1
the 2
433
Progress
434
Exercise 23
5 minutes
435
Formatted output
$ python3 counter3.py
cat 1
mat 1
on 1 Ugly!
sat 1
the 2
cat 1
mat 1
on 1 We want data
nicely aligned
sat 1
the 2
436
The format() method
'xxxAyyy100zzz'
'xxx{}yyy{}zzz'
'xxxAyyy100zzz'
437
String formatting ― 1
>>> 'xxx{:5s}yyy'.format('A')
'xxxA␣␣␣␣yyy'
5 ― pad to 5 spaces
(left aligns by default) 438
String formatting ― 2
>>> 'xxx{:<5s}yyy'.format('A')
'xxxA␣␣␣␣yyy'
439
String formatting ― 3
>>> 'xxx{:>5s}yyy'.format('A')
'xxx␣␣␣␣Ayyy'
440
Integer formatting ― 1
>>> 'xxx{:5d}yyy'.format(123)
'xxx␣␣123yyy'
>>> 'xxx{:>5d}yyy'.format(123)
'xxx␣␣123yyy'
>>> 'xxx{:>5d}yyy'.format(123)
'xxx␣␣123yyy'
>>> 'xxx{:05d}yyy'.format(123)
'xxx00123yyy'
>>> 'xxx{:+5d}yyy'.format(123)
'xxx␣+123yyy'
>>> 'xxx{:+05d}yyy'.format(123)
'xxx␣+0123yyy'
446
Integer formatting ― 7
>>> 'xxx{:5,d}yyy'.format(1234)
'xxx1,234yyy'
>>> 'xxx{:5.2f}yyy'.format(1.2)
'xxx 1.20yyy'
>>> 'xxx{:f}yyy'.format(1.2)
'xxx1.200000yyy'
$ python3 counter4.py
cat 1
mat 1
on 1
sat 1
the 2 452
Progress
Formatting string.format(args)
Substitutions {:>6s}
{:+06d}
{:+012.7f}
453
Exercise 24
Complete exercise24.py
to format the output as shown:
Joe 9
Samantha 45
Methuselah 969
5 minutes
454
And that's it! (And “it” is a lot!)
Text “if” test Reading files
Prompting Indented blocks Writing files
Numbers Lists Functions
Arithmetic Indices “Structured programming”
Comparisons Object methods Tuples
Booleans Built-in help “for” loops
Variables “for” loops Modules
Deleting names “Treat it like a list…” Dictionaries
“while” loop Values direct/via index Formatting
455
But wait! There’s more…
456
Congratulations!
Text “if” test Reading files
Prompting Indented blocks Writing files
Numbers Lists Functions
Arithmetic Indices “Structured programming”
Comparisons Object methods Tuples
Booleans Built-in help “for” loops
Variables “for” loops Modules
Deleting names “Treat it like a list…” Dictionaries
“while” loop Values direct/via index Formatting
457
Please don’t forget the feedback.