...........................................................................................................................................I
..................................................................................................................................................... V
.................................................................................................................................................. VII
1 .......................................................................................................................................1
1.1 Python ...............................................................................................................1
1.2 ....................................................................................................................3
1.3 ....................................................................................................................3
1.4 Syntax errors...............................................................................................4
1.5 Runtime errors ............................................................................................4
1.6 Semantic errors...........................................................................................4
1.7 ........................................................................................................................4
1.8 ........................................................................................................5
1.9 ........................................................................................................................7
1.10
.................................................................................................................................7
1.11 ....................................................................................................................................9
2 ................................................................................................................. 11
2.1 ...................................................................................................................... 11
2.2 ..................................................................................................................................12
2.3 ..........................................................................................................13
2.4 ..................................................................................................................................14
2.5 ......................................................................................................................14
2.6 ..............................................................................................................15
2.7 ......................................................................................................................16
2.8 ..................................................................................................................16
2.9 ..................................................................................................................................17
2.10
...............................................................................................................................17
2.11 ..................................................................................................................................18
2.12
...............................................................................................................................18
2.13
...............................................................................................................................20
3 .............................................................................................................................................22
3.1 ..............................................................................................................22
3.2 ..........................................................................................................................24
3.3 import ..................................................................................24
3.4 ..................................................................................................................................26
3.5 ..............................................................................................26
3.6 ..............................................................................................................................27
3.7 ..................................................................................................................................28
3.8 ..................................................................................................................................30
4 .........................................................................................................................................32
4.1 ......................................................................................................................32
4.2 ..............................................................................................................32
4.3 ......................................................................................................................33
4.4 ..........................................................................................................................33
-2-
7
7
4.5 ..........................................................................................................................34
4.6 ......................................................................................................................35
4.7 ......................................................................................................................35
4.8 return .......................................................................................................................36
4.9 ..........................................................................................................................36
4.10
.......................................................................................................................37
4.11 Gasp..................................................................................................................................39
4.12
...............................................................................................................................40
4.13
...............................................................................................................................41
.....................................................................................................................................46
5.1 ..............................................................................................................................46
5.2 ..........................................................................................................................47
5.3 ......................................................................................................................49
5.4 ..........................................................................................................................50
5.5 function.....................................................................................................50
5.6 ..............................................................................................................51
5.7 ..................................................................................................................52
5.8 doctest ................................................................................................52
5.9 ..................................................................................................................................54
5.10
...............................................................................................................................55
.............................................................................................................................................60
6.1 ..........................................................................................................................60
6.2 ..........................................................................................................................60
6.3 while .......................................................................................................................61
6.4 ..................................................................................................................62
6.5 ..........................................................................................................................63
6.6 ..........................................................................................................................64
6.7 ..................................................................................................................................65
6.8 ..........................................................................................................................66
6.9 ..................................................................................................................66
6.10
...................................................................................................................67
6.11 ..........................................................................................................................68
6.12
...............................................................................................................68
6.13
...............................................................................................................................70
6.14
...................................................................................................................70
6.15
...............................................................................................................................70
6.16
...............................................................................................................................71
6.17
...............................................................................................................................72
doctests 7. ...................................................................75
7. ....................................................................................................................................76
7.1 ..................................................................................................................76
7.2 ..................................................................................................................................76
7.3 for ........................................................................................................77
7.4 ......................................................................................................................78
7.5 ......................................................................................................................79
7.6 ..........................................................................................................79
-3-
7.7 in ........................................................................................................................79
7.8 A find ....................................................................................................................80
7.9 ......................................................................................................................81
7.10
...................................................................................................................81
7.11 string .......................................................................................................................82
7.12
...................................................................................................................83
7.13
...............................................................................................................84
7.14
...............................................................................................................................86
7.15
...............................................................................................................................87
8 Catch .....................................................................................................................91
8.1 ..................................................................................................................................91
8.2 while ............................................................................................................91
8.3 ......................................................................................................................92
8.4 ..........................................................................................................................93
8.5 break .......................................................................................................................93
8.6 ..........................................................................................................................94
8.7 ..........................................................................................................................95
8.8 ..................................................................................................................96
8.9 ..........................................................................................................................97
8.10
...........................................................................................................................98
8.11 ................................................................................................................................101
8.12
.............................................................................................................................102
8.13
pong.py..........................................................................................................102
9 Tuple .........................................................................................................................................104
9.1 tuple ..............................................................................................................104
9.2 Tuple .....................................................................................................................105
9.3 Tuple .........................................................................................................106
9.4 ........................................................................................................................106
9.5 ................................................................................................................107
9.6 ................................................................................................................................108
9.7 ........................................................................................................................109
9.8 .................................................................................................... 111
9.9 ................................................................................................................................ 112
10
....................................................................................................................................... 114
11
........................................................................................................................... 115
11.1 ........................................................................................................................ 117
11.2 ........................................................................................................................ 119
11.3 ................................................................................................................................121
11.4 ................................................................................................................................122
11.5 ................................................................................................................................123
11.6 ................................................................................................................................126
12
...........................................................................................................................128
12.1
.............................................................................................128
12.2
.............................................................................................................................129
12.3
.....................................................................................................130
12.4
.........................................................................................................................130
-4-
12.5
.............................................................................................................................132
12.6
.....................................................................................................133
12.7
.............................................................................................................133
12.8
.............................................................................................................................134
12.9
.............................................................................................................................136
13
...........................................................................................................................137
13.1 Time ......................................................................................................................137
13.2
.........................................................................................................................137
13.3
.........................................................................................................................139
13.4
.........................................................................................................141
13.5
V.S. ..................................................................................................141
13.6
.........................................................................................................................142
13.7
.............................................................................................................................143
13.8
.............................................................................................................................143
14
...........................................................................................................................145
14.1
.............................................................................................................145
14.2 printTime ......................................................................................................................145
14.3
.................................................................................................................147
14.4
.................................................................................................148
14.5
.............................................................................................................149
14.6
.................................................................................................................150
14.7
Points.........................................................................................................152
14.8
.................................................................................................................153
14.9
Polymorphism .............................................................................................154
14.10 .............................................................................................................................156
-5-
free speech
free pizza GNU Free
Documentation License
jeff@elkner.net
0.1.1
Jeff 2007 - 2008 HB-Woodlawn
James CrowleyJoshua EddyEric LarsonBrian McGrail Iliana Vazuka
beta
Ammar Nabulsi
Aldric Giacomoni
Roger Sperberg
-I-
Ben Bruno
Carl LaCombe commutative symmetric
Alessandro Montanile
Emanuele Rusconi
Michael Vogt shell vs. script
0.1.2
Lloyd Hugh Allen 8.4
Yvon Boulianne
Fred Bremmer 2.1
Jonah Cohen Perl LaTeX HTML
Michael Conlon
Lee Harr
James Kaylin
David Kershaw 3.10 catTwice
Eddie Lam Makefile
Ian Thomas
Keith Verheyden
Peter Winstanley
Chris Wrobel I/O
Moshe Zadka Dictionaries
James Mayer
Hayden McAfee
Angel Arnal
David Hutchins
Gregor Lingl Python
Julie Peters
0.1.3
2008
- IV -
David Beazley
Python
Python Guido van Rossum
Python ABC 1980
Python C++Java
Modula-3 Scheme Python
Python Python
Python ---
C++ Java Python
Python Python
Python
Python Python
-V-
Jeffrey Python
Python
C++
Python
Python
- VI -
By Jeffrey Elkner
---
---
Richard Stallman
Python
1999 Advanced Placement Computer
Science C++
Pascal
C++
C++
C++
GNU/Linux
Windows Macintosh
Python
Matt Ahrens Python
pyTicket
- VII -
Python
GNU
Python
Allen Java
Allen
---
---
- VIII -
Python
Python
Python
Hello, world C++
#include <iostream.h>
void main()
{
cout << "Hello, world." << endl;
}
Python
print "Hello, World!"
Python
C++
#includevoid
main(){ }
Python
Python C++
- IX -
Python
Python
Python def
def
Python C++
http://openbookproject.net/pyBiblio
Python
jeff@elkner.net
Jeffrey Elkner
-X-
1.1
Python
PythonPython
C++PHP Java
-1-
Python
firstprogram.py
print 1 + 1
Python .py
$ python firstprogram.py
2
Python Unix
-2-
Python shell
Python
shell
1.2
1.3
-3-
1.4
Syntax errors
Python
1.5
Runtime errors
1.6
Semantic errors
1.7
-4-
Linux Linus
Torvalds Intel 80386 Larry Greenfield Linus
AAAA BBBB LinuxThe
Linux Users' Guide Beta Version 1
1.8
3+3=6 3=+6$
H2O 2Zz
3=+6$ $
2Zz Zz
-5-
---3=+6$
------
-6-
1.9
Hello, World!
Hello, World!
Hello, World!
Python
1.10
algorithm
bug
byte code
compile
debugging
exception
-7-
executable
formal language
high-level language
Python
interpret
low-level language
natural language
object code
parse
portability
program
Python shell
Python Python shell >>>
return
runtime error
-8-
script
semantic error
semantics
source code
syntax
syntax error
token
1.11
1.
3. 1 2 return Python
Python
File "<stdin>", line 1
1 2
^
SyntaxError: invalid syntax
Python
Python
-9-
Python
Python
print '"hello"'
5. print cheese
Traceback (most recent call last):
File "<stdin>", line 1, in ?NameError: name 'cheese' is not defined
NameError
cheese
6. Python 'This is a test...' enter
test1.py Python
'This is a test...'
Python Python
'This is a test...' 'This is a test...'
42 42
- 10 -
2.1
2 (1 + 1 ) "Hello, World!"
2 "Hello, World!"
print
>>> print 4
4
>>> type(3.2)
<type 'float'>
"17" "3.2"
>>> type("17")
<type 'str'>
>>> type("3.2")
<type 'str'>
Python '"
>>> type('This is a string.')
<type 'str'>
>>> type("And so is this.")
<type 'str'>
- 11 -
"Bruce's beard"
'The knights who say "Ni!"'
1,000,000 Python
2.2
>>> 17 = n
print
>>> print message
What's up, Doc?>>> print n
17
>>> print pi
3.14159
- 12 -
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>
2.3
Bruce bruce
_ my_name
price_of_tea_in_china
Python 31
and
del
from
as
elif
global or
with
assert
else
if
yield
break
class
exec
in
continue finally is
not
pass
while
raise
return
- 13 -
def
for
lambda try
Python
2.4
Python print
Python Print
print 1
x = 2
print x
1
2
2.5
>>> 1 + 1
2
>>> 17
17
>>> x
2
17
3.2
"Hello, World!"
1 + 1
2.6
Python
20+32
hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)
+ - / () Python
* **
>>> minute = 59
>>> minute/60
0
minute 5959 60 0.98333 0
Python
>>> minute*100/60
98
- 15 -
2.7
Python
PEMDAS
1. Parentheses
2 * (3-1) 4(1+1)**(5-2)
8 (minute * 100) / 60
2.8
message
message-1 "Hello"/123
message*"Hello"
"15"+2
+
+
fruit = "banana"
baked_good = " nut bread"
print fruit + baked_good
banana nut bread nut
- 16 -
* 'Fun'*3
'FunFunFun'
+ * 4*3 4+4+4
"Fun"*3 "Fun"+"Fun"+"Fun"
2.9
Python
n = raw_input(" ")
print n
n = input("")
print n
$ python tryinput.py
7 * 3
21
2.10
------
>>>
20
print 17 + 3
print
print "", hour*60+minute
- 17 -
minute+1 = hour
2.11
comment #
#
percentage = (minute * 100) / 60
2.12
value
type
intfloatstring
int
Python
str
Python
float
- 18 -
Python
baseexponent
variable:
assignment statement
=
Python
n = n + 1
n = n
Python
assignment operator
Python =
state diagram
variable name
Python azAZ _0
9
keyword
ifdef while
statement
Python print
expression
evaluate
operator
operand
- 19 -
integer division
rules of precedence
concatenate
composition
comment
2.13
1.
>>> print n = 7
>>> print 7 + 5
>>> x = input()
3.14
>>> type(x)
- 20 -
>>> x = raw_input()
3.14
>>> type(x)
>>> x = input()
'The knights who say "ni!"'
>>> x
>>> x = input()
The knights who say "ni!"
>>> x
>>> x = raw_input()
'The knights who say "ni!"'
>>> x
6. Python bruce + 4
NameError: name 'bruce' is not defined
bruce bruce + 4 10
7. madlib.py Python
http://madlibs.org
- 21 -
3.1
Python
def NAME( LIST OF PARAMETERS ):
STATEMENTS
Python
LIST OF PARAMETERS
def
1.
2. Python - Python
def
def new_line():
print
# print
new_line
print
arguments
First line.
Second line.
new_line
three_lines
new_line
1.
2.
three_lines
tryme1.py
def new_line():
print
def three_lines():
- 23 -
new_line()
new_line()
new_line()
print "First Line."
three_lines()
print "Second Line."
new_line three_lines
3.2
Python
3.3
import
Python
- 24 -
>>> abs(5)
5
>>> abs(-5)
5
abs 5 -5
pow
>>> pow(2, 3)
8
>>> pow(7, 4)
2401
max
>>> max(7, 11)
11
>>> max(4, 1, 17, 2, 12)
17
>>> max(3*11, 5**3, 512-9, 1024**0)
503
max
503 33
125 1
def print_twice(bruce):
print bruce, bruce
bruce
bruce
bruce
Python shell import
print_twice chap03.py
Python shell
>>> from chap03 import *
>>> print_twice('Spam')
Spam Spam
>>> print_twice(5)
5 5
>>> print_twice(3.14159)
3.14159 3.14159
- 25 -
bruce = 'Spam' print_twice('Spam')
print_twice(5) bruce = 5 print_twice(3.14159) bruce = 3.14159
print_twice
I
print_twice
>>> print_twice('Spam'*4)
SpamSpamSpamSpam SpamSpamSpamSpam
'Spam'*4 'SpamSpamSpamSpam' print_twice
3.4
Python
>>> print_twice(abs(-7))
7 7
>>> print_twice(max(3, 1, abs(-11), 7))
11 11
abs(-7) 7 print_twice
abs(-11) 11 max(3, 1, 11, 7)
11 print_twice(11)
3.5
- 26 -
>>>
>>>
>>>
Pie
3.6
__main__
cat_twice cat_twice print_twice
__main__
part1 chant1
part2 chant2 bruce cat
- 27 -
Python
tryme2.py Python
def print_twice(bruce):
print bruce, bruce
print cat
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
chant1 = "Pie Jesu domine, "
chant2 = "Dona eis requim."
cat_twice(chant1, chant2)
print cat print_twice cat
stack trace
3.7
function
function definition
compound statement
- 28 -
1. -
2. -
keyword expression :
statement
statement ...
header
:
body
Python
function call
flow of execution
parameter
import
Python
Python shell
tryme.py
def print_thrice(thing):
print thing, thing, thing
n = 42
s = "And now for something completely different..."
tryme.py Python shell
$ ls
tryme.py <and other stuff...>
$ python
>>>
tryme.py print_thricen s
>>> n
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
- 29 -
function composition:
local variable
stack diagram
frame
traceback
. stack
trace runtime stack
3.8
1. tryme3.py three_lines
nine_lines clear_screen
clear_screen
- 30 -
2. tryme3.py clear_screen
4. cat_n_times s n
def cat_n_times(s, n):
<fill in your code here>
import_test.py unix
import_test.py ls import_test.py Python shell
- 31 -
4
4.1
Python %
>>>
>>>
2
>>>
>>>
1
quotient = 7 / 3
print quotient
remainder = 7 % 3
print remainder
7 3 2 1
--- x % y 0x y
x % 10 x
x % 100
4.2
Boole
True False true false
>>> type(True)
<type 'bool'>
>>> type(true)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
boolean expression==
>>> 5 == 5
True
- 32 -
>>> 5 == 6
False
True5
6 False
==
x
x
x
x
x
!= y
# x y
> y
# x y
< y
# x y
>= y
# x y
<= y
# x y
Python
=== = ==
=< =>
4.3
andor not
4.4
if
if x > 0:
print "x is positive"
if
if
if
- 33 -
if
if :
True
False
if
pass
if True:
pass
4.5
#
#
if
if x % 2 == 0:
print x, "is even"
else:
print x, "is odd"
x 2 0 x
branches
def print_parity(x):
if x % 2 == 0:
print x, "is even"
else:
print x, "is odd"
x print_parity
>>> print_parity(17)
17 is odd.
>>> y = 41
>>> print_parity(y+1)
- 34 -
42 is even.
4.6
if x < y:
print x, "is less than", y
elif x > y:
print x, "is greater than", y
else:
print x, "and", y, "are equal"
elif else if elif
else
if choice == 'a':
function_a()
elif choice == 'b':
function_b()
elif choice == 'c':
function_c()
else:
print "Invalid choice."
Python
4.7
if x == y:
print x, "and", y, "are equal"
else:
if x < y:
print x, "is less than", y
else:
print x, "is greater than", y
if
- 35 -
if 0 < x:
if x < 10:
print "x is a positive single digit."
print and
4.8
return
return
def print_square_root(x):
if x <= 0:
print "Positive numbers only, please."
return
result = x**0.5
print "The square root of x is", result
print_square_root x x
0 0 return
4.9
Python raw_input
input
- 36 -
Return Enter raw_input
input Python
prompt = "What...is the airspeed velocity of an unladen swallow?\n"
speed = input(prompt)
speed
Python
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?What do you mean, an African
or a European swallow?...
SyntaxError: invalid syntax
Python
4.10
Python
int()
>>> int("32")
32
- 37 -
>>> int("Hello")
ValueError: invalid literal for int() with base 10: 'Hello'
int
>>>
-2
>>>
3
>>>
42
>>>
1
int(-2.3)
int(3.99999)
int("42")
int(1.0)
float()
>>> float(32)
32.0
>>> float("3.14159")
3.14159
>>> float(1)
1.0
Python 1 1.0
str()
>>> str(32)
'32'
>>> str(3.14149)
'3.14149'
>>> str(True)
'True'
>>> str(true)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
str() True
true
>>> bool(1)
True
>>> bool(0)
False
>>> bool("Ni!")
True
>>> bool("")
- 38 -
False
>>> bool(3.14159)
True
>>> bool(0.0)
False
Python
0 0
4.11 Gasp
GASPGraphics API for Students of Python Python
gasp
>>> from gasp import *
>>> begin_graphics()
>>> Circle((200, 200), 60)
Circle instance at (200, 200) with radius 60
>>> Line((100, 400), (580, 200))
Line instance from (100, 400) to (590, 250)
>>> Box((400, 350), 120, 100)
Box instance at (400, 350) with width 120 and height 100
>>> end_graphics()
>>>
- 39 -
GASP
4.12
modulus operator
%
boolean value
True FalsePython
bool
boolean expression
comparison operator
==!=><>= <=
logical operator
andor not
conditional statement
- 40 -
condition
block
body
branch
chained conditional
Python
if ... elif ... else
nesting
prompt
type conversion
4.13
1. Python
a) >>> 5 % 2
b) >>> 9 % 5
c) >>> 15 % 12
d) >>> 12 % 15
e) >>> 6 % 6
f) >>> 0 % 7
g) >>> 7 % 0
- 41 -
2.
if x < y:
print x, "is less than", y
elif x > y:
print x, "is greater than", y
else:
print x, "and", y, "are equal"
compare(x, y) compare
3.
Python p q
expression = raw_input("Enter a boolean expression in two variables, p and q:
")
print " p
q
length = len( " p
print length*"="
%s"
q
% expression
%s" % expression)
p_and_q.py
p or q
p
q
p or q
=====================
True
True
True
True
False
True
False True
True
False False
False
def truth_table(expression):
print " p
q
%s"
length = len( " p
q
print length*"="
% expression
%s" % expression)
- 42 -
a.
b.
c.
d.
e.
not(p or q)
p and q
not(p and q)
not(p) or not(q)
not(p) and not(q)
4. Python shell
True or False
True and False
not(False) and True
True or 7
False or 7
True and 0
False or 8
"happy" and "sad"
"happy" or "sad"
"" and "sad"
"happy" and ""
and or
5.
if choice == 'a':
function_a()
elif choice == 'b':
function_b()
- 43 -
dispatch('b')
function_b was called...
abc Python Shell
6. is_divisible_by_3
3 This number is divisible by three.This number is not divisible
by three.
is_divisible_by_5
7.
is_divisible_by_n(x, n)
ch04e06.py Python Shell
>>> from ch04e06 import *
>>> is_divisible_by_n(20, 4)
Yes, 20 is divisible by 4
>>> is_divisible_by_n(21, 8)
No, 21 is not divisible by 8
8.
if "Ni!":
print 'We are the Knights who say, "Ni!"'
else:
print "Stop it!No more of this!"
if 0:
print "And now for something completely different..."
else:
print "What's all this, then?"
# gasp
- 44 -
begin_graphics()
#
#
#
#
#
#
pause()
end_graphics()
#
#
#
#
draw_house()
draw_house()
x y -- def draw_house(x, y):
draw_house
- 45 -
5.1
abspow max
biggest = max(3, 7, 2, 5)
x = abs(3 - 11) + 10
fruitful
functions area
def area(radius):
temp = 3.14159 * radius**2
return temp
return return
return value
def area(radius):
return 3.14159 * radius**2
temp temporary variables
return
abs
def absolute_value(x):
if x < 0:
return -x
else:
return x
return return
return
else if return
- 46 -
def absolute_value(x):
if x < 0:
return -x
return x
return
dead code
return
absolute_value
def absolute_value(x):
if x < 0:
return -x
elif x > 0:
return x
x 0
return None
5.2
incremental development
x1, y1x2, y2
- 47 -
Python distance
>>> distance(1, 2, 4, 6)
0.0
3 4 5 3-4-5
---
x2 - x1 y2 - y1 dx dy
dx dy
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
print "dsquared is: ", dsquared
return 0.0
print
scaffolding
- 48 -
25
0.5
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = dsquared**0.5
return result
result
1.
2.
3.
5.3
composition
xc yc xp yp
distance
return result
area2 area
radius result
5.4
>>> is_divisible(6, 4)
False
>>> is_divisible(6, 3)
True
if is_divisible(x, y):
print "x is divisible by y"
else:
print "x is not divisible by y"
if is_divisible(x, y) == True:
5.5
function
- 50 -
def f(n):
return 3*n - 6
def g(n):
return 5*n + 2
def h(n):
return -2*n + 17
def doto(value, func):
return func(value)
print doto(7,
print doto(7,
print doto(7,
doto
f)
g)
h)
7 fg h
func
15
37
3
5.6
import
- 51 -
5.7
Python
5.8
doctest
unit testing
- 52 -
myfunctions.py
def is_divisible_by_2_or_5(n):
"""
>>> is_divisible_by_2_or_5(8)
True
"""
if __name__ == '__main__':
import doctest
doctest.testmod()
doctest doctest
$ python myfunctions.py
**********************************************************************
File "myfunctions.py", line 3, in __main__.is_divisible_by_2_or_5
Failed example:
is_divisible_by_2_or_5(8)
Expected:
True
Got nothing
**********************************************************************
1 items had failures:
1 of
1 in __main__.is_divisible_by_2_or_5
***Test Failed*** 1 failures.
$
is_divisible_by_2_or_5(8)
True is_divisible_by_2_or_5
doctest True
True
def is_divisible_by_2_or_5(n):
"""
>>> is_divisible_by_2_or_5(8)
True
"""
return True
if __name__ == '__main__':
import doctest
doctest.testmod()
- 53 -
doctest
-v
$ python myfunctions.py -v
Trying:
is_divisible_by_2_or_5(8)
Expecting:
True
ok
1 items had no tests:
__main__
1 items passed all tests:
1 tests in __main__.is_divisible_by_2_or_5
1 tests in 2 items.
1 passed and 0 failed.
Test passed.
$
is_divisible_by_2_or_5 True
\
def is_divisible_by_2_or_5(n):
"""
>>> is_divisible_by_2_or_5(8)
True
>>> is_divisible_by_2_or_5(7)
False
>>> is_divisible_by_2_or_5(5)
True
>>> is_divisible_by_2_or_5(9)
False
"""
return n % 2 == 0 or n % 5 == 0
if __name__ == '__main__':
import doctest
doctest.testmod()
-v
5.9
fruitful function
- 54 -
return value
temporary variable
dead code
return
None
return return Python None
NoneType
incremental development
scaffolding
boolean function
composition of functions
unit testing
Python doctest
5.10
ch05.py
if __name__ == '__main__':
import doctest
doctest.testmod()
doctest
"""
>>> compare(5, 4)
1
>>> compare(7, 7)
0
>>> compare(2, 3)
-1
>>> compare(42, 1)
1
"""
#
doctest
2. hypotenuse
"""
>>> intercept(1, 6, 3, 12)
3.0
>>> intercept(6, 1, 1, 6)
7.0
>>> intercept(4, 6, 12, 8)
5.0
"""
intercept doctest
4. is_even(n) True
False doctest
5. is_odd(n) n True False
doctest is_even
6.
def is_factor(f, n):
"""
>>> is_factor(3, 12)
True
>>> is_factor(5, 12)
False
>>> is_factor(7, 14)
True
>>> is_factor(2, 14)
True
>>> is_factor(7, 15)
False
"""
is_factor doctest
7.
def is_multiple(m, n):
"""
>>> is_multiple(12,
True
>>> is_multiple(12,
True
>>> is_multiple(12,
False
>>> is_multiple(12,
True
>>> is_multiple(12,
False
3)
4)
5)
6)
7)
- 57 -
"""
is_multiple doctest is_factor
is_multiple
8.
def f2c(t):
"""
>>> f2c(212)
100
>>> f2c(32)
0
>>> f2c(-40)
-40
>>> f2c(36)
2
>>> f2c(37)
3
>>> f2c(38)
3
>>> f2c(39)
4
"""
f2c
round Python shell round.__doc__
round
9.
def c2f(t):
"""
>>> c2f(0)
32
>>> c2f(100)
212
>>> c2f(-40)
-40
>>> c2f(12)
54
>>> c2f(18)
64
- 58 -
>>> c2f(-48)
-54
"""
c2f
- 59 -
6.1
bruce = 5
print bruce,
bruce = 7
print bruce
5 7 bruce 5
7 print
Python
= a = b
a = 7 7 = a
Python a = 7 7 = a
a = b a b
Python
a = 5
b = a
# a b
a = 3
# a b
a b
<- :=
6.2
- 60 -
x = x + 1
x 1 x
Python
>>> x = x + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> x = 0
>>> x = x + 1
>>>
1 1 .
6.3
while
Python
while
countdown while
def countdown(n):
while n > 0:
print n
n = n-1
print "Blastoff!"
while n 0 n
n 1 0 Blastoff!
while
1. False True
2. while
3. 1
- 61 -
countdown n
n 0
def sequence(n):
while n != 1:
print n,
if n % 2 == 0:
# n is even
n = n / 2
else:
# n is odd
n = n * 3 + 1
n != 1 n 1
n
n 2 n * 3 + 1
3 31051684 21
n n 1
n 2
n 1 16
6.4
sequence(3)
3 n 3 1while
3 3 % 2 == 0 Falseelse
3 * 3 + 1 n
- 62 -
n
output
-------3
3
10
10 != 1 True 1010 % 2 == 0
if n 5
n
output
-------3
3
10
10
5
5
16
16
8
8
4
4
2
2
1
n 2
log2(n) 1
6.5
def num_digits(n):
count = 0
while n:
count = count + 1
n = n / 10
return count
num_digits(710) 3
counter count 0
count --
- 63 -
0 5
def num_zero_and_five_digits(n):
count = 0
while n:
digit = n % 10
if digit == 0 or digit == 5:
count = count + 1
n = n / 10
return count
num_zero_and_five_digits(1055030250) 7
6.6
Python
>>>
>>>
>>>
1
>>>
>>>
2
>>>
count = 0
count += 1
count
count += 1
count
n = 2
n *= 5
n
n -= 4
n
n /= 2
n
n %= 2
n
- 64 -
6.7
Intel
Pentium
2
x = 1
while x < 13:
print x, '\t', 2**x
x += 1
'\t' tab \t
tab \n
tab
print
tab tab Tab
1
2
3
4
5
6
7
8
9
10
11
2
4
8
16
32
64
128
256
512
1024
2048
- 65 -
12
6.8
4096
tab
1 6
2
i = 1
while i <= 6:
print 2*i, '
',
i += 1
print
i
i 1 6 i 7
2*i
print print
6.9
4
6
8
10
12
encapsulategeneralize
print_parity is_divisible
2
n
def print_multiples(n):
i = 1
while i <= 6:
print n*i, '\t',
i += 1
print
- 66 -
n 2
2 3
6
9
12
15
4
18
8
12
16
20
24
--- print_multiples
i = 1
while i <= 6:
print_multiples(i)
i += 1
print_multiples
print
1
2
3
4
5
6
2
4
6
8
10
12
3
6
9
12
15
18
4
8
12
16
20
24
5
10
15
20
25
30
6
12
18
24
30
36
6.10
def print_mult_table():
i = 1
while i <= 6:
print_multiples(i)
i += 1
- 67 -
6.11
print_multiples print_mult_table
i
print_multiples i print_mult_table i
i print_mult_table 1 6 3
4print_mult_table i
print_multiples n
print_multiples i 1 6 2
print_mult_table i
i j
6.12
6 6
print_mult_table
def print_mult_table(high):
i = 1
while i <= high:
print_multiples(i)
i += 1
high 6 7 print_mult_table
- 68 -
1
2
3
4
5
6
7
2
3
4
5
6
4
6
8
10
12
6
9
12
15
18
8
12
16
20
24
10
15
20
25
30
12
18
24
30
36
14
21
28
35
42
---
print_multiples
high
print_mult_table
7 7
1
2
3
4
5
6
7
2
3
4
5
6
7
4
6
8
10
12
14
6
9
12
15
18
21
8
12
16
20
24
28
10
15
20
25
30
35
12
18
24
30
36
42
14
21
28
35
42
49
ab = ba
print_mult_table
print_multiples(i, high)
print_multiples(i, i)
- 69 -
1
2
3
4
5
6
7
4
6
8
10
12
14
9
12
15
18
21
16
20
24
28
25
30
35
36
42
49
6.13
1.
2.
3.
4.
6.14
def sqrt(n):
approx = n/2.0
better = (approx + n/approx)/2.0
while better != approx:
approx = better
better = (approx + n/approx)/2.0
return approx
25 5.0
6.15
- 70 -
n 9
n - 1 10 - n 9
6.16
multiple assignment
increment
1
decrement
1
iteration
loop
- 71 -
infinite loop
trace
counter
0
body
loop variable
tab
tab
newline
cursor
escape sequence
\
encapsulate
generalize
development plan
algorithm
6.17
- 72 -
1.
produces
this
output.
1
3
6
10
15
5. ch06.py
if __name__ == '__main__':
import doctest
doctest.testmod()
is_prime True
False doctests
6. num_digits(0) 1
num_digits(-24) -1/10 -1 num_digits
ch06.py
def num_digits(n):
"""
>>> num_digits(12345)
5
>>> num_digits(0)
1
>>> num_digits(-12345)
5
"""
num_digits doctests
- 73 -
7. ch06.py
def num_even_digits(n):
"""
>>> num_even_digits(123456)
3
>>> num_even_digits(2468)
4
>>> num_even_digits(1357)
0
>>> num_even_digits(2)
1
>>> num_even_digits(20)
2
"""
num_even_digits
8. ch06.py
def print_digits(n):
"""
>>> print_digits(13789)
9 8 7 3 1
>>> print_digits(39874613)
3 1 6 4 7 8 9 3
>>> print_digits(213141)
1 4 1 3 1 2
"""
print_digits doctests
9. sum_of_squares_of_digits
sum_of_squares_of_digits(987) 194 9**2 + 8**2 + 7**2 == 81 + 64 + 49 ==
194
def sum_of_squares_of_digits(n):
"""
>>> sum_of_squares_of_digits(1)
1
>>> sum_of_squares_of_digits(9)
81
>>> sum_of_squares_of_digits(11)
2
>>> sum_of_squares_of_digits(121)
6
>>> sum_of_squares_of_digits(987)
194
"""
- 74 -
7 doctests
- 75 -
7.
7.1
intfloatboolNoneType str
---
7.2
len
>>> len(fruit)
6
length = len(fruit)
last = fruit[length]
# ERROR!
IndexError: string index out of range
"banana" 0 0 5
length 1
length = len(fruit)
last = fruit[length-1]
fruit[-1]
fruit[-2]
7.3
for
while
index = 0
while index < len(fruit):
letter = fruit[index]
print letter
index += 1
index <
len(fruit) index
len(fruit)-1
Python
--- for
for char in fruit:
print char
char
for
Robert McCloskey's Make Way for
Ducklings JackKackLackMackNackOuackPack Quack
- 77 -
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
print letter + suffix
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack
Ouack Quack
7.4
7.5
if word == "banana":
print "Yes, we have no bananas!"
zebras
7.6
[]
7.7
in
- 79 -
in
>>> 'p' in 'apple'
True
>>> 'i' in 'apple'
False
>>> 'ap' in 'apple'
True
>>> 'pa' in 'apple'
False
def remove_vowels(s):
vowels = "aeiouAEIOU"
s_without_vowels = ""
for letter in s:
if letter not in vowels:
s_without_vowels += letter
return s_without_vowels
7.8
A find
-1
- 80 -
eureka
Eureka
7.9
fruit = "banana"
count = 0
for char in fruit:
if char == 'a':
count += 1
print count
7.10
find
7.11 string
string
>>> import string
dir
>>> dir(string)
string
>>> type(string.digits)
<type 'str'>
>>> type(string.find)
<type 'function'>
string.digits
>>> print string.digits
0123456789
string.find
docstring __doc__
- 82 -
7.12
string
string.digits
string.lowercase string.uppercase
print string.lowercase
print string.uppercase
print string.digits
find find(lowercase, ch)
-1 ch
- 83 -
def is_lower(ch):
return string.find(string.lowercase, ch) != -1
in
def is_lower(ch):
return ch in string.lowercase
def is_lower(ch):
return 'a' <= ch <= 'z'
ch a z
string
>>> print string.whitespace
Whitespace
string.whitespace whitespace tab\t
\n
string
Python Library Reference Python
http://www.python.org
7.13
Python %
Python
>>> "His name is %s." % "Arthur"
'His name is Arthur.'
>>> name = "Alice"
>>> age = 10
>>> "I am %s and I am %d years old." % (name, age)
'I am Alice and I am 10 years old.'
>>> n1 = 4
>>> n2 = 5
>>> "2**10 = %d and %d * %d = %f" % (2**10, n1, n2, n1 * n2)
'2**10 = 1024 and 4 * 5 = 20.000000'
>>>
"<>" % (<>)
%
%
- 84 -
%s"Arthur"
i = 1
print "i\ti**2\ti**3\ti**5\ti**10\ti**20"
while i <= 10:
print i, '\t', i**2, '\t', i**3, '\t', i**5, '\t', i**10, '\t', i**20
i += 1
1 10 tab
\t 8 tab
i
1
2
3
4
5
6
7
8
9
10
i**2
i**3
i**5
i**10
i**20
1
1
1
1
1
4
8
32
1024
1048576
9
27
243
59049
3486784401
16
64
1024
1048576
1099511627776
25
125
3125
9765625
95367431640625
36
216
7776
60466176
3656158440062976
49
343
16807
282475249
79792266297612001
64
512
32768
1073741824
1152921504606846976
81
729
59049
3486784401
12157665459056928801
100
1000
100000 10000000000
100000000000000000000
tab
i = 1
print "%-4s%-5s%-6s%-8s%-13s%-15s" %
('i', 'i**2', 'i**3', 'i**5', 'i**10', 'i**20')
while i <= 10:
print "%-4d%-5d%-6d%-8d%-13d%-15d" % (i, i**2, i**3, i**5, i**10, i**20)
i += 1
i
1
i**2 i**3
1
1
i**5
1
i**10
1
i**20
1
- 85 -
2
3
4
5
6
7
8
9
10
4
8
32
9
27
243
16
64
1024
25
125
3125
36
216
7776
49
343
16807
64
512
32768
81
729
59049
100 1000 100000
%
1024
1048576
59049
3486784401
1048576
1099511627776
9765625
95367431640625
60466176
3656158440062976
282475249
79792266297612001
1073741824
1152921504606846976
3486784401
12157665459056928801
10000000000 100000000000000000000
-
%-13d 13
7.14
Python
[:]
.
docstring
- 86 -
Docstring Docstrings doctest
whitespace
string.whitespace
7.15
1.
prefixes = "JKLMNOPQ"
suffix = "ack"
for letter in prefixes:
print letter + suffix
Ouack Quack
2.
fruit = "banana"
count = 0
for char in fruit:
if char == 'a':
count += 1
print count
count_letters
3. count_letters
find 8.10
4. is_lower
5. stringtools.py
def reverse(s):
"""
>>> reverse('happy')
'yppah'
>>> reverse('Python')
'nohtyP'
>>> reverse("")
- 87 -
''
>>> reverse("P")
'P'
"""
if __name__ == '__main__':
import doctest
doctest.testmod()
reverse doctests
6. mirror stringtools.py
def mirror(s):
"""
>>> mirror("good")
'gooddoog'
>>> mirror("yes")
'yessey'
>>> mirror('Python')
'PythonnohtyP'
>>> mirror("")
''
>>> mirror("a")
'aa'
"""
doctests
7. remove_letter stringtools.py
def remove_letter(letter, strng):
"""
>>> remove_letter('a', 'apple')
'pple'
>>> remove_letter('a', 'banana')
'bnn'
>>> remove_letter('z', 'banana')
'banana'
>>> remove_letter('i', 'Mississippi')
'Msssspp'
"""
doctests
8.
def is_palindrome(s):
"""
>>> is_palindrome('abba')
True
>>> is_palindrome('abab')
- 88 -
False
>>> is_palindrome('tenet')
True
>>> is_palindrome('banana')
False
>>> is_palindrome('straw warts')
True
"""
def count(sub, s):
"""
>>> count('is', 'Mississippi')
2
>>> count('an', 'banana')
2
>>> count('ana', 'banana')
2
>>> count('nana', 'banana')
1
>>> count('nanan', 'banana')
0
"""
def remove(sub, s):
"""
>>> remove('an', 'banana')
'bana'
>>> remove('cyc', 'bicycle')
'bile'
>>> remove('iss', 'Mississippi')
'Missippi'
>>> remove('egg', 'bicycle')
'bicycle'
"""
def remove_all(sub, s):
"""
>>> remove_all('an', 'banana')
'ba'
>>> remove_all('cyc', 'bicycle')
'bile'
>>> remove_all('iss', 'Mississippi')
'Mippi'
>>> remove_all('eggs', 'bicycle')
'bicycle'
"""
- 89 -
doctests
9. Python shell
a.
b.
c.
d.
10.
- 90 -
8 Catch
8.1
GASP
8.2
while
while gasp
- 91 -
x y
GASP
begin_graphics .
set_speed
filled=True Circle(...)
ball = Circle ball
GASP move_to
wait gasp
set_speed
8.3
GASP
- 92 -
-2
-1
-4
1
-2
3
-5
-3
4
-5
random_between 1 y pitch.py
dy = 1
-4 4
dy = random_between(-4, 4)
8.4
dy
pitch.py while
if ball_y >= 590 or ball_y <= 10:
dy *= -1
8.5
break
break
guess.py
8.6
j k
mitt.py
from gasp import *
begin_graphics(800, 600, title="Catch", background=color.yellow)
set_speed(40)
mitt_x = 780
mitt_y = 300
mitt = Circle((mitt_x, mitt_y), 20)
while True:
if key_pressed('k') and mitt_y <= 580:
mitt_y += 5
elif key_pressed('j') and mitt_y >= 20:
- 94 -
mitt_y -= 5
if key_pressed('escape'):
break
move_to(mitt, (mitt_x, mitt_y))
wait()
end_graphics()
mitt.py j k
8.7
wait()
wait(event=ELAPSED_TIME, delay=1)
end_graphics()
collide.py
8.8
while
if key_pressed('escape'):
break
move_to(mitt, (mitt_x, mitt_y))
if distance(ball_x, ball_y, mitt_x, mitt_y) <= 30:
remove_from_screen(ball)
break
# ball is caught
wait()
end_graphics()
catch.py
8.9
0 1
1 1 0 1
if player_score == 5:
Text("Player Wins!", (340, 290), size=32)
else:
Text("Computer Wins!", (340, 290), size=32)
wait(event=ELAPSED_TIME, delay=4)
end_graphics()
scores.py
catch.py if ball_x > 810:
8.10
catch.py
from gasp import *
COMPUTER_WINS = 1
PLAYER_WINS = 0
QUIT = -1
def play_round():
ball_x = 10
ball_y = random_between(20, 280)
ball = Circle((ball_x, ball_y), 10, filled=True)
dx = 4
dy = random_between(-5, 5)
mitt_x = 780
mitt_y = random_between(20, 280)
mitt = Circle((mitt_x, mitt_y), 20)
while True:
if ball_y >= 590 or ball_y <= 10:
dy *= -1
ball_x += dx
ball_y += dy
if ball_x >= 810:
remove_from_screen(ball)
remove_from_screen(mitt)
return COMPUTER_WINS
move_to(ball, (ball_x, ball_y))
if key_pressed('k') and mitt_y <= 580:
mitt_y += 5
elif key_pressed('j') and mitt_y >= 20:
mitt_y -= 5
if key_pressed('escape'):
return QUIT
move_to(mitt, (mitt_x, mitt_y))
if distance(ball_x, ball_y, mitt_x, mitt_y) <= 30:
remove_from_screen(ball)
remove_from_screen(mitt)
return PLAYER_WINS
wait()
def play_game():
player_score = 0
comp_score = 0
while True:
- 99 -
COMPUTER_WINSPLAYER_WINS QUIT
Python
- 100 -
8.11
random
Python
trichotomy
a b a < ba > b a = b
nested loop
abstraction
Python
constant
Python Python
- 101 -
8.12
1. mitt.py <Escape>
2. guess.py
11
3. mitt.py
4. collide.py ball1_dx 2
ball1_dx 4 ball2_dx -2
5. collide.py break # .
remove_from_screen(ball1)
remove_from_screen break
6.
Text("Player Wins!", (340, 290), size=32)
wait(event=ELAPSED_TIME, delay=2)
8.8 catch.py
7. catch.py play_round
<Escape>
8. catch.py
9.
10.
8.13 pong.py
Pong P pong
catch.py pong
catch.py pong.py
- 102 -
- 103 -
9 Tuple
9.1
tuple
Python tuple
tuple
>>> tuple = 'a', 'b', 'c', 'd', 'e'
tuple
>>> tuple = ('a', 'b', 'c', 'd', 'e')
tuple
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
Python ('a')
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
>>> tuple[0]
'a'
slice operator
>>> tuple[1:3]
('b', 'c')
tuple
>>> tuple[0] = 'A'
TypeError: object doesn't support item assignment
tuple tuple
9.2
Tuple
a b
>>> temp = a
>>> a = b
>>> b = temp
Python tuple
>>> a, b = b, a
- 105 -
tuple tuple
tuple
>>> a, b, c, d = 1, 2, 3
ValueError: unpack tuple of wrong size
9.3
Tuple
tuple
tuple
a, b = swap(a, b)
swap swap
x, y = y, x
swap(a, b)
a x swap x x
__main__ a y b
9.4
- 106 -
Python
import random
for i in range(10):
x = random.random()
print x
low high
low high
9.5
randomList
def randomList(n):
s = [0] * n
for i in range(n):
s[i] = random.random()
- 107 -
return s
>>> randomList(8)
0.15156642489
0.498048560109
0.810894847068
0.360371157682
0.275119183077
0.328578797631
0.759199803101
0.800367163582
random
9.6
7.8
count = 0
for char in fruit:
if char == 'a':
- 108 -
count = count + 1
print count
num
low high
count = 0
for num in t:
if low < num < high:
count = count + 1
print count
inBucket
low high
pattern matching
9.7
inBucket
- 109 -
numBuckets 1.0
/ numBuckets
i 0
numBuckets-1
bucketWidth
numBuckets = 8
0.0 to 0.125
0.125 to 0.25
0.25 to 0.375
0.375 to 0.5
- 110 -
0.5 to 0.625
0.625 to 0.75
0.75 to 0.875
0.875 to 1.0
0.0
1.0
inBucket i
numBuckets = 8
buckets = [0] * numBuckets
bucketWidth = 1.0 / numBuckets
for i in range(numBuckets):
low = i * bucketWidth
high = low + bucketWidth
buckets[i] = inBucket(t, low, high)
print buckets
1000
[138, 124, 128, 118, 130, 117, 114, 131]
125
9.8
- 111 -
inBucket
i bucketWidth
0.0 1.0
bucketWidth
numBuckets = 8
buckets = [0] * numBuckets
for i in t:
index = int(i * numBuckets)
buckets[index] = buckets[index] + 1
int
len(buckets)-1
buckets histogram
histogram
9.9
immutable type
mutable type
- 112 -
tuple
tuple
Tuple
deterministic
pseudorandom
histogram
pattern matching
- 113 -
10
- 114 -
11
f
>>> f = open("test.dat","w")
>>> print f
<open file 'test.dat', mode 'w' at fe820>
mode"w"
test.dat
write
>>> f.write("Now is the time")
>>> f.write("to close the file")
>>> f.close()
- 115 -
"r"
>>> f = open("test.dat","r")
>>> f = open("test.cat","r")
IOError: [Errno 2] No such file or directory: 'test.cat'
read
time to
read
>>> f = open("test.dat","r")
>>> print f.read(5)
Now i
read read
>>>
- 116 -
break
while True
break text
11.1
Python
>>> f = open("test.dat","w")
>>> f.write("line one\nline two\nline three\n")
>>> f.close()
- 117 -
readline
>>> f = open("test.dat","r")
>>> print f.readline()
line one
>>>
readlines
<br>012
readline readlines
>>> print f.readline()
filterFile oldFile #
def filterFile(oldFile, newFile):
f1 = open(oldFile, "r")
f2 = open(newFile, "w")
while True:
text = f1.readline()
if text == "":
break
- 118 -
if text[0] == '#':
continue
f2.write(text)
f1.close()
f2.close()
return
continue
text text
text
11.2
write
str
>>> x = 52
>>> f.write (str(x))
format operator %%
%
"%d" tuple
d
>>> cars = 52
>>> "%d" % cars
'52'
- 119 -
'52' 52
>>> cars = 52
>>> "In July we sold %d cars." % cars
'In July we sold 52 cars.'
tuple
>>> "%6d" % 62
'
62'
6.100000'
- 120 -
>>> "%-6d" % 62
'62
'
6.10'
dictionary
dictionary
def report (wages) :
students = wages.keys()
students.sort()
for student in students :
print "%-20s %12.2f" % (student, wages[student])
dictionary
>>> wages = {'mary': 6.23, 'joe': 5.45, 'joshua': 4.25}
>>> report (wages)
joe
5.45
joshua
4.25
mary
6.23
11.3
- 121 -
Python
path
>>>
f = open("/usr/share/dict/words","r")
>>>
print f.readline()
Aarhus
/
delimiter
/usr/share/dict/words
11.4
str
>>>
f.readline()
'12.3[1, 2, 3]'
picklingpickle
pickle
- 122 -
dump
>>> pickle.dump(12.3, f)
>>> pickle.dump([1,2,3], f)
>>> f.close()
>>> f = open("test.pck","r")
>>> x = pickle.load(f)
>>> x
12.3
>>> type(x)
<type 'float'>
>>> y = pickle.load(f)
>>> y
[1, 2, 3]
>>> type(y)
<type 'list'>
load
11.5
Python
- 123 -
>>> a = []
>>> print a[5]
IndexError: list index out of range
dictionary
>>> b = {}
>>> print b['what']
KeyError: what
Python
try
except
- 124 -
try except
IOError except
exists
true false
def exists(filename):
try:
f = open(filename)
f.close()
return True
except IOError:
return False
17 17
def inputNumber () :
x = input ('Pick a number: ')
if x == 17 :
raise ValueError, '17 is a bad number'
return x
raise ValueError Python
TypeErrorKeyError
NotImplementedError
inputNumber Python
>>> inputNumber ()
- 125 -
Pick a number: 17
ValueError: 17 is a bad number
inputNumber
ValueError
11.6
file
CD-ROM
directory
path
text file
continue statement
format operator
%
format string
format sequence
%
pickle
exception
- 126 -
handle
try except
raise
raise
- 127 -
12
12.1
Python
Point
(0, 0)
(x, y) x y
Python
tuple
class Point:
pass
import
4.4
Point pass
Point Point
instances
instantiation Point Point
blank = Point()
- 128 -
12.2
math.pi string.uppercase
attributes
blank Point
x x x
blank
>>> print blank
<__main__.Point instance at 80f8e70>
Point id
12.3
def printPoint(p):
print '(' + str(p.x) + ', ' + str(p.y) + ')'
printPoint printPoint(blank)
(3.0, 4.0)
12.4
*
Point
is
- 130 -
>>> p1 = Point()
>>> p1.x = 3
>>> p1.y = 4
>>> p2 = Point()
>>> p2.x = 3
>>> p2.y = 4
>>> p1 is p2
False
p1 p2 p1 p2
>>> p2 = p1
>>> p1 is p2
True
shallow equality
deep equality
samePoint
samePoint
>>> p1 = Point()
>>> p1.x = 3
>>> p1.y = 4
>>> p2 = Point()
>>> p2.x = 3
- 131 -
>>> p2.y = 4
>>> samePoint(p1, p2)
True
12.5
class Rectangle:
pass
Rectangle
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0
box.corner.x box
corner x
- 132 -
12.6
findCenter Rectangle
Point Rectangle
def findCenter(box):
p = Point()
p.x = box.corner.x + box.width/2.0
p.y = box.corner.y - box.height/2.0
return p
box
>>> center = findCenter(box)
>>> printPoint(center)
(50.0, -100.0)
12.7
width height
box.width = box.width + 50
box.height = box.height + 100
method
def growRect(box, dwidth, dheight) :
box.width = box.width + dwidth
box.height = box.height + dheight
- 133 -
moveRect Rectangle dx dy
dx corner x dy corner y
12.8
copy copy
False
>>> samePoint(p1, p2)
True
Point copy
shallow copying
Rectangle Point copy
Point Rectangle Point
copy b1 b2
Rectangles growRect
moveRect
b1 b2
deepcopy growRect Rectangle
Rectangle
def growRect(box, dwidth, dheight) :
import copy
newBox = copy.deepcopy(box)
newBox.width = newBox.width + dwidth
- 135 -
moveRect Rectangle
12.9
class
instantiate
instance
object
constructor
method
attribute
shallow equality
deep equality
shallow copy
copy copy
deep copy
copy
deepcopy
- 136 -
13
13.1 Time
Time
class Time:
pass
Time
time = Time()
time.hours = 11
time.minutes = 59
time.seconds = 30
Time
printTime Time :
:
after Time t1 t2
t1 t2 True False
13.2
addTime Time
pure functionsmodifiers
addTime
- 137 -
Time
Time currentTime
breadTime addTime
printTime 14.2
>>> currentTime = Time()
>>> currentTime.hours = 9
>>> currentTime.minutes = 14
>>> currentTime.seconds = 30
- 138 -
12:49:30
return sum
13.3
- 139 -
increment Time
seconds
if while
def increment(time, seconds):
time.seconds = time.seconds + seconds
- 140 -
increment
13.4
13.5 V.S.
prototype development
planned development
Time 60
addTime increment
Time
Time
- 141 -
def convertToSeconds(t):
minutes = t.hours * 60 + t.minutes
seconds = minutes * 60 + t.seconds
return seconds
Time
def makeTime(seconds):
time = Time()
time.hours = seconds // 3600
time.minutes = (seconds%3600) // 60
time.seconds = seconds%60
return time
convertToSeconds addTime
def addTime(t1, t2):
seconds = convertToSeconds(t1) + convertToSeconds(t2)
return makeTime(seconds)
increment
13.6
60 10
convertToSeconds makeTime
- 142 -
Time
13.7
algorithm
n 9
n-1 10-n
9
13.8
pure function
modifier
prototype development
planned development
algorithm
- 144 -
14
14.1
Python
Time
Point Rectangle
Python
Time
Time
dictionaries
keys values
14.2 printTime
Time printTime
- 145 -
class Time:
pass
def printTime(time):
print str(time.hours) + ":" + \
str(time.minutes) + ":" + \
str(time.seconds)
Time
>>> currentTime = Time()
>>> currentTime.hours = 9
>>> currentTime.minutes = 14
>>> currentTime.seconds = 30
>>> printTime(currentTime)
printTime
class Time:
def printTime(time):
print str(time.hours) + ":" + \
str(time.minutes) + ":" + \
str(time.seconds)
printTime
>>> currentTime.printTime()
currentTime time
- 146 -
self
printTime(currentTime)
printTime
currentTime.printTime()
currentTime
14.3
increment 13.3
class Time:
#previous method definitions here...
- 147 -
increment
currentTime.increment(500)
selfseconds 500
14.4
after Time
self
class Time:
#previous method definitions here...
- 148 -
if doneTime.after(currentTime):
print "The bread is not done yet."
done.time current.time
14.5
string.find
find string.find
7.7
def find(str, ch):
index = 0
while index < len(str):
if str[index] == ch:
return index
index = index + 1
return -1
start 0
find
>>> find("apple", "p")
1
end
end len(str)
find str
14.6
__init__ initTime
class Time:
def __init__(self, hours=0, minutes=0, seconds=0):
- 150 -
self.hours = hours
self.minutes = minutes
self.seconds = seconds
self.hours hours
Time init
>>> currentTime = Time(9, 14, 30)
>>> currentTime.printTime()
9:14:30
9:0:30
14.7 Points
12.1 Point
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return '(' + str(self.x) + ', ' + str(self.y) + ')'
x y 0
__str__ Point
__str__ Python str
>>> p = Point(3, 4)
>>> str(p)
'(3, 4)'
Point __str____str__
print
>>> p = Point(3, 4)
>>> print p
(3, 4)
__init__ __str__
- 152 -
14.8
operator overloading
+ __add__
class Point:
# previously defined methods here...
other
self Point Point x
y
+ Point Python __add__
>>>
p1 = Point(3, 4)
>>>
p2 = Point(5, 7)
>>>
p3 = p1 + p2
>>>
print p3
(8, 11)
p1 + p2 p1.__add__(p2)
__sub__(self, other)
__mul__
__rmul__
* PointPython __mul__
Pointdot product
def __mul__(self, other):
- 153 -
* PointPython
__rmul__scalar multiplication
Point other
__rmul__
>>> p1 = Point(3, 4)
>>> p2 = Point(5, 7)
>>> print p1 * p2
43
>>> print 2 * p2
(10, 14)
p2 * 2 PointPython
__mul__ 2 __mul__ other
x
>>> print p2 * 2
AttributeError: 'int' object has no attribute 'x'
14.9 Polymorphism
- 154 -
multadd
Python
def multadd (x, y, z):
return x * y + z
x y z
Point
>>> p1 = Point(3, 4)
>>> p2 = Point(5, 7)
>>> print multadd (2, p1, p2)
(11, 15)
>>> print multadd (p1, p2, 1)
44
Point Point
polymorphic
frontAndBack
def frontAndBack(front):
import copy
back = copy.copy(front)
- 155 -
back.reverse()
print str(front) + str(back)
reverse
frontAndBack
>>>
myList = [1, 2, 3, 4]
>>>
frontAndBack(myList)
[1, 2, 3, 4][4, 3, 2, 1]
Point
copyreverse print
copy Point __str__
Point reverse
def reverse(self):
self.x , self.y = self.y, self.x
Point frontAndBack
>>>
p = Point(3, 4)
>>>
frontAndBack(p)
(3, 4)(4, 3)
14.10
object-oriented language
- 156 -
object-oriented programming
method
override
initialization method
operator overloading
+-*><
dot product
scalar multiplication
polymorphic
- 157 -