An Introduction To Python For Absolute Beginners
An Introduction To Python For Absolute Beginners
http://www.ucs.cam.ac.uk/docs/course-notes/unix-courses/PythonAB
1
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
2
Course outline ― 2
Assignment
Names
Loops
if… else…
Indentation
Comments
3
Course outline ― 3
Lists
Indices
Lengths
Changing items
Extending lists
Methods
Creating lists
Testing lists
Removing from lists
for… loop
Iterables
Slices
4
Course outline ― 4
Files
Reading & writing
Tuples
Modules
System modules
External modules
Dictionaries
Formatted text
5
Who uses Python?
On-line games
Web services
Applications
Science
Instrument control
Embedded systems
en.wikipedia.org/wiki/List_of_Python_software
6
What sort of language is Python?
Compiled Interpreted
7
Running Python ― 1
8
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
9
Quitting Python
>>> exit()
>>> Ctrl + D
10
A first Python command
Python prompt
Python command
11
Python commands
Python “function”
Round brackets
― “parentheses”
print('Hello, world!')
Function’s “argument”
12
Python text
Quotation marks
'Hello, world!'
The body
of the text
13
!
Quotes?
print Command
'print' Text
14
Python scripts
File in home directory print('Hello, world!')
Unix prompt
Unix command
to run Python
$ Unix prompt
15
Editing Python scripts — 1
Use either
gedit or
Sublime text.
16
Editing Python scripts — 2
Use either
gedit or
Sublime text.
17
Progress
Interactive Python
Python scripts
print() command
18
Exercise 1
2 minutes
19
A little more text
www.unicode.org/charts/ hello2.py
20
Getting characters
˘
ğ Character Selector
“LATIN SMALL
LETTER G \u011f
WITH BREVE”
21
Text: a “string” of characters
>>> type('Hello, world!')
Class: string
Length: 13
Letters
str 13 H e l l o ,␣w o r l d !
22
Text: “behind the scenes”
str 13 72 101 108 108 111 44 32 … 100 33
>>> ord('ğ')
287
28710
>>> chr(287)
'ğ'
23
ğ
Adding strings together: +
hello3.py
>>> 'Hello, ' + 'world!'
'Hello, world!'
>>>
24
Pure concatenation
>>> 'Hello,␣' + 'world!'
'Hello, world!'
25
Single & double quotes
26
Python strings: input & output
'Hello, world!'
Single or double
"Hello, world!" quotes on input.
Create same
string object.
str 13 H e l l o ,␣w o r l d !
27
Uses of single & double quotes
28
Why we need different quotes
✘
File "<stdin>", line 1
print('He said 'hello' to her.')
^
SyntaxError: invalid syntax
29
Adding arbitrary quotes
>>> print('He said \'hello\' to her.')
>>> print('Hello, ↵
✘
File "<stdin>", line 1
print('Hello,
^
SyntaxError: EOL while
scanning string literal “EOL”: End Of Line
31
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
32
the length of the object
The backslash
Special Ordinary \' '
\" "
Ordinary Special \n ↵
\t ⇥
33
\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
34
line
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
35
lines
Python’s “secondary” prompt
>>> '''Hello,
... world'''
Python asking for more
of the same command.
36
It’s still just text!
>>> 'Hello,\nworld!'
'Hello\nworld'
Python uses \n to represent
line breaks in strings.
>>> '''Hello,
... world!'''
37
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 !
38
Progress
International text
print()
Concatenation of strings
Special characters
Long strings
39
Attaching names to values
“variables” message = 'Hello, world!'
print(message)
>>> message='Hello, world!'
'Hello, world!'
>>> type(message)
<class 'str'>
message str 13 H e l l o , ␣w o r l d !
41
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 !
42
Reading some text into a script
message = input('Yes?␣')
print(message)
input('Yes?␣')
Boo! print(message)
43
Can't read numbers directly!
$ python3 input2.py number = input('N?␣')
print(number + 1) ✘
N? 10
input2.py
string integer
44
input(): strings only
$ python3 input2.py number = input('N?␣')
print(number + 1) ✘
N? 10
input2.py
input('N?␣') str 2 1 0
≠ int 10
45
Some more types
>>> type('Hello, world!')
>>> 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'
47
Converting text to floats
>>> float('10.0') '10.0' is a string
>>> float('␣10.␣')
10.0
48
Converting between ints and
floats
>>> float(10)
10.0
>>> int(10.9)
10 Truncates
fractional part
>>> int(-10.9)
-10
49
Converting into text
>>> str(10) integer string
'10'
'10.0'
50
Converting between types
int() anything integer
51
Reading numbers into a script
text = input('N?␣')
number = int(text)
$ python3 input3.py print(number + 1)
N? 10
11
52
Stepping through our script — 1
text = input('N?␣')
str 3 N ? ␣ number = int(text)
print(number + 1)
53
Stepping through our script — 2
text = input('N?␣')
str 3 N ? ␣ number = int(text)
print(number + 1)
input function
54
Stepping through our script — 3
text = input('N?␣')
number = int(text)
print(number + 1)
input function
text str 2 1 0
55
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
56
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
57
Stepping through our script — 6
text = input('N?␣')
number = int(text)
print(number + 1)
number int 10
58
Stepping through our script — 7
text = input('N?␣')
number = int(text)
print(number + 1)
+ function
int 11
59
Stepping through our script — 6
text = input('N?␣')
number = int(text)
print(number + 1)
number int 10
int 11
print function
60
Progress
Names Values name = value
Types strings
integers
61
Exercise 3
3 minutes
62
Integers
ℤ {… -2, -1, 0,
1, 2, 3, 4 …}
63
Integer addition & subtraction
>>> 20+5
25
“No surprises”
64
Integer multiplication
There is no “×” on the keyboard. Linux:
AltGr + Shift + ,
Use “*” instead
>>> 20␣*␣5
100
Still no surprises
65
Integer division
There is no “÷” on the keyboard. Linux:
AltGr + Shift + .
Use “/” instead
>>> 20␣/␣5
4.0 This is a floating point number!
Surprise!
66
Integer division gives floats !
Fractions Floats sometimes
!
Consistency Floats always
>>> 20␣/␣40
0.5
>>> 20␣/␣30
0.6666666666666666
67
Integer powers
There is no “42” on the keyboard.
68
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
69
How big can a Python integer be?
>>> 2**2
4
>>> 4**2
16
>>> 16**2
256
>>> 256**2
65536
>>> 65536**2
4294967296
70
How big can a Python integer be?
>>> 4294967296**2
18446744073709551616
>>> 18446744073709551616**2
340282366920938463463374607431768211456
>>> 340282366920938463463374607431768211456**2
1157920892373161954235709850086879078532699846
65640564039457584007913129639936
>>> 115792089237316195423570985008687907853269
984665640564039457584007913129639936**2
1340780792994259709957402499820584612747936582
0592393377723561443721764030073546976801874298
1669034276900318581864860508537538828119465699
46433649006084096
71
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
72
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
74
2.71828182
Basic operations
>>> 20.0 + 5.0 >>> 20.0 - 5.0
25.0 15.0
75
Floating point imprecision
>>> 1.0 / 3.0
0.3333333333333333
≈ 17 significant figures
76
Hidden imprecision
>>> 0.1
!
0.1
1.8446744073709552 e+19
1.8446744073709552 ×1019
78
Floats are not exact
>>> 4294967296.0**2 Floating point
1.8446744073709552e+19
1.8446744073709552×1019 18446744073709552000
- 18446744073709551616
384
79
How big can a Python float be? ―
2
>>> 1.8446744073709552e+19**2
3.402823669209385e+38
>>> 3.402823669209385e+38**2
1.157920892373162e+77
80
Floating point limits
1.2345678901234567 × 10N
17 significant figures
Positive values:
4.94065645841×10-324 < N < 8.98846567431×10307
81
Complex numbers
ℑ
ℂ
z2
z
ℜ
>>> (1.25+0.5j)**2
(1.3125+1.25j)
82
Progress
Arithmetic + - * / ** %
Integers No limits!
Limited precision
Complex numbers
83
Exercise 4
1. 223 ÷ 71
2. (1 + 1/10)10
3. (1 + 1/100)100
4. (1 + 1/1000)1000
3 minutes
84
Comparisons
5 < 10 ✔
5 > 10 ✘
85
Comparisons
>>> 5 < 10 Asking the question
True
✔
>>> 5 > 10 Asking the question
False
✘
86
True & False
>>> type(True)
<class 'bool'> “Booleans”
5 + 10 15 int
int int
87
True & False
bool ✓ True
Only two values
bool ✗ False
88
Six comparisons
Maths Python
≠ !=
< <
> >
≤ <=
≥ >=
89
Equality comparison &
assignment
= name = value
==
value1 == value2
90
Textual comparisons
>>> 'cat' < 'dog' Alphabetic ordering
True
True
True
91
Ordering text is complicated
Python inequalities use Unicode character numbers.
Alphabetical order?
German: z<ö
Swedish: ö<z
92
“Syntactic sugar”
0 < number
number < 10
>>> number = 5
True
93
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
-1
95
True
Boolean operations
bool
? bool
bool
96
Boolean operations ― “and”
bool
and bool
bool
98
Boolean operations ― “or”
bool
or bool
bool
100
Boolean operations ― “not”
101
Boolean operations ― “not”
>>> not 6 < 7 6 < 7 True not False
False
True
102
Ambiguity in expressions
3+6/3
✘ ✔
(3 + 6) / 3 3 + (6 / 3)
3 5
103
Division before addition
3 +6/3
Division first
3+ 2
Addition second
5
104
“Order of precedence”
First
not x x and y x or y
105 Last
Progress
Comparisons == != < > <= >=
106
other True
Exercise 5
Predict whether these expressions will evaluate to True or False.
Then try them.
3. 60 - 45 / 5 + 10 == 1
3 minutes
107
Names and values: “assignment”
>>> alpha = 100
109
Simple evaluations
>>> beta = 100 + 20
1. 100 + 20 RHS
2.
int 120
3. LHS
beta int 120
110
Changing value — 1
>>> gamma = 1
>>> gamma = 2
111
Changing value — 2 RHS
>>> gamma = 1
int 1
112
Changing value — 3 LHS
>>> gamma = 1
gamma int 1
113
Changing value — 4 RHS
>>> gamma = 1
gamma int 1
>>> gamma = 2
int 2
114
Changing value — 5 LHS
>>> gamma = 1
gamma int 1
>>> gamma = 2
int 2
115
Changing value — 6
garbage collection
✘
>>> gamma = 1
gamma int 1
>>> gamma = 2
int 2
116
Changing value — 7
>>> gamma = 1
gamma
>>> gamma = 2
int 2
117
Changing value — a subtlety
✘
>>> gamma = 1
gamma int 1
>>> gamma = 2
118
Names on the RHS — 1
>>> delta = alpha + 40
alpha + 40 RHS
1.
alpha
2.
3.
int 140
119
Names on the RHS — 2
>>> delta = alpha + 40
LHS
4. delta int 140
120
Same name on both sides — 0
Starting
delta int 140 position
>>> print(delta)
140
121
Same name on both sides — 1
RHS
>>> delta = delta + 10
1. delta + 10
2. delta
4. int 150
122
Same name on both sides — 2
LHS
>>> delta = delta + 10
123
Same name on both sides — 3
LHS
>>> delta = delta + 10
int 150
✗
7.
delta int 140 No longer
used.
124
“Syntactic sugar”
thing += 10 thing = thing + 10
125
Deleting a name ― 1
>>> print(thing)
>>> print(thing)
1
126
Deleting a name ― 2
>>> print(thing)
1 Known
variable
>>> del thing
>>> print(thing)
128