You are on page 1of 334

:

/ . :.1382
330.
.1 ) (
005/133

QA76/73


33
2303798 :2358465 :
80 79 76 74 81
77

:
:

1000 :

: 1382
:

:
:

:
964-7999-30-5 :


.
from.now.on.python@gmail.com .

:
.
.
.
:
.
.
.
.



.

.

.
.
.

.

C
.
C
. ++C


C++
.
1990
) (CWI Guido van Rossum . Guido
Monty Python's Flying Circus
.
.
Python .

Scripting Language
Amoeba Guido
.

.
) (GUIs
C++ .
OS/2 Unix Windows ... .
C C++


.

.
. - .
.

C .
.

.
.

.


.

How To Think Like a Computer Scientist


. 20
.

.
CD ) (


.

:





.

1 ........................................................................................................................

-1-1 2 ................................................................................................................................................
-2-1 4 ..................................................................................................................................................................
-3-1 5 .......................................................................................................................................................
-1-3-1 5 ............................................................................................................................................................
-2-3-1 6 .....................................................................................................................................................
-3-3-1 6 ..........................................................................................................................................................
-4-3-1 6 .................................................................................................................................................
-4-1 7 ...............................................................................................................................................
-5-1 9 ........................................................................................................................................................................
-6-19 ................................................................................................................................................................................

13 .....................................................................................................
-1-2 14 .....................................................................................................................................................
-2-2 15 ............................................................................................................................................................................
-3-2 16 ................................................................................................................................
-4-2 17 .........................................................................................................................................................................
-5-2 18 ................................................................................................................................................................

-6-2 19 ......................................................................................................................................................
-7-2 20 ..............................................................................................................................................................
-8-2 21 ...............................................................................................................................................
-9-2 22 ..............................................................................................................................................................................
-10-2 22 .....................................................................................................................................................................
-11-2 23 .........................................................................................................................................................................

27 ..........................................................................................................................................

-1-3 28 ..................................................................................................................................................................
-2-3 29 ..............................................................................................................................................................
-3-3 30 ............................................................................................................................................................
-4-3 30 ....................................................................................................................................................................
-5-332 ............................................................................................................................................................................
-6-3 33 ..............................................................................................................................................................................
-7-3 33 ...............................................................................................................................................
-8-3 36 .............................................................................................................................................
-9-3 36 ..........................................................................................................................................................................
-10-3 37 ................................................................................................................................................
-11-3 39 ..........................................................................................................................
-12-3 40 .........................................................................................................................................................
-13-3 41 .............................................................................................................................................................
-14-3 42 .........................................................................................................................................................................


45 ..................................................................................................................
-1-4 46 ............................................................................................................................................................
-2-4 47 ....................................................................................................................................................................
-3-4 47 .........................................................................................................................................................
-4-4 48 ...................................................................................................................................................

-5-4 49 ............................................................................................................................................
-6-4 50 .........................................................................................................................................
-7-4 51 ...............................................................................................................................................
-8-4 52 ....................................................................................................................................................... return
-9-4 52 ................................................................................................................................................................
-10-4 54 ....................................................................................................................
-11-4 55 ...........................................................................................................................................................
-12-4 55 ......................................................................................................................................................
-13-4 57 .........................................................................................................................................................................

59...........................................................................................................................

-1-5 60 ..............................................................................................................................................................
-2-5 61 ...................................................................................................................................................................
-3-5 64 ..............................................................................................................................................................................
-4-5 65 ........................................................................................................................................................................
-5-5 66 ..........................................................................................................................................................
-6-5 69 ..........................................................................................................................................................
-7-5 69 ......................................................................................................................................................................
-8-5 70 ........................................................................................................................................................
-9-5 72 ............................................................................................................................................................................


75 ..........................................................................................................................................
-1-6 76 .............................................................................................................................................................
-2-6 77 ........................................................................................................................................................... while
-3-6 79 ...........................................................................................................................................................................
-4-6 82 .............................................................................................................................................................
-5-6 82 .......................................................................................................................................................

-6-6 84 ......................................................................................................................................................
-7-6 84 ............................................................................................................................................................
-8-6 85 .............................................................................................................................................................
-9-687 ..................................................................................................................................................................................
-10-6 87 ..........................................................................................................................................................................


91........................................................................................................................................
-1-7 92 ..........................................................................................................................................................
-2-7 93 ......................................................................................................................................................................
-3-7 93 ................................................................................................................................................. for
-4-7 95 ...............................................................................................................................................................
-5-7 96 ..............................................................................................................................................................
-6-7 96 ....................................................................................................................................................
-7-7 97 ........................................................................................................................................................... find
-8-7 98 ........................................................................................................................................................
-9-7 98 ........................................................................................................................................................ string
-10-7 99 ..................................................................................................................................................
-11-7 101 ......................................................................................................................................................................


103 ....................................................................................................................................
-1-8 104 ...............................................................................................................................................................
-2-8 105 .......................................................................................................................................................
-3-8 107 .................................................................................................................................................................
-4-8 107 .............................................................................................................................................................
-5-8 108 .........................................................................................................................................for
-6-8 109 ........................................................................................................................................................
-7-8 109 ..........................................................................................................................................................
-8-8 110 .................................................................................................................................................

-9-8 111 .................................................................................................................................................................


-10-8 111 ...........................................................................................................................................................
-11-8112 ...................................................................................................................................................................
-12-8 113 ..........................................................................................................................................................
-13-8 114 .......................................................................................................................................
-14-8 115 .....................................................................................................................................................
-15-8 116 ..................................................................................................................................................................
-16-8 116 ...................................................................................................................................................
-17-8 117 ......................................................................................................................................................................

119 ................................................................................................................................

-1-9 120 .........................................................................................................................................


-2-9 121 ..........................................................................................................................................
-3-9 122 ....................................................................................................................
-4-9 123 ..............................................................................................................................................................
-5-9 123 ............................................................................................................................................
-6-9 124 .........................................................................................................................................................................
-7-9 125 ..............................................................................................................................................................
-8-9 127 ................................................................................................................................................
-9-9 128 .........................................................................................................................................................................


131 .............................................................................................................................
-1-10 133 .................................................................................................................................
-2-10 134 ..................................................................................................................................................
-3-10 135 ........................................................................................................................................
-4-10 135 ...............................................................................................................................................
-5-10 137 .................................................................................................................................................................

-6-10 139 ..................................................................................................................................................


-7-10 140 .........................................................................................................................................................
-8-10 140 ......................................................................................................................................................................


143..................................................................................................................
-1-11 146 .........................................................................................................................................................
-2-11 148 .........................................................................................................................................................
-3-11 150 .............................................................................................................................................................
150 ................................................................................................................................................................ Pickling -4-11
-5-11 152 ......................................................................................................................................................................
-6-11 154 .......................................................................................................................................................................

157...........................................................................................................................

-1-12 - 158 .....................................................................................................................................


-2-12 159 .................................................................................................................................................................
-3-12 160 ......................................................................................................................................
-4-12 161 .........................................................................................................................................................
-5-12 162 ....................................................................................................................................................................
-6-12 163 ..........................................................................................................................
-7-12 163 ....................................................................................................................................................
-8-12 164 ................................................................................................................................................................
-9-12 166.......................................................................................................................................................................


169 ........................................................................................................................
-1-13 170 ...........................................................................................................................................................................
-2-13 171 ...............................................................................................................................................................
-3-13 172 ...........................................................................................................................................................

-4-13 173 ......................................................................................................................................................


-5-13 174 .............................................................................................
-6-13 175 .........................................................................................................................................................................
-7-13 176 .................................................................................................................................................................
-8-13 177 ......................................................................................................................................................................


179 .......................................................................................................................
-1-14 180 ................................................................................................................................................
181 ................................................................................................................................................... printTime -2-14
-3-14 182 ................................................................................................................................................................
-4-14 183 .................................................................................................................................................
-5-14 184 .............................................................................................................................................
-6-14 185 ................................................................................................................................................
-7-14 186 ........................................................................................................................................... Point
-8-14 187 ..............................................................................................................................................
-9-14 189 ................................................................................................................................................................
-10-14191 ....................................................................................................................................................................

193...................................................................................................................
-1-15 194 ........................................................................................................................................................................
-2-15 194 ........................................................................................................................................................... Card
-3-15 __196 .......................................................................................................... __str
-4-15 197 ........................................................................................................................................................
-5-15 198 ..........................................................................................................................................................
-6-15 199 ...............................................................................................................................................
-7-15 201 ............................................................................................................................................
-8-15 202 ..........................................................................................................................................

-9-15 203 ......................................................................................................................................................................


205 ........................................................................................................................................
-1-16 206 ..........................................................................................................................................................................
-2-16 206 .......................................................................................................................................................
-3-16 208 ...........................................................................................................................................................
-4-16 209 .............................................................................................................................................
-5-16 210 .......................................................................................................................................... CardGame
-6-16 211 ................................................................................................................................ OldMaidHand
-7-16 212 ............................................................................................................................... OldMaidGame
-8-16 216 .......................................................................................................................................................................

219

219 ...................................................................................................................

-1-17 220 ........................................................................................................................................................


-2-17 220 ......................................................................................................................................................... Node
-3-17 222 ....................................................................................................................................
-4-17 223 ..................................................................................................................................................
-5-17 224 ................................................................................................................................................
-6-17 225 ...................................................................................................................................................
-7-17 226 ................................................................................................................................................
-8-17 227 ...................................................................................................................................
-9-17 228 ................................................................................................................................... LinkedList
-10-17 229 .................................................................................................................................................................
-11-17230 ....................................................................................................................................................................


233....................................................................................................................................
-1-18 234 ..................................................................................................................................................

-2-18 235 ...........................................................................................................................................................................


-3-18 235 .............................................................................................................
-4-18 236 ................................................................................................................
-5-18 237 ............................................................................................. postfix
-6-18238 ..........................................................................................................................................................................
-7-18 238 .................................................................................................................................. postfix
-8-18 239 ...........................................................................................................................................
-9-18 240 ......................................................................................................................................................................

243 ......................................................................................................................................

ADT -1-19 244 ................................................................................................................................................................


-2-19 244 .............................................................................................................................................................
-3-19 246 ...................................................................................................................................................
-4-19 246 ........................................................................................................................................
-5-19 248 ...............................................................................................................................................................
-6-19 250 .................................................................................................................................................. Golfer
-7-19 251 ......................................................................................................................................................................

253..................................................................................................................................

-1-20 255 ......................................................................................................................................................


-2-20 256 ....................................................................................................................................................
-3-20 256 ...................................................................................................................................................
-4-20 257 .......................................................................................................................................................
-5-20 259 ....................................................................................................................................
-6-20 263 .....................................................................................................................................................
-20-7 264 .........................................................................................................................................................
-8-20 266.......................................................................................................................................................................

269 ..................................................................................................................
-1-21 270 ......................................................................................................................................................................
-2-21 271 ...............................................................................................................................................
-3-21 274 .................................................................................................................................................
-4-21 274 .......................................................................................................................................................
275 .............................................................................................................................................................. lambda -5-21
-6-21 277 ....................................................................................................................................................
-7-21 278 .............................................................................................................................................
-8-21 281 ..................................................................................................................................................................
-9-21 285 .....................................................................................................................................
-10-21 286 ....................................................................................................................................................
-11-21 else 287 ...................................................................................................................................
-12-21289 ....................................................................................................................................................................

291 ..............................................................................................
-1- 292 ........................................................................................................................................ IDLE
-1-1- 292 ........................................................................................................................... IDLE
-2-1- 293 ............................................................................................................... Python Shell
-3-1- 294 ...........................................................................................................................................................
-4-1- 294 .......................................................................................................................................................
-5-1- 295 ........................................................................................................................................................
-6-1- 295 .............................................................................................................................................
-7-1- 296 .........................................................................................................................
-8-1- 297 .................................................................................................................................
-1-8-1- 298 ..........................................................................................................................................
-2-8-1- 299 ..................................................................................................................................
-3-8-1- 300 .............................................................................................................................................

-9-1- 300 ................................................................................... Find/Replace


-10-1- )301 ......................................................................................... (Path Browser
302 ........................................................................................................................................................ PythonWin -2-
-1-2- 302 ......................................................................................................................................................
-2-2- 303 .................................................................................................................................................


305 .............................................................................................................
-1- 306 ..........................................................................................................................................................
-2- 306 ....................................................................................................................................................................
-3- 307 .......................................................................................................................................................
-4- 310 .........................................................................................................................................................
-5- - 310 ........................................................................................................................................
-6- 311 ...................................................................................................................................................

313 ..........................................................................................................................

.
.
)
( .
.
.
.
.
.
.
.
.
-1-1

C .

.

.
.
:
.
. .

.
.

.
.

.
.
:

.
. :

. : .

:
)Python 2.3 (#46, Jul 29 2003, 18:54:32
[MSC v.1200 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information
IDLE 1.0
>>> print 1+1
2

.
. >>>

. print 1+1 Enter


2 .

. .
latoya.py :
print 1+1

.py.
:
1

latoya.py

$ python
2

.
.
.
.

.
-2-1
.

. . ..

:
: .
-1 .
.

:
.

: .
: .
: .


:

.

.
-3-1
.
Bug Debugging
.
:
-1

-2

-3


.
-1-3-1

.
.
. " "this is a book.
.


. - -
.


.
-2-3-1

.
.
.
.
-3-3-1


. .
.


.
-4-3-1


.
.
.

.
.

.
:
.

.
.

.

Intel 80386 .
: AAAA
BBBB . .

.
-4-1

. . . .
.
.

.

. 3+3=6
3+=6$ H2O .
2zZ .

. .
3+=6$ ) $ ( . 2zZ
zZ .
.
3+=6$ =
+ .
.

.
.
.
. .
.
)
( :
:
.

)( :
.

: .

.
.

) ( .

.
.
.

.
-5-1
"Hello,aWorld!"


! Hello, World .
:
"!print "Hello, World


. :
!Hello, World

)(
.

"! "Hello,aWorld . .
-6-1
) problem solving (
.

10

) high-level language (

.
) low-level language (

.
) portable (
.
) interpret(
.
) compile (

.
) source code (
.
) object code (
.
) executable (
.
) script(
) (.
) program(
.

11

) algorithm(
.
) bug(
.
) debugging(
.
) syntax (
.
) syntax error (
) ( .
) runtime error (

.
) exception(
.
) semantic error (
.
) semantics(
.
) natural language (
.

12

) formal language (

. .
) token (
.
) parse(
.
) print statement (
.

14


.
.
.

.
-1-2

. ) 2 (1+1
.

"!"Hello,aWorld

2 .

"! "Hello,aworld . )
( . ) (
)"( )'( .
:
>>> print 4
4

:
)"!>>> type("Hello, World
>'<type 'string
)>>> type(17
>'<type 'int

str int . )
( float
.

)>>> type(3.2
>'<type 'float

15

" "17 " "3.2


.
)">>> type("17
>'<type 'str
)">>> type("3.2
>'<type 'str

.

') ',( .1,000,000
:
>>> print 1,000,000
1 0 0

. 1,000,000
.
.
-2-2
.
.

:
"?>>> message = "What's up, Doc
>>> n = 17
>>> pi = 3.14159

. "? "What'saupaDoc
message . 17 n
3.14159 pi.

16

.
. 1-2 .
"?"What's up, Doc

message

17

3.14159

pi

1-2

.
>>> print message
?What's up, Doc
>>> print n
17
>>> print pi
3.14159

.
.
)>>> type(message
>'<type 'str
)>>> type(n
>'<type 'int
)>>> type(pi
>'<type 'float

.
-3-2
.
.

17

.
.
.
) ( Bruce . bruce .
) _ ( .
my_name . price_of_tea_in_china
:
">>> 76trombones = "big parade
SyntaxError: invalid syntax
>>> more$ = 1000000
SyntaxError: invalid syntax
">>> class = "Computer Science 101
SyntaxError: invalid syntax

76trombones more$ .
) ($ . class

class .

.
28 :
raise
return
try
while

not
or
pass
print

import
in
is
lambda

for
from
global
if

else
except
exec
finally

continue
def
del
elif

and
assert
break
class

.

.
-4-2
.
: .

18


.
.
.
.
:
print 1
x = 2
print x

:
1
2

.
-5-2

>>> 1 + 1
2

.
>>> 17
17
>>> x
2

.
"?>>> message = "What's up, Doc
>>> message
"?"What's up, Doc
>>> print message
?What's up, Doc

19


.
print .

.
:
17
3.2
"!"Hello, World
1 + 1

.

-6-2

.
:
)(5+9)*(15-7

5**2

minute/60

hour*60+minute

hour-1

20+32

- + /
. )*( )**(
.

.

. :
>>> minute = 59
>>> minute/60
0

20

minute 59 . 59 60 0.98333

. .



) (1 .
:
>>> minute*100/60
98

.
.
-7-2

.
.
PEMDAS .
:
Subtraction

Addition

Division

Multiplication

Exponentiation

Parentheses


. 2*(3-
) 1 4 ) (1+1)**(5-2 8 .
. (minute*100)/60
.
2**1+1 3
4 3*1**3 3 . 27

21

.
2*3-1 5 4
2/3-1 1 ) 1 . (2/3=0

minute*100/60 5900/60
98 .
59*1 59 .
-8-2

. ) message (:
message-1

"Hello"/123

"message*"Hello

"15"+2

. + .
. :
"fruit = "banana
"bakedGood = " nut bread
print fruit + bakedGood

banana nut bread . nut


.
* . '3*'Fun
' 'FunFunFun .
.
+* .
3*4 4+4+4 ' 3*'Fun ' 'Fun'+'Fun'+'Fun
.
.

22

-9-2

.
:
>>> print 17 + 3
20


.
. .
print "Number of minutes since midnight: ", hour*60+minute

:
percentage = (minute * 100) / 60


.
: .
:
. minute+1 = hour
-10-2
.

.
.

# :

23

# compute the percentage of the hour that has elapsed


percentage = (minute * 100) / 60

.
:
# caution: integer

percentage = (minute * 100) / 60


division

#
.
.
.
-11-2
) value(

) (
.

) type(
. .
) (int ) (float
) .(str
) floating-point (
.
) variable(
.

24

) statement (
.
.
) assignment(

.
) state diagram (
.
) keyword (

while def if . . .
.
) expression(
.
) evaluate(
.
) operator(
.
) operand(
.
) integer division (

.
.

25

) rules of precedence (

.
) concatenate(
.
) composition(

.
) comment(
)
( .

28


.

.
.
.
.

.
-1-3
:
)">>> type("32
>'<type 'str

type .

.
. .

:
)">>> betty = type("32
>>> print betty
>'<type 'str

id .
:
)>>> id(3
134882108
>>> betty = 3
)>>> id(betty
134882108

29

id . id
id . id .
-2-3

. int
:
)">>> int("32
32
)">>> int("Hello
ValueError: invalid literal for int(): Hello

int
:
)>>> int(3.99999
3
)>>> int(-2.3
-2

float :
)>>> float(32
32.0
)">>> float("3.14159
3.14159

str :
)>>> str(32
''32
)>>> str(3.14149
''3.14149

1
.
. .
1.0

30

-3-3

.
. minute/60
59 !
minute
:
>>> minute = 59
>>> float(minute) / 60.0
0.983333333333

.
:

>>> minute = 59
>>> minute / 60.0
0.983333333333


.
-4-3
sin log
) sin(pi/2 ) log(1/x . )(
. pi/2 1.571 1/x x 10.0
0.1.
.
1.571 1 ) 0.1 (10 1.

31

)) log(1/sin(pi/2
.
.

math .

.

import :
>>> import math

. .

)>>> decibel = math.log10 (17.0


>>> angle = 1.5
)>>> height = math.sin(angle

17 10 decibel .
log ) e ( .
angle sin .
) cot tan ( .
180 pi . 45
:
>>> degrees = 45
>>> angle = degrees * math.pi / 180
)>>> math.sin(angle

pi math .
2 2:
>>> math.sqrt(2) / 2.0
0.707106781187

32

-5-3

. .
.
.

Enter ) (
.
.
. .py

.

.
.
from...import
. :
from MODULE import NAME1, NAME2, NAME3,

cos exp :
from math import cos, exp

) (
* :
* >>> from math import

math )
)( ( .

33

-6-3
.
.
:
)>>> x = cos(angle + pi/2

pi 2 angle
cos.

:
))>>> x = exp(log(10.0

10 e e .
x .
-7-3

.
.

. .
.
.
:
def NAME( LIST OF PARAMETERS ):
STATEMENTS


. ) (LIST OF PARAMETERS
) ( .

34

.
2.
.
:
def newLine():
print

newLine .
) .
print (
:
"print "First Line.
)(newLine
"print "Second Line.

:
First line.
Second line.

.
:
"print "First Line.
)(newLine
)(newLine
)(newLine
"print "Second Line.

threeLines :

indent-2

35

def threeLines():
)(newLine
)(newLine
)(newLine
"print "First Line.
)(threeLines
"print "Second Line.

.
.
:
.1 .
.
.2 .
threeLines newLine .
.
:

.
) ( .
.
threeLines
.

:1-3 nineLines threeLines


. 27

36

-8-3
6-3 :
def newLine():
print
def threeLines():
)(newLine
)(newLine
)(newLine
"print "First Line.
)(threeLines
"print "Second Line.

threeLines : . newLine

.
.
.
.

:2-3 .
.
.
:3-3 newLine
threeLines .

-9-3

37

.
.
.
.
.

.

.
. .
.
.
.

.
-10-3

.
. sin
.
. pow
.
.
- :
def printTwice(bruce):
print bruce, bruce

38

bruce .
) ( . bruce
.
.
printTwice :
)'>>> printTwice('Spam
Spam Spam
)>>> printTwice(5
5 5
)>>> printTwice(3.14159
3.14159 3.14159


.
-
. printTwice :
)>>> printTwice('Spam'*4
SpamSpamSpamSpam SpamSpamSpamSpam
))>>> printTwice(math.cos(math.pi
-1.0 -1.0

.
-SpamSpamSpamSpam-SpamSpamSpamSpama 'Spam'*4-
'Spam'*4 . printTwice 'Spam'*4
SpamSpamSpamSpam .
printTwice .

:

printTwice

"!>>> state1 = "Don't worry


>>> print state1
!Don't worry
'>>> state2 = '"Mr. Rossum", has created Python.
"Mr. Rossum", has created Python.

printTwice :4-3

39

'Spam'*4-'Spam'*4

:
'>>> michael = 'Eric, the half a bee.
)>>> printTwice(michael
Eric, the half a bee. Eric, the half a bee.

.
) (michael ) (bruce .
printTwice bruce
.
-11-3

. :
def catTwice(part1, part2):
cat = part1 + part2
)printTwice(cat

) ( )
( .
:
" >>> chant1 = "Pie Jesu domine,
">>> chant2 = "Dona eis requiem.
)>>> catTwice(chant1, chant2
Pie Jesu domine, Dona eis requiem. Pie Jesu domine, Dona eis
requiem.

catTwice cat .
:

40


>>> print cat
Traceback (most recent call last):
? File "<interactive input>", line 1, in
NameError: name 'cat' is not defined

printTwice bruce

.
.
-12-3

.

.

.
:
""Pie Jesu domine,
""Dona eis requiem.

__main__ chart1
chart2

""Pie Jesu domine,

part1

""Dona eis requiem.

part2

""Pie Jesu domine, Dona eis requiem.

cat

""Pie Jesu do mine, Dona eis requiem.

bruce

catTwice

printTwice

1-3

. printTwice
catTwice catTwice __ __main
.
__ __main .

41

. part1 chant1
part2 chant2 . bruce cat.

__ __main .
printTwice cat
NameError :
Traceback (innermost last):
__File "test.py", line 13, in __main
)catTwice(chant1, chant2
File "test.py", line 5, in catTwice
)printTwice(cat
File "test.py", line 9, in printTwice
print cat
NameError: cat

.
.
.
. .
-13-3

. newLine
. :
)
(.
.3
newLine() + 7
.4
newLine printTwice
.

42

:5-3 .
.
-14-3
) function call (

.
) argument(
.
.
) return value (
.
.
) type conversion (

.
) type coercion (
.
) module(
.
) dot notation (

.

43

) function(
.
.
.
) function definition (
.
) flow of execution (

) parameter(

.
) local variable (
. .
) stack diagram (
.
) frame(
.
.
) traceback(
.

46


.

.
.
.

.
.
-1-4
) (
. ) (%
. :
quotient = 7 / 3
print quotient
remainder = 7 % 3
print remainder

>>>
>>>
2
>>>
>>>
1

7 3 2 1.

. . x%y
x y .
.
x%10 ) x (10 x%100
x .

47

-2-4

) (true ) (false .

1 0 .
== :
>>> 5 == 5
1
>>> 5 == 6
0

(true) 1
5 6 (false) 0.
== . :
x y x y
x y
x y
x y
x y

x != y
x > y
x < y
x >= y
x <= y


. = == .
= == . =>
) ( =< ) (
>= <= .
-3-4
or and : .not
. x > 0 and x < 10 x

48

n%2 == 0 or n%3 == 0 .

2 3 .

not x > y
x y not(x > y) .

. true .
x = 5
x and 1
y = 0
y and 1

>>>
>>>
1
>>>
>>>
0

.
0 .
-4-4

. .
if:
if x > 0:
"print "x is positive

if .
.

if

:
HEADER:
FIRST STATEMENT
...
LAST STATEMENT

49

) (Header ) (: .
.
. ) (

if
. )
( .
pass .
-5-4
if
. :
if x%2 == 0:
"print x, "is even
else:
"print x, "is odd

x 2 x
. .
true false .

.

. :
def printParity(x):
if x%2 == 0:
"print x, "is even
else:
"print x, "is odd

printParity x .
:

50


)>>> printParity(17
17 is odd
>>> y=21
)>>> printParity(y+1
22 is even

-6-4
.

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':
)(functionA
elif choice == 'B':
)(functionB
elif choice == 'C':
)(functionC
else:
"print "Invalid choice.

. false
.
.
.

:1-4
.

) compare(x,y )dispatch(choice

51

-7-4

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

.
.
.
:
if 0 < x:
if x < 10:
"print "x is a positive single digit.

print .
and :
if 0 < x and x < 10:
"print "x is a positive single digit.

.
:
if 0 < x < 10:
"print "x is a positive single digit.

52

-8-4 return
return
. :
import math
def printLogarithm(x):
if x <= 0:
"print "Positive numbers only, please.
return
)result = math.log(x
print "The log of x is", result

printLogarithm x .
x 0
return .
. math
import.
-9-4

.
.

. :
def countdown(n):
if n == 0:
"!print "Blastoff
else:
print n
)countdown(n-1

countdown n . n
! Blastoff n countdown

53

)( n-1 .

)>>> countdown(3

countdown n=3 n 3
. . .
countdown n=2 n 2
. . .
countdown n=1 n 1
. . .
countdown n=0 n 0
! Blastoff .
countdown n=1 .
countdown n=2 .
countdown n=3 .
__ __main ) !!( .
:
3
2
1
!Blastoff

newLine threeLines :
def newline():
print
def threeLines():
)(newLine
)(newLine
)(newLine

2 106
. :

54


def nLines(n):
if n > 0:
print
)nLines(n-1

countdown n 0
n-1 .
) 1+(n-1 n
!

.
-10-4
11-3
. .

. .
1-4 countdown n=3
:
____main
3

countdown

countdown

countdown

countdown

1-4

__ __main .
__ __main . countdown
n . n=0 .
.

55

:2-4 nLines n=4 .


-11-4

.
.
:
def recurse():
)(recurse


. :
File "<stdin>", line 2, in recurse
) (
File "<stdin>", line 2, in recurse
RuntimeError: Maximum recursion depth exceeded

.
.
98 .

:3-4 .
-12-4

. .
. raw_input .
.
Enter raw_input
:

56


)( >>> input = raw_input
?What are you waiting for
>>> print input
?What are you waiting for

raw_input

. .

raw_input

:
)" ?>>> name = raw_input ("What...is your name
!What...is your name? Cyrus, King of the World
>>> print name
!Cyrus, King of the World

input :
\prompt = "What...is the airspeed velocity of an unladen
"swallow?\n
)speed = input(prompt

\
. .

speed .
:
)>>> 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

raw_input
.

57

-13-4
) modulus operator (
) (% .
.
) boolean expression (
) (true ) (false.
) comparison operator (
<= , == ,!= ,< ,> : =>

) logical operator (
. ) (: .
.
) conditional statement (
.
) condition(
.
) compound statement (
. ) (:
.
) block(
.
) body(
.

58

) branches(
.
) nested(

.
) recursion(
) (.
) base case (

.
) infinite recursion (
.
.
) prompt(
.

60


. .

.
.
-1-5

.
.
)e = math.exp(1.0
)height = radius * math.sin(angle


. :
import math
def area(radius):
temp = math.pi * radius**2
return temp

return return

. :
. .
:
def area(radius):
return math.pi * radius**2

temp .
return :

61

def absoluteValue(x):
if x < 0:
return -x
else:
return x

return
. .
) return (
.


return . :
def absoluteValue(x):
if x < 0:
return -x
elif x > 0:
return x

x
return . None
:
)>>> print absoluteValue(0
None

:1-5 compare 1 x>y 0 x==y

x<y -1 .

-2-5
.
.

.

62


.
.
) (x1, y1
) (x2, y2 . :
)

( ) +

= distance

distance
. )( ) (
.

.
:
def distance(x1, y1, x2, y2):
return 0.0


.
.
:
)>>> distance(1, 2, 4, 6
0.0

3 4
5 ) .(3-4-5
.

. .
- . -

63

x2 - x1 y2 - y1 .
dx dy :
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
print "dx is", dx
print "dy is", dy
return 0.0

3 ) 4 (0.0 .

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

) 25( .
math sqrt
.
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
)result = math.sqrt(dsquared
return result

. result
return .

64


.
.
.
:
.
.
.5 .
.
.6
.

:2-5 hypotenuse

. )
( . .
-3-5

. .


.
xc yc
xp yp .
. distance :
)radius = distance(xc, yc, xp, yp

65

)result = area(radius
return result

:
def area2(xc, yc, xp, yp):
)radius = distance(xc, yc, xp, yp
)result = area(radius
return result

area2 ) area (
. .
radius result
:
def area2(xc, yc, xp, yp):
))return area(distance(xc, yc, xp, yp

:3-5 ) slope(x1, y1, x2, y2

) (x1 ,y1 ) (x2 ,y2 .


) intercept(x1, y1, x2, y2
.
-4-5

. :
def isDivisible(x, y):
if x % y == 0:
return 1
# it's true
else:
return 0
# it's false

66

isDivisible .
/ . isDivisible 1 0
x y .
if
if :
def isDivisible(x, y):
return x % y == 0

:
)>>> isDivisible(6, 4
0
)>>> isDivisible(6, 3
1

:
if isDivisible(x, y):
"print "x is divisible by y
else:
"print "x is not divisible by y

if :
if isDivisible(x, y) == 1:

.
:4-5 ) isBetween(x, y, z x y z

1 0 .
-5-5


.
.
) .

67

. . . .
!(
)
.
( .
.
.

.
.
. :
:frabjuous frabjuous !
.
:
0! = 1
!)n! = n *(n-1

1 0 n n
.n-1 ! 3 3 ! 2 2 ! 1 1 ! 0.
6.

. .
factorial :
def factorial(n):

0 1 :
def factorial(n):
if n == 0:
return 1

68

) (
n-1 n :
def factorial(n):
if n == 0:
return 1
else:
)recurse = factorial(n-1
result = n * recurse
return result

countdown 9-4 .
3 :
3 0 n-1.
2 0 n-1
.
1 0
n-1.
0 0
1 .
) ( 1 n 1
.
) ( 1 n 2 .
) ( 2 n 3 6 .
.
1-5
:
____main
6

return

recurse

factorial

return

recurse

factorial

return

recurse

factorial

factorial

1-5

69

.
result n recurse .
recurse result .
-6-5

. .
.
.

. math.cos math.exp
.
.
.
4-5 isDivisible
. ) (
.
.
) (
: n-1 n
n .

!
-7-5

:

70


def factorial(n):
if n == 0:
return 1
else:
)return n * factorial(n-1


.
.
fibonacci
:
fibonacci(0) = 1
fibonacci(1) = 1
)fibonacci(n) = fibonacci(n-1) + fibonacci(n-2

:
def fibonacci (n):
if n == 0 or n == 1:
return 1
else:
)return fibonacci(n-1) + fibonacci(n-2

n


.
-8-5
factoial 1.5
)>>> factorial (1.5
RuntimeError: Maximum recursion depth exceeded

71


n==0 . n .
n 0.5 . n 0.5
.
factorial
factorial .
. .
type ) (1
.
:
def factorial (n):
if type(n) != type(1):
"print "Factorial is only defined for integers.
return -1
elif n < 0:
"print "Factorial is only defined for positive integers.
return -1
elif n == 0:
return 1
else:
)return n * factorial(n-1

. )
( .
1 :
)">>> factorial ("fred
Factorial is only defined for integers.
-1
)>>> factorial (-2
Factorial is only defined for positive integers.
-1

n
.

72

.
.
.
-9-5
) fruitful function (
.
) return value (
.
) temporary variable (
.
) dead code (

return .
None

return return
None .
) incremental development (

.
) scaffolding(
.
) composition(
.

) guardian(
.

73

76

.

.

.


.
-1-6
.
)
(.
= 5
bruce,
= 7
bruce

bruce
print
bruce
print

5 7 bruce 5
. 7 print

.
:
5
bruce
7

1-6


)=(
a = b .

77

.
7 = a a = 7 7 = a .
. aa=ab
a b .
:

aa=a7

a = 5
b = a # a and b are now equal
a = 3 # a and b are no longer equal

a b
) .
<- =(. :
.
.
-2-6 while
nLines countdown

. .
.
while.
countdown while:
def countdown(n):
while n > 0:
print n
n = n-1
"!print "Blastoff

.
while .
n > 0 n 1 . n
0 ! Blastoff .

78

while :
0 1
.7 (0) false while .
.8 (1) true 1.

. false
.
false

.
.
countdown n
0
. :

# n is even
# n is odd

def sequence(n):
while n != 1:
print n,
if n%2 == 0:
n = n/2
else:
n = n*3+1

n != 1 n 1
false.
n
. n 2
n*3+1 . ) sequence
( 3 :
3 10 5 16 8 4 2 1

79

n n
1 . n .
2 n 1
. 16
) n == 1(.

n .

:1-6 nLines 9-4


.
-3-6
.

.
.
.
: !
. .
.

.
.
.

.
:
x = 1.0
while x < 10.0:
)print x, '\t', math.log(x
x = x + 1.0

' '\t tab .

80

.
print .
tab tab stop .
tab stop . tab
. :
0.0
0.69314718056
1.09861228867
1.38629436112
1.60943791243
1.79175946923
1.94591014906
2.07944154168
2.19722457734

1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0

log
. 2
2 . :
e

:
)print x, '\t', math.log(x)/math.log(2.0

:
0.0
1.0
1.58496250072
2.0
2.32192809489
2.58496250072
2.80735492206
3.0
3.16992500144

1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0

81

4 2 1 8 2 2
.
2
:
x = 1.0
while x < 100.0:
)print x, '\t', math.log(x)/math.log(2.0
x = x * 2.0

x
x .
:
0.0
1.0
2.0
3.0
4.0
5.0
6.0

1.0
2.0
4.0
8.0
16.0
32.0
64.0

tab
.
2 .

:2-6 2 (216) 65536.


.

)\( ' '\t .


tab )
' '\n (.
.
tab .
'\'

82

:3-6 :
Python
is a
programming language.

-4-6
.
. 1 6
.
2
:
i = 1
while i <= 6:
print 2*i, ' ',
i = i + 1
print

i .
print 2*i
. print .
print .
:
12

10

. .
-5-6

. :
printParity 5-4 isDivisible . 4-5
2
.

83

n :
def printMultiples(n):
i = 1
while i <= 6:
print n*i, '\t',
i = i + 1
print


.
2 n.
2
3 :
18

15

12

4 :
24

20

16

12


printMultiples
:
i = 1
while i <= 6:
)printMultiples(i
i = i + 1

printMultiples .
print .
:
6
12
18
24
30
36

5
10
15
20
25
30

4
8
12
16
20
24

3
6
9
12
15
18

2
4
6
8
10
12

1
2
3
4
5
6

84

-6-6
5-6
:
def printMultTable():
i = 1
while i <= 6:
)printMultiples(i
i = i + 1

.
.
.

.
.
-7-6
i
printMultiples printMultTable .

I printMultiples I printMultTable
.
.
.
i .
.

1
2

1
2
3

printMultTable

printMultiples
i

2-6

85

i printMultTable 1 6 .
3 . 4 .
printMultTable printMultiples i
. n .
printMultiples i 1 6 .
2 . i
printMultTable.
.
i j .

.
-8-6

.
printMultTable :
def printMultTable(high):
i = 1
while i <= high:
)printMultiples(i
i = i + 1

6 high . printMultTable
:
6
12
18
24
30
36
42

5
10
15
20
25
30
35

4
8
12
16
20
24
28

3
6
9
12
15
18
21

2
4
6
8
10
12
14

1
2
3
4
5
6
7

86

-
. printMultiples
.
high
) ( .
:
def printMultiples(n, high):
i = 1
while i <= high:
print n*i, '\t',
i = i + 1
print
def printMultTable(high):
i = 1
while i <= high:
)printMultiples(i, high
i = i + 1

) (
)
(printMultTable .
:
7
14
21
28
35
42
49

6
12
18
24
30
36
42

5
10
15
20
25
30
35

4
8
12
16
20
24
28

3
6
9
12
15
18
21

2
4
6
8
10
12
14

1
2
3
4
5
6
7


.
ab=ba .
!
printMultiples .

87

) printMultiples(i,ahigh )printMultiples(i,ai

49

36
42

25
30
35

16
20
24
28

9
12
15
18
21

4
6
8
10
12
14

1
2
3
4
5
6
7

:4-6 printMultTable

.
-9-6

.
. :

.


.
.
.
.
-10-6
) multiple assignment (
.

88

) iteration(
.
) loop(

.
) infinite loop (
.
tab

) cursor(
.
) escape sequence (
/
.
) newline (
.
) loop variable (
.
) encapsulate(

) (.

89

) generalize(
) (
) ( .
.
) development plan (
.
.

92


.
.
.
.
.
-1-7
float int : ) string
( .
.
.

. .
:
">>> fruit = "banana
]>>> letter = fruit[1
>>> print letter

] fruit[1 1 fruit . letter


. letter :
a

" 'a' "banana .


. ""banana
' 'b ' 'a '.'n
0 0
:
]>>> letter = fruit[0
>>> print letter
b

93

.
.
.
-2-7
len :
">>> fruit = "banana
)>>> len(fruit
6

!# ERROR

)length = len(fruit
]last = fruit[length

:
IndexError: string index out of range

" "banana .
0 5 .
length :
)length = len(fruit
]last = fruit[length-1


. ] fruit[-1 fruit[-2]
.
-3-7 for
.

94

. .
while:
index = 0
while index < len(fruit):
]letter = fruit[index
print letter
index = index + 1

.
) index < len(fruit index
false .
len(fruit)-1 .

:1-7


:
for char in fruit:
print char

char
.
-
- for .
Mack Lack Kack Jack
Pack OuackaNack Quack . :
"prefixes = "JKLMNOPQ
"suffix = "ack
for letter in prefixes:
print letter + suffix

95

:
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

" "Ouack " "Quack


.

:2-7 .
-4-7
. :
">>> s = "Peter, Paul, and Mary
]>>> print s[0:5
Peter
]>>> print s[7:11
Paul
]>>> print s[17:21
Mary

] [n:m n m
n m . .
. 1-7 :

""banana
5 6

0 1 2 3 4

fruit
index

1-7

) (
. :

96


">>> fruit = "banana
]>>> fruit[:3
''ban
]>>> fruit[3:
''ana

] s[:
-5-7
:

if word == "banana":
"!print "Yes, we have no bananas

:
if word < "banana":
"print "Your word," + word + ", comes before banana.
elif word > "banana":
"print "Your word," + word + ", comes after banana.
else:
"!print "Yes, we have no bananas


. . :
Your word, Zebra, comes before banana.

.
.
!
-6-7
][
. :

!# ERROR

97

"!greeting = "Hello, world


'greeting[0] = 'J
print greeting

! jello,aworld
TypeError: object doesn't support item assignment.

.

:
"!greeting = "Hello, world
]newGreeting = 'J' + greeting[1:
print newGreeting

greeting .
.
-7-7 find

def find(str, ch):
index = 0
while index < len(str):
if str[index] == ch:
return index
index = index + 1
return -1

find ][ .
.
1 .
return .
str[index] == ch .
1 .

98

3eureka
.

:3-7 find

-8-7
' 'a :
"fruit = "banana
count = 0
for char in fruit:
if char == 'a':
count = count + 1
print count

.
' 'a .
count ' 'a.

:4-7 counterLetter
.
:5-7
find .
-9-7 string
string .
:
>>> import string

-3

99

string find .
:
">>> fruit = "banana
)">>> index = string.find(fruit, "a
>>> print index
1

.
- .
find .
string.find .
:
)">>> string.find("banana", "na
2

)>>> string.find("banana", "na", 3


4

:
)>>> string.find("bob", "b", 1, 2
-1

b 1 2 )
2 (.
-10-7

. string .

100

string.lowercase
. string.uppercase .
:
>>> print string.lowercase
>>> print string.uppercase
>>> print string.digits

find .
) find(lowercase, ch 1 ch
:
def isLower(ch):
return string.find(string.lowercase, ch) != -1

in

def isLower(ch):
return ch in string.lowercase

. :
def isLower(ch):
'return 'a' <= ch <= 'z

ch a z .

:6-7 .

string :
>>> print string.whitespace

101

.
. string.whitespace
(\t) tab space ) (\n.
-11-7
) compound data type (
.

) index(

.
) traverse(
.
) slice(
.
) immutable(
.
) counter(
.
) whitespace(
.
string.whitespace .

104

.
.
. .


. .
- -
. -
.
-1-8

)] [( :
][10, 20, 30, 40
]"["spam", "bungee", "swallow

.
.
) ( :
]]["hello", 2.0, 5, [10, 20

) .
(

:
)>>> range(1,5
][1, 2, 3, 4

105

range
.
.
range .
:
)>>> range(10
][0, 1, 2, 3, 4, 5, 6, 7, 8, 9


. 1 10 2:
)>>> range(1, 10, 2
][1, 3, 5, 7, 9

.
][ .

.
]"vocabulary = ["ameliorate", "castigate", "defenestrate
]numbers = [17, 123
][ = empty
print vocabulary, numbers, empty
][ ]['ameliorate', 'castigate', 'defenestrate'] [17, 123

-2-8

)][( . 0
:
]print numbers[0
numbers[1] = 5

106

.
numbers
123 5.
:
]>>> numbers[3-2
5
]>>> numbers[1.0
TypeError: sequence index must be integer


:
>>> numbers[2] = 5
IndexError: list assignment index out of range

:
]>>> numbers[-1
5
]>>> numbers[-2
17
]>>> numbers[-3
IndexError: list index out of range

] numbers[-1 ] numbers[-2
] numbers[-3 .
:
]"horsemen = ["war", "famine", "pestilence", "death
i = 0
while i < 4:
]print horsemen[i
i = i + 1

107

while 0 4 . i 4
. i 2 1 0 3
.
i i

. .
-3-8

len .
.
. :
]"horsemen = ["war", "famine", "pestilence", "death
i = 0
while i < len(horsemen):
]print horsemen[i
i = i + 1

i len(horsemen)-1
. i ) len(horsemen
. ) len(horsemen .
)(
. :
]]['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3

:1-8 .
len
-4-8
in .
10-7 :

108


]'>>> horsemen = ['war', 'famine', 'pestilence', 'death
>>> 'pestilence' in horsemen
1
>>> 'debauchery' in horsemen
0

pestilence horsemen in
debauchery in false .
not in
:
true

>>> 'debauchery' not in horsemen


1

-5-8 for
for 3-7 .
for :
for VARIABLE in LIST:
BODY

:
i = 0
while i < len(LIST):
]VARIABLE = LIST[i
BODY
i = i + 1

for i .
for:
for horseman in horsemen:
print horseman

: )( horseman )(
) horsemen( horseman .

109

for :
for number in range(20):
if number % 2 == 0:
print number
for fruit in ["banana", "apple", "quince"]:
"!print "I like to eat " + fruit + "s

0 19 .
.
-6-8
+ :
]a = [1, 2, 3
]b = [4, 5, 6
c = a + b
print c
]2, 3, 4, 5, 6

>>>
>>>
>>>
>>>
[1,

* :
[0] * 4
]0, 0, 0
[1, 2, 3] * 3
]2, 3, 1, 2, 3, 1, 2, 3

>>>
[0,
>>>
[1,

] [0 4 ] [1,2,3 3 .
-7-8
4-7 :
]'>>> list = ['a', 'b', 'c', 'd', 'e', 'f
]>>> list[1:3
]'['b', 'c
]>>> list[:4
]'['a', 'b', 'c', 'd
]>>> list[3:

110


]'['d', 'e', 'f
]>>> list[:
]'['a', 'b', 'c', 'd', 'e', 'f

-8-8
.
:
]">>> fruit = ["banana", "apple", "quince
">>> fruit[0] = "pear
">>> fruit[-1] = "orange
>>> print fruit
]'['pear', 'apple', 'orange

:
]'>>> list = ['a', 'b', 'c', 'd', 'e', 'f
]'>>> list[1:3] = ['x', 'y
>>> print list
]'['a', 'x', 'y', 'd', 'e', 'f


:
]'>>> list = ['a', 'b', 'c', 'd', 'e', 'f
][ = ]>>> list[1:3
>>> print list
]'['a', 'd', 'e', 'f


:
]'>>> list = ['a', 'd', 'f
]'>>> list[1:1] = ['b', 'c
>>> print list
]'['a', 'b', 'c', 'd', 'f
]'>>> list[4:4] = ['e
>>> print list
]'['a', 'b', 'c', 'd', 'e', 'f

111

-9-8
.
.
del :
]'>>> a = ['one', 'two', 'three
]>>> del a[1
>>> a
]'['one', 'three

) (
.
-10-8
:
"a = "banana
"b = "banana

a b " "banana
. :
a

""banana

""banana

""banana

1-8

a b

. .

.
id .
a b :

112


)>>> id(a
135044008
)>>> id(b
135044008

.
a b .
.
:
]>>> a = [1, 2, 3
]>>> b = [1, 2, 3
)>>> id(a
135045528
)>>> id(b
135041704
] [ 1, 2, 3

] [ 1, 2, 3

2-8

:
a b .
-11-8

:
]>>> a = [1, 2, 3
>>> b = a

3-8:
a
] [ 1, 2, 3
b

3-8

113

a b .
:
>>> b[0] = 5
>>> print a
][5, 2, 3

.
.
.
.
-12-8

) ( .

:
]a = [1, 2, 3
]b = a[:
print b
]2, 3

>>>
>>>
>>>
[1,

a .
.
a b :
>>> b[0] = 5
>>> print a
][1, 2, 3

:2-8 a b .

114

-13-8

. head :
def head(list):
]return list[0

:
]>>> numbers = [1, 2, 3
)>>> head(numbers
1

list numbers .

numbers

____main

list

head

] [ 1, 2, 3

4-8

:
.
.
deleteHead :
def deleteHead(list):
]del list[0

:
]numbers = [1, 2, 3
)deleteHead(numbers
print numbers
]3

>>>
>>>
>>>
[2,

115

. tail
:
def tail(list):
]return list[1:

tail :
]numbers = [1, 2, 3
)rest = tail(numbers
print rest
]3

>>>
>>>
>>>
[2,


rest numbers .
-14-8
.
3 :
]]>>> list = ["hello", 2.0, 5, [10, 20

] list[3 [10, 20] .


:
]>>> elt = list[3
]>>> elt[0
10

:
]>>> list[3][1
20

)][(
.

116

-15-8
. :
3

:
]]>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9

matrix .
:
]>>> matrix[1
][4, 5, 6

:
]>>> matrix[1][1
5

.
.
. .
-16-8
string .
split .
:
>>> import string
">>> song = "The rain in Spain...
)>>> string.split(song
]'['The', 'rain', 'in', 'Spain...

117


. ' 'ai :
)'>>> string.split(song, 'ai
]'['The r', 'n in Sp', 'n...

.
join split .
:
]'>>> list = ['The', 'rain', 'in', 'Spain...
)>>> string.join(list
''The rain in Spain...

split join :
)'_' >>> string.join(list,
''The_rain_in_Spain...

:3-8 )) string.join(string.split(song song


.

-17-8
) list(
.
) element (
) ( . .
) sequence(

.

118

) nested list (
.
) list traversal (
.
) object(
.
) aliases(
.
) clone(
.
.
) delimiter(
) ( .

120

:
.
.

.
.
-1-9

.
:
'>>> tuple = 'a', 'b', 'c', 'd', 'e

:
)'>>> tuple = ('a', 'b', 'c', 'd', 'e

:
)>>> t1 = ('a',
)>>> type(t1
>'<type 'tuple

)' ('a :
)'>>> t2 = ('a
)>>> type(t2
>'<type 'string


. :

121

)'>>> tuple = ('a', 'b', 'c', 'd', 'e


]>>> tuple[0
''a

:
]>>> tuple[1:3
)'('b', 'c

:
'>>> tuple[0] = 'A
TypeError: object doesn't support item assignment


:
]>>> tuple = ('A',) + tuple[1:
>>> tuple
)'('A', 'b', 'c', 'd', 'e

-2-9
.
. a:b
>>> temp = a
>>> a = b
>>> b = temp

.
:
>>> a, b = b, a

.
.
. .

122

:
>>> a, b, c, d = 1, 2, 3
ValueError: unpack tuple of wrong size

-3-9
.
:
def swap(x, y):
return y, x

:
)a, b = swap(a, b

swap .
swap :
# incorrect version

def swap(x, y):


x, y = y, x

swap :
)swap(a, b

a x . x swap x
a __ __main . y
b.

. .

:1-9
.

123

-4-9

.
.
. .

.
.

. .
random random 0.0 1.0
. random
. :
import random
for i in range(10):
)(x = random.random
print x

0.0 x high high

:2-9 high low .


:3-9 low high
) ( .
-5-9
. randomList
. n

124

. .
:
def randomList(n):
s = [0] * n
for i in range(n):
)(s[i] = random.random
return s

.
:
)>>> randomList(8
[0.15156642489, 0.498048560109, 0.810894847068, 0.360371157682,
]0.275119183077, 0.328578797631, 0.759199803101, 0.800367163582

random .
.

.

.

-6-9

.

. 8-7
.
.
:

125

count = 0
for char in fruit:
if char == 'a':
count = count + 1
print count

fruit list char num .


.
. num
low high .
count = 0
for num in list:
if low < num < high:
count = count + 1
print count

inBucket . low list


high:
def inBucket(list, low, high):
count = 0
for num in list:
if low < num < high:
count = count + 1
return count

. .
.
-7-9
inBucket .
:
)low = inBucket(a, 0.0, 0.5
)high = inBucket(a, 0.5, 1

126

.
)0.0, 0.25
)0.25, 0.5
)0.5, 0.75
)0.75, 1.0

inBucket(a,
inBucket(a,
inBucket(a,
inBucket(a,

=
=
=
=

bucket1
bucket2
bucket3
bucket4


.
. numBuckets
1/numBuckets .
. i 1
numBuckets-1 :
bucketWidth = 1.0 / numBuckets
for i in range(numBuckets):
low = i * bucketWidth
high = low + bucketWidth
print low, "to", high

.
) bucketWidth ( .
numBuckets = 8 :
0.0 to 0.125
0.125 to 0.25
0.25 to 0.375
0.375 to 0.5
0.5 to 0.625
0.625 to 0.75
0.75 to 0.875
0.875 to 1.0

)(
. 0.0 1.0 .
.
.

127

. .
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(list, low, high
print buckets

1000 :
][138, 124, 128, 118, 130, 117, 114, 131

125 .
.

:4-9
.

-8-9
.
inBucket .
.

. .
i bucketWidth
. 0.0 1.0
.
bucketWidth . .

128


bucketWidth = 1.0 / numBuckets bucketWidth

numBuckets . 0.0 0.1 numBucket


0.0 numbuckets .

:
numBuckets = 8
buckets = [0] * numBuckets
for i in list:
)index = int(i * numBuckets
buckets[index] = buckets[index] + 1

int .
)
(len(buckets)-1
buckets histogram
.

:5-9 histogram
histogram .
-9-9
) immutable type (
.
.
) mutable type (
.
. .

129

) tuple(
.

.
) tuple assignment (
.

.
) deterministic(
.
) pseudorandom (
.

) patern matching (

.
histogram

132

-
.
.

.
. .

. }{ .

}{ = >>> eng2sp
'>>> eng2sp['one'] = 'uno
'>>> eng2sp['two'] = 'dos

eng2sp
. :
>>> print eng2sp
}'{'one': 'uno', 'two': 'dos


. ) (:

. . -

-
:
}'>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres

eng2sp :
>>> print eng2sp
}'{'one': 'uno', 'three': 'tres', 'two': 'dos

133

- !

:
]'>>> print eng2sp['two
''dos

' 'two ' 'dos -


.
-1-10
del - .
:
>>> inventory = {'apples': 430, 'bananas': 312, 'oranges': 525,
}'pears': 217
>>> print inventory
}{'oranges': 525, 'apples': 430, 'pears': 217, 'bananas': 312

:
]'>>> del inventory['pears
>>> print inventory
}{'oranges': 525, 'apples': 430, 'bananas': 312


:
>>> inventory['pears'] = 0
>>> print inventory
}{'oranges': 525, 'apples': 430, 'pears': 0, 'bananas': 312

len - :
)>>> len(inventory
4

134

-2-10
-
. keys
) keys(eng2sp
)( eng2sp.keys :
)(>>> eng2sp.keys
]'['one', 'three', 'two

) (keys
) (eng2sp . .

. keys

eng2sp .
values keys
:
)(>>> eng2sp.values
]'['uno', 'tres', 'dos

items ) -
( :
)(>>> eng2sp.items
])'[('one','uno'), ('three', 'tres'), ('two', 'dos

.
.
.
has_key (1) true
:
)'>>> eng2sp.has_key('one
1
)'>>> eng2sp.has_key('deux
0

135

.
:
)'>>> has_key('one
NameError: has_key

-3-10
.
.

copy . opposites
:
}'>>> opposites={'up': 'down', 'right': 'wrong', 'true': 'false
>>> alias = opposites
)(>>> copy = opposites.copy

alias opposites copy


. alias opposites :
'>>> alias['right'] = 'left
]'>>> opposites['right
''left

copy opposites :
'>>> copy['right'] = 'privilege
]'>>> opposites['right
''left

-4-10
14-8 .

:

136

0
0
0
0
0

1
0
0
0
3

0
0
0
0
0

0
0
2
0
0

0
0
0
0
0

0 :
matrix = [ [0,0,0,1,0],
[0,0,0,0,0],
[0,2,0,0,0],
[0,0,0,0,0],
] ][0,0,0,3,0


.
:
}matrix = {(0,3): 1, (2, 1): 2, (4, 3): 3

-
. .
][ :
]matrix[0,3
1


.
.
. 0
:
]>>> matrix[1, 3
)KeyError: (1, 3

137

get :
)>>> matrix.get((0,3), 0
1

get
:
)>>> matrix.get((1,3), 0
0

get
!
-5-10
fibonacci 7-5
.
. fibonacci(20)
) fibonacci(30 1 ) fibonacci(40
.
fibonacci n = 4 :
fibonacci
4

fibonacci
2

fibonacci
0

fibonacci

fibonacci
1

1-10

fibonacci
1

fibonacci
2

fibonacci
0

fibonacci
1

138


. fibonacci na=a4
fibonacci n = 3 n = 2 . fibonacci na=a3
fibonacci n = 2 n = 1 . ...
) fibonacci(0 ) fibonacci(1 .
.

.
. fibonacci :

}previous = {0:1, 1:1


def fibonacci(n):
if previous.has_key(n):
]return previous[n
else:
)newValue = fibonacci(n-1) + fibonacci(n-2
previous[n] = newValue
return newValue

previous .
0 : 1 1 1 .
fibonacci
.
.
.
fibonacci ) fibonacci(40
. ) fibonacci(50
:
)>>> fibonacci(50
OverflowError: integer addition

139

20,365,011,074 .
) (integer
. .
-6-10
long int
. long int . L

)>>> type(1L
>'<type 'long int

long int long long .


:
)>>> long(1
1L
)>>> long(3.9
3L
)'>>> long('57
57L

long int
fibonacci :
}>>> previous = {0:1L, 1:1L
)>>> fibonacci(50
20365011074L

previous fibonacci .
long int long int .

factorial :1-10 longaint

140

-7-10
7 .
histogram .
.

.
histogram :
}{ = >>> letterCounts
>>> for letter in "Mississippi":
... letterCounts[letter] = letterCounts.get (letter, 0) + 1
...
>>> letterCounts
}{'M': 1, 's': 4, 'p': 2, 'i': 4

. )
( .
.
histogram .
items sort :
)(>>> letterItems = letterCounts.items
)(>>> letterItems.sort
>>> print letterItems
])[('M', 1), ('i', 4), ('p', 2), ('s', 4

items sort
. extend append reverse .
-8-10
) dictionary(
- .
.

141

) key(
.
) key-value pair -(
.
) method(

.
) invoke(
.
) call graph (
.

) hint(
.
) overflow(
.

144

.
.

. CD

.
)(
.
.

PDF .
.
. .
. .

.
.
.
. f
:
)">>> f = open("test.dat","w
>>> print f
><open file 'test.dat', mode 'w' at fe820

open . ) (
. w ) (write .
test.dat
.
) (
.
write :
)">>> f.write("Now is the time
)">>> f.write("to close the file

145


:
)(>>> f.close

. "r"
) (read :
)">>> f = open("test.dat","r

:
)">>> f = open("test.cat","r
'IOError: [Errno 2] No such file or directory: 'test.cat

read .
:
)(>>> text = f.read
>>> print text
Now is the timeto close the file

)(>>> f.close

time to .
read :
)">>> f = open("test.dat","r
)>>> print f.read(5
Now i

read
read :
)>>> print f.read(1000006
s the timeto close the file
)(>>> print f.read
>>>

146

50 .
file :
def copyFile(oldFile, newFile):
)"f1 = open(oldFile, "r
)"f2 = open(newFile, "w
while 1:
)text = f1.read(50
if text == "":
break
)f2.write(text
)(f1.close
)(f2.close
return

break .
.
while 1 true .
break text
.
-1-11

.
.

:
)">>> f = open("test.dat","w
)">>> f.write("line one\nline two\nline three\n
)(>>> f.close

readline
:

147

)">>> f = open("test.dat","r
)(>>> print f.readline
line one
>>>

readlines :
)(>>> print f.readlines
]'['line two\012', 'line three\012


012 .
readline readlines :
)(>>> print f.readline
)(>>> print f.readlines
][

filterFile .
# :
def filterFile(oldFile, newFile):
)"f1 = open(oldFile, "r
)"f2 = open(newFile, "w
while 1:
)(text = f1.readline
if text == "":
break
if text[0] == '#':
continue
)f2.write(text
)(f1.close
)(f2.close
return

continue .
text
.

148

-2-11
write
. str:
>>> x = 52
))>>> f.write (str(x

% . %
.

" "%d

. d decimal:
>>> cars = 52
>>> "%d" % cars
''52

' '52 52 .
.
:
>>> cars = 52
>>> "In July we sold %d cars." % cars
''In July we sold 52 cars.

" "%f
" "%s :
)'>>> "In %d days we made %f million %s." % (34,6.1,'dollars
''In 34 days we made 6.100000 million dollars.

.

:

:
)%d" % (1,2
not enough arguments for format string
''dollars
illegal argument type for built-in operation

149

>>> "%d %d
TypeError:
>>> "%d" %
TypeError:

.

:
>>> "%6d" % 62
'
'62
>>> "%12f" % 6.1
'
'6.100000

.

:
>>> "%-6d" % 62
'62
'

:
>>> "%12.2f" % 6.1
'
'6.10

.
.

.
:
def report (wages):
)(students = wages.keys
)(students.sort
for student in students:
)]print "%-20s %12.02f" % (student, wages[student

150


}>>> wages = {'mary': 6.23, 'joe': 5.45, 'joshua': 4.25
)>>> report (wages
joe
5.45
joshua
4.25
mary
6.23

21
.
-3-11

) ( .
.

)( :
)">>> f = open("C:\\programming\\Python\\Tests\\test1.dat","r
)(>>> print f.readline
This is a test.

C programming Python
Tests test1.dat .
This is a test. )( readline .
"\"
"\" .
"\"
.
Pickling -4-11
.
str :
))>>> f.write (str(12.3
))]>>> f.write (str([1,2,3

151

.
.
:
)(>>> f.readline
']'12.3[1, 2, 3

PicklingPickling .



. pickle .
pickle :
>>> import pickle
)">>> f = open("test.pck","w

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
.

152

-5-11
.
.
:
>>> print 55/0
ZeroDivisionError: integer division or modulo

:
][ = >>> a
]>>> print a[5
IndexError: list index out of range

:
}{ = >>> b
]'>>> print b['what
KeyError: what

:
.
.

. try except
.


.
:
)' filename = raw_input('Enter a file name:
try:
)"f = open (filename, "r
except:
print 'There is no file named', filename

153

try .
except
.
: exists
true false :
except

def exists(filename):
try:
)f = open(filename
)(f.close
return 1
except:
return 0

except .
.
.
17 . 17
) ( :
def inputNumber ():
)' x = input ('Pick a number:
if x == 17:
'raise 'BadNumberError', '17 is a bad number
return x

raise : .
BadNumberError .
inputNumber
:
)( >>> inputNumber
Pick a number: 17
BadNumberError: 17 is a bad number

154

:1-11 inputNumber
BadNumberError .
-6-11
) file(
CD-ROM
.
) directory(
) (folder .
break statement

.
) text file (

.
continue statement

.
.

) format operator (
%
.
) format string (

.

155

) format sequence (
%
.
) path(
.
pickling

) exception(
.
) handle(
try . except

158

.

.
- .
.
-1-12 -
. -
:.
.
)( .
.
) (0a,0 .

. .

.
.

.
:
class Point:
pass

)
.(import
) 4-4 (.
Point . pass .
.

159

Point Point .
. .
Point Point :
)(blank = Point

blank Point .

Point

.
-2-12

:
>>> blank.x = 3.0
>>> blank.y = 4.0

math.pi
. string.uppercase .

:
3.0
4.0

x
y

blank

1-12

blank Point .
.
:
>>> print blank.y
4.0
>>> x = blank.x
>>> print x
3.0

160

blank.x blank x .
x . x x .
.

:
')' print '(' + str(blank.x) + ', ' + str(blank.y) +
distanceSquared = blank.x * blank.x + blank.y * blank.y

) (3.0, 4.0
25.0 .
blank :
>>> print blank
><__main__.Point instance at 80f8e70

blank Point __ __main


80f8e70 . ) (16
. Point
.

:1-12 Point id
.
-3-12
. :
def printPoint(p):
')' print '(' + str(p.x) + ', ' + str(p.y) +

printPoint
. ) printPoint(blank ) (3.0, 4.0.

161

:2-12 distance 2-5


.
-4-12

.
== . :
)(p1 = Point
p1.x = 3
p1.y = 4
)(p2 = Point
p2.x = 3
p2.y = 4
p1 == p2

>>>
>>>
>>>
>>>
>>>
>>>
>>>
0

p1 p2 . p1
p2 :
>>> p2 = p1
>>> p1 == p2
1

samePoint

:
def samePoint(p1, p2):
)return (p1.x == p2.x) and (p1.y == p2.y


samePoint :
)(Point
= 3
= 4
)(Point

= p1
p1.x
p1.y
= p2

>>>
>>>
>>>
>>>

162


>>> p2.x = 3
>>> p2.y = 4
)>>> samePoint(p1, p2
1

-5-12
.
.
.
: ) ( ) (
.
. -
. :
class Rectangle:
pass

:
)(box = Rectangle
box.width = 100.0
box.height = 200.0

Rectangle .
- !
)(box.corner = Point
box.corner.x = 0.0
box.corner.y = 0.0

. box.corner.x
corner corner x
.
box

163

:
0.0
0.0

x
y

100.0
200.0

width
height

box

corner

2-12

-6-12
. 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

-7-12
.
width height
:
box.width = box.width + 50
box.height = box.height + 100

164


:
def growRect(box, dwidth, dheight):
box.width = box.width + dwidth
box.height = box.height + dheight

dwidth dheight
. Rectangle
.
Rectangle bob growRect
:
)(bob = Rectangle
bob.width = 100.0
bob.height = 200.0
)(bob.corner = Point
bob.corner.x = 0.0
bob.corner.y = 0.0
)growRect(bob, 50, 100

>>>
>>>
>>>
>>>
>>>
>>>
>>>

growRect box bob .


box bob .

:3-12 moveRect Rectangle


dx dy dx x dy
y .
-8-12
.
.
.
. copy
copy :

import copy
)(p1 = Point
p1.x = 3
p1.y = 4
)p2 = copy.copy(p1
p1 == p2
)samePoint(p1, p2

165

>>>
>>>
>>>
>>>
>>>
>>>
0
>>>
1

copy copy
Point p1 . p2
.
Point copy
. .

Rectangle Point
. Point Rectangle
Rectangle Point .
b1 ) ( b2
. :
b2

width
height
corner

100.0
200.0

0.0
0.0

x
y

100.0
200.0

width
height

corner

3-12

. growRect
Rectangle moveRect
. .
copy deepcopy
.
:
)>>> b2 = copy.deepcopy(b1

166

b1 b2 .
deepcopy growRect
Rectangle Rectangle . Rectangle
:
def growRect(box, dwidth, dheight):
import copy
)newBox = copy.deepcopy(box
newBox.width = newBox.width + dwidth
newBox.height = newBox.height + dheight
return newBox

moveRect :4-12
Rectangle .

Rectangle

-9-12
) class(
.
.
) instance(
.
) object(

.
) instantiate(
.
) constructor(
.

167

) attribute(
.
) shallow equality (
.
) deep equality (
.
) shallow copy (

copy copy .
) deep copy (


deepcopy copy .

170

.
.

.
- .

.
-1-13
- Time
. :
class Time:
pass

Time
:
)(time = Time
time.hours = 11
time.minutes = 59
time.seconds = 30

Time :

11
59
30

hour
minute
second

time

1-13

:1-13 printTime Time


hours:minutes:seconds .

:2-13 after

171

Time t1 t2

t1 t2 ) true (1 )(0
false .
-2-13
addTime
. : .
addTime :
def addTime(t1, t2):
)(sum = Time
sum.hours = t1.hours + t2.hours
sum.minutes = t1.minutes + t2.minutes
sum.seconds = t1.seconds + t2.seconds
return sum

Time

.

.
. Time:
currentTime breadTime .
addTime .
printTime 2-14 :
)(currentTime = Time
currentTime.hours = 9
currentTime.minutes = 14
currentTime.seconds = 30

>>>
>>>
>>>
>>>

)(breadTime = Time
breadTime.hours = 3
breadTime.minutes = 35
breadTime.seconds = 0

>>>
>>>
>>>
>>>

)>>> doneTime = addTime(currentTime, breadTime


)>>> printTime(doneTime

172

12:49:30 .
.

.
.
:
def addTime(t1, t2):
)(sum = Time
sum.hours = t1.hours + t2.hours
sum.minutes = t1.minutes + t2.minutes
sum.seconds = t1.seconds + t2.seconds
if sum.seconds >= 60:
sum.seconds = sum.seconds - 60
sum.minutes = sum.minutes + 1
if sum.minutes >= 60:
sum.minutes = sum.minutes - 60
sum.hours = sum.hours + 1
return sum

.
.
-3-13

.
.
.

increment Time
.
:

173

def increment(time, seconds):


time.seconds = time.seconds + seconds
if time.seconds >= 60:
time.seconds = time.seconds - 60
time.minutes = time.minutes + 1
if time.minutes >= 60:
time.minutes = time.minutes - 60
time.hours = time.hours + 1


.
seconds
seconds
60 . while if:
def increment(time, seconds):
time.seconds = time.seconds + seconds
while time.seconds >= 60:
time.seconds = time.seconds - 60
time.minutes = time.minutes + 1
while time.minutes >= 60:
time.minutes = time.minutes - 60
time.hours = time.hours + 1

:3-13 .

:4-13 increment
.
-4-13
.
.

174

.
.

.
.
-5-13
.
) (

.
-
-
.

.
Time 60! second
minute 60 hour 3600.
addTime increment
60 .
- Time

. Time :
def convertToSeconds(t):
minutes = t.hours * 60 + t.minutes
seconds = minutes * 60 + t.seconds
return seconds

Time:

175

def makeTime(seconds):
)(time = Time
time.hours = seconds/3600
seconds = seconds - time.hours * 3600
time.minutes = seconds/60
seconds = seconds - time.minutes * 60
time.seconds = seconds
return time


.
addTime :
def addTime(t1, t2):
)seconds = convertToSeconds(t1) + convertToSeconds(t2
)return makeTime(seconds

.
) (.

increment :5-13 .
-6-13
60 10
. .
60
) convertToSeconds (makeTime
.
. Time
.
. 150-12 .
5 0 .
.

176

) ( )
(.
-7-13

.
. .
.
. .
.
.
n 9 ) (n-1 10-n .
9 . 6 9
:
54

10-6 4

6-1 5

!

.
.
.

.
.
.

. .

.

177

-8-13
) pure function (
.
.
) modifier (
.
.
) functional programming style (
.
) prototype development (

.
) planned development (

.
) algorithm(

.

180


- .
.
C++ .
-1-14

.
:

.

.
Time 13

. Point Rectangle
.

.

.
Time
. Time
. .

values keys .
.
:

181


.
.
.
.
.
.
printTime -2-14
13 Time printTime
:
class Time:
pass
def printTime(time):
print str(time.hours) + ":" +
str(time.minutes) + ":" +
)str(time.seconds

:
)(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 :

182

)(currentTime = Time
currentTime.hours = 9
currentTime.minutes = 14
currentTime.seconds = 30
)(currentTime.printTime

>>>
>>>
>>>
>>>
>>>


.

currentTime time .
self
.
printTime(currentTime)
: printTime
.
.
)( currentTime.printTime : currenttime .
.

.
-3-14
) increment (3-13 .

:
class Time:
#previous method definitions here...
def increment(self, seconds):
self.seconds = seconds + self.seconds
while self.seconds >= 60:
self.seconds = self.seconds - 60
self.minutes = self.minutes + 1

183

while self.minutes >= 60:


self.minutes = self.minutes - 60
self.hours = self.hours + 1

.
. increment :
)(currentTime = Time
currentTime.hours = 9
currentTime.minutes = 14
currentTime.seconds = 30
)currentTime.increment(500

self
seconds 500 .

:1-14 ) convertToSeconds (5-18


Time .
-4-14
after Time .
self . :
class Time:
#previous method definitions here...
def after(self, time2):
if self.hour > time2.hour:
return 1
if self.hour < time2.hour:
return 0
if self.minute > time2.minute:
return 1
if self.minute < time2.minute:
return 0
if self.second > time2.second:
return 1
return 0

184


:
if doneTime.after(currentTime):
"print "The bread will be done after it starts.

:

-5-14
.
string.find .
- .
find find.string .
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

:
)>>> find("apple", "p", 2
2
)>>> find("apple", "p", 3
-1

185

:2-14 end

.
: . end ) len(str
. .
find str .
-6-14

__ __init ) init (.
Time :
class Time:
def __init__(self, hours=0, minutes=0, seconds=0):
self.hours = hours
self.minutes = minutes
self.seconds = seconds

self.hours hours .
.
Time
init :
)>>> currentTime = Time(9, 14, 30
)(>>> currentTime.printTime
>>> 9:14:30

:
)(>>> currentTime = Time
)(>>> currentTime.printTime
>>> 0:0:0

:
)>>> currentTime = Time (9
)(>>> currentTime.printTime
>>> 9:0:0

186

:
)>>> currentTime = Time (9, 14
)(>>> currentTime.printTime
>>> 9:14:0

:
)>>> currentTime = Time(seconds = 30, hours = 9
)(>>> currentTime.printTime
>>> 9:0:30

-7-14 Point
Point 1-12 :
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 str .
)>>> p = Point(3, 4
)>>> str(p
')'(3, 4

Point __ __str
__ __str print :
)>>> p = Point(3, 4
>>> print p
)(3, 4

187

__ __init
__ __str
.
-8-14

- . .
.
+ __ __add :
class Point:
# previously defined methods here...
def __add__(self, other):
)return Point(self.x + other.x, self.y + other.y

.
other self . Point
Point x y .
+ Point __ __add :
)p1 = Point(3, 4
)p2 = Point(5, 7
p3 = p1 + p2
print p3
)11

>>>
>>>
>>>
>>>
(8,

p1+p2 ) p1.__add__(p2
.

:3-14 ) __sub__(self, other Point

188

.
__ __rmul .
* Point __ __mul
____mul

Point .
:
def __mul__(self, other):
return self.x * other.x + self.y * other.y

* Point

__ __mul :

def __rmul__(self, other):


)return Point(other * self.x, other * self.y

Point .
other __rmul__
.
:
)>>> p1 = Point(3, 4
)>>> p2 = Point(5, 7
>>> print p1 * p2
43
>>> print 2 * p2
)(10, 14

p2*2
__ __mul 2 .
__ __mul x other
:
Point

>>> print p2 * 2
'AttributeError: 'int' object has no attribute 'x

.
. .

189

-9-14
.
.

.
.
) multadd (
.
:
def multadd (x, y, z):
return x * y + z

x y z
. :
)>>> multadd (3, 2, 1
7

Point:
)4
)7
)(2, p1, p2
)(p1, p2, 1

>>> p1 = Point(3,
>>> p2 = Point(5,
>>> print multadd
)(11, 15
>>> print multadd
44

Point Point

.

190

frontAndBack
:
def frontAndBack(front):
import copy
)back = copy.copy(front
)(back.reverse
)print str(front) + str(back

reverse
. .
frontAndBack :

copy

]>>> myList = [1, 2, 3, 4


)>>> frontAndBack(myList
][1, 2, 3, 4][4, 3, 2, 1


. Point
.

:

reverse copy print.


copy __ __str Point
. reverse Point:
def reverse(self):
self.x , self.y = self.y, self.x

Point frontAndBack:
)>>> p = Point(3, 4
)>>> frontAndBack(p
)(3, 4)(4, 3

191


.
-10-14
) object-oriented programming language (
-
.
) object-oriented programming (

.
) method(
.
) override (
.
.
) initialization method (

.
) operator overloading (
.

) > < * - + ( -

) dot product (
Point
.

192

) scalar multiplication (
Point
.
) polymorphic (
.
.

194


.

.
-1-15
.
.
if while if .

.
) ( .
.
Card
.
-2-15 Card

.
.
. .
:
Clubs < Diamonds < Hearts < Spades
:
Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King
Ace King 2 .

195


) rank : ( ) suit ( .
. " "Spades
" "Queen .
) (rank ) (suit .
.

.

. :
3
2
1
0

Spades
Hearts
Diamonds
Clubs


.
:
11
12
13

Jack
Queen
King

) (

. Card :
class Card:
def __init__(self, suit=0, rank=0):
self.suit = suit
self.rank = rank

196

3 Clubs :
)threeOfClubs = Card(0,3

0 Clubs .
-3-15 ____str
Card
) (integer .

.
:

class Card:
]"suitList = ["Clubs", "Diamonds", "Hearts", "Spades
rankList = ["narf", "Ace", "2", "3", "4", "5", "6", "7",
]""8", "9", "10", "Jack", "Queen", "King
#init method omitted
def __str__(self):
return (self.rankList[self.rank] + " of " +
)]self.suitList[self.suit

__ __str suitList rankList suit


rank . ] self.suitList[self.suit
: suit self suitList
.
" "narf rankList
. 1 13 .
. 0 2 2 3 3
.
:
)>>> card1 = Card(1, 11
>>> print card1
Jack of Diamonds

197

suitList Card .
Card :
)>>> card2 = Card(1, 3
>>> print card2
3 of Diamonds
]>>> print card2.suitList[1
Diamonds


. " "JacksofsDiamonds
" "JacksofsSwirly Whales :
">>> card1.suitList[1] = "Swirly Whales
>>> print card1
Jack of Swirly Whales

Diamonds Swirly Whales :


>>> print card2
3 of Swirly Whales

.
-4-15
)== < > (
.
- __ __cmp
. __cmp__ self other
1 -1 0 .

. .

198

.
.

. 3 Clubs 2 Clubs
3 Diamonds 3 Clubs . 3 Clubs 2
Diamonds .

. .
Clubs
Diamonds .
__ __cmp :
def __cmp__(self, other):
# check the suits
if self.suit > other.suit: return 1
if self.suit < other.suit: return -1
# suits are the same... check ranks
if self.rank > other.rank: return 1
if self.rank < other.rank: return -1
# ranks are the same... it's a tie
return 0

Ace )1( 2 .

__cmp__ :1-15 Ace King .


-5-15
Card Deck .
Deck
.
Deck . Cards
52 :

199

class Deck:
def __init__(self):
][ = self.cards
for suit in range(4):
for rank in range(1, 14):
))self.cards.append(Card(suit, rank

.
0 3 1 13 .
52
. Card
cards . append ) ( .

-6-15

. Deck Card :
class Deck:
...
def printDeck(self):
for card in self.cards:
print card

) (...
. printDeck __ __str Deck.
__ __str .

.
__ __str Deck .

:

200


class Deck:
...
def __str__(self):
"" = s
for i in range(len(self.cards)):
"s = s + " "*i + str(self.cards[i]) + "\n
return s

. self.cards
i
.

.
print __ __str
. str __ __str
.

s . s

. s
. s Deck
:
)(>>> deck = Deck
>>> print deck
Ace of Clubs
2 of Clubs
3 of Clubs
4 of Clubs
5 of Clubs
6 of Clubs
7 of Clubs
8 of Clubs
9 of Clubs
10 of Clubs
Jack of Clubs
Queen of Clubs
King of Clubs
Ace of Diamonds

201

52
.
-7-15

.
randrange random
. a randrange b a-<=-x-<-b
. b
.
:
))random.randrange(0, len(self.cards


. .
:
class Deck:
...
def shuffle(self):
import random
)nCards = len(self.cards
for i in range(nCards):
)j = random.randrange(i, nCards
]self.cards[i], self.cards[j]=self.cards[j], self.cards[i

52
nCards .

. ) (i ) (j .
2-9 :
]self.cards[i], self.cards[j] = self.cards[j], self.cards[i

:2-15 .

202

-8-15
Deck removeCard .
(1) true (0) false
:
class Deck:
...
def removeCard(self, card):
if card in self.cards:
)self.cards.remove(card
return 1
else:
return 0

) (
in true .
__ __cmp . ____cmp
Card removeCard
.
. pop
:
class Deck:
...
def popCard(self):
)(return self.cards.pop

pop .
.
isEmpty .
true :
class Deck:
...
def isEmpty(self):
)return (len(self.cards) == 0

203

-9-15
) encode (

.
) class attribute (
.
.
) accumulator(

.

206

Card .

.
-1-16

.
.

. .
.
.

.
.
.
.
.
) ( .
.
Old Maid
.
.
-2-16
.
.

.

207

.

. Poker
. Bridge
.
. Hand Deck
.
:
class Hand(Deck):
pass

Hand Deck .
Hand
name cards . name
name . cards .
:
class Hand(Deck):
def __init__(self, name=""):
][ = self.cards
self.name = name

.
removeCard Hand Deck
addCard :
class Hand(Deck):
...
def addCard(self,card):
)self.cards.append(card

) (...
. append .

208

-3-16
Hand Deck .
Hand Deck

Deck .
deal .

.
deal . ) (
.
:
class Deck:
...
def deal(self, hands, nCards=999):
)nHands = len(hands
for i in range(nCards):
if self.isEmpty(): break # break if out of cards
)(card = self.popCard
# take the top card
?hand = hands[i % nHands] # whose turn is next
)hand.addCard(card
# add the card to the hand

nCards :
.
i 0 nCards-1 .
pop . .
) (% )
( . i
i%nHands ) (0.

209

-4-16
printDeck __ __str
Deck . :
)(>>> deck = Deck
)(>>> deck.shuffle
)">>> hand = Hand("frank
)>>> deck.deal([hand], 5
>>> print hand
Hand frank contains
2 of Spades
3 of Spades
4 of Spades
Ace of Hearts
9 of Clubs


Hand .
__ __str Hand Deck
:
)class Hand(Deck
...
def __str__(self):
s = "Hand " + self.name
if self.isEmpty():
"s = s + " is empty\n
else:
"s = s + " contains\n
)return s + Deck.__str__(self

s .
is-empty s . contains
Deck . Deck __ __str
self Deck .
) self Hand ( Deck
Hand Deck .
.

210

-5-16 CardGame
CardGame
:
class CardGame:
def __init__(self):
)(self.deck = Deck
)(self.deck.shuffle


.
CardGame
. Old Maid .
.
4 Clubs 4 Spades Jack . Hearts
Jack Diamonds .
Queen Clubs Queen
Spades .
. .
.
) (
.
. .
Queen Spades .
.
. Old Maid

.

211

-6-16 OldMaidHand
OldaMaid Hand
. OldMaidHand
Hand removeMatches :
class OldMaidHand(Hand):
def removeMatches(self):
count = 0
]originalCards = self.cards[:
for card in originalCards:
)match = Card(3 - card.suit, card.rank
if match in self.cards:
)self.cards.remove(card
)self.cards.remove(match
)print "Hand %s: %s matches %s" % (self.name,card,match
count = count + 1
return count


. self.cards
.
.

. ) ( .
3-crad.suit ) Club (0 ) Spade (1 Heart
) (2 . .
.
removeMatches :
)(>>> game = CardGame
)">>> hand = OldMaidHand("frank
)>>> game.deck.deal([hand], 13
>>> print hand
Hand frank contains
Ace of Spades
2 of Diamonds
7 of Spades
8 of Clubs

212

6 of Hearts
8 of Spades
7 of Clubs
Queen of Clubs
7 of Diamonds
5 of Clubs
Jack of Diamonds
10 of Diamonds
10 of Hearts
>>> hand.removeMatches()
Hand frank: 7 of Spades matches 7 of Clubs
Hand frank: 8 of Spades matches 8 of Clubs
Hand frank: 10 of Diamonds matches 10 of Hearts
>>> print hand
Hand frank contains
Ace of Spades
2 of Diamonds
6 of Hearts
Queen of Clubs
7 of Diamonds
5 of Clubs
Jack of Diamonds

Hand .__ init__ OldMaidHand

OldMaidGame -7-16
OldMaidGame .
play CardGame
.
OldMaidGame CardGame __ init__
:
class OldMaidGame(CardGame):
def play(self, names):
# remove Queen of Clubs
self.deck.removeCard(Card(0,12))
# make a hand for each player
self.hands = []

213

for name in names:


f.hands.append(OldMaidHand(name))
# deal the cards
self.deck.deal(self.hands)
print "---------- Cards have been dealt"
self.printHands()
# remove initial matches
matches = self.removeAllMatches()
print "---------- Matches discarded, play begins"
self.printHands()
# play until all 50 cards are matched
turn = 0
numHands = len(self.hands)
while matches < 25:
matches = matches + self.playOneTurn(turn)
turn = (turn + 1) % numHands
print "---------- Game is Over"
self.printHands()

removeAllMatches .
: removeMatches
class OldMaidGame(CardGame):
...
def removeAllMatches(self):
count = 0
for hand in self.hands:
count = count + hand.removeMatches()
return count

self.hands printHands :1-16


.
count
.

.

214

turn . 0
. numHand 0
.
playOneTurn .
:
class OldMaidGame(CardGame):
...
def playOneTurn(self, i):
if self.hands[i].isEmpty():
return 0
)neighbor = self.findNeighbor(i
)(pickedCard = self.hands[neighbor].popCard
)self.hands[i].addCard(pickedCard
print "Hand", self.hands[i].name, "picked", pickedCard
)(count = self.hands[i].removeMatches
)(self.hands[i].shuffle
return count


0 .

.
.
findNeighbor
:
class OldMaidGame(CardGame):
...
def findNeighbor(self, i):
)numHands = len(self.hands
for next in range(1,numHands):
neighbor = (i + next) % numHands
if not self.hands[neighbor].isEmpty():
return neighbor

215

None findNeighbor
.
.( )
. . printHand
10)
. (
:
>>> import cards
>>> game = cards.OldMaidGame()
>>> game.play(["Allen","Jeff","Chris"])
---------- Cards have been dealt
Hand Allen contains
King of Hearts
Jack of Clubs
Queen of Spades
King of Spades
10 of Diamonds
Hand Jeff contains
Queen of Hearts
Jack of Spades
Jack of Hearts
King of Diamonds
Queen of Diamonds
Hand Chris contains
Jack of Diamonds
King of Clubs
10 of Spades
10 of Hearts
10 of Clubs
Hand Jeff: Queen of Hearts matches Queen of Diamonds
Hand Chris: 10 of Spades matches 10 of Clubs
---------- Matches discarded, play begins
Hand Allen contains
King of Hearts
Jack of Clubs
Queen of Spades
King of Spades
10 of Diamonds
Hand Jeff contains

216

Jack of Spades
Jack of Hearts
King of Diamonds
Hand
Jack
King
10

Chris contains
of Diamonds
of Clubs
of Hearts

Hand Allen picked King of Diamonds


Hand Allen: King of Hearts matches King of Diamonds
Hand Jeff picked 10 of Hearts
Hand Chris picked Jack of Clubs
Hand Allen picked Jack of Hearts
Hand Jeff picked Jack of Diamonds
Hand Chris picked Queen of Spades
Hand Allen picked Jack of Diamonds
Hand Allen: Jack of Hearts matches Jack of Diamonds
Hand Jeff picked King of Clubs
Hand Chris picked King of Spades
Hand Allen picked 10 of Hearts
Hand Allen: 10 of Diamonds matches 10 of Hearts
Hand Jeff picked Queen of Spades
Hand Chris picked Jack of Spades
Hand Chris: Jack of Clubs matches Jack of Spades
Hand Jeff picked King of Spades
Hand Jeff: King of Clubs matches King of Spades
---------- Game is Over
Hand Allen is empty
Hand Jeff contains
Queen of Spades
Hand Chris is empty

. Jeff
-8-16
( )inheritance
.
( ) parent class
.

217

) child class (

.

220

15 16 Card
. .
.

.
-1-17

) 8-12 ( .
.

. .

.
:
None
.
.
-2-17 Node
____str

class Node:
def __init__(self, cargo=None, next=None):
self.cargo = cargo
self.next = next
def __str__(self):
)return str(self.cargo

221

.
) (cargo ) (next None .
.
str .
Node .
)">>> node = Node("test
>>> print node
test

:
)>>> node1 = Node(1
)>>> node2 = Node(2
)>>> node3 = Node(3

.
:
node3

3
None

cargo
next

node2

2
None

cargo
next

node1

1
None

cargo
next

1-17

:
>>> node1.next = node2
>>> node2.next = node3

None .
2-17.

222

node2

node3

3
None

cargo
next

node1

cargo
next

cargo
next

2-17

.
.
-3-17

. .
.
.
printList
.
def printList(node):
while node:
print node,
node = node.next
print

.
)>>> printList(node1
1 2 3

printList
. next .
node
.
3-17 list node .

3
None

cargo
y

node1

node2

node3

cargo
y

223

cargo
y

node

3-17

:1-17

] .[1,a2,a3 printList
.

-4-17
.
.
.1 : ) ( )
(
.2 .
.3 .
) 2 (
. -
- .

.
None :

224


def printBackward(list):
if list == None: return
head = list
tail = list.next
)printBackward(tail
print head,

.
.
.
printList :
)>>> printBackward(node1
3 2 1

.
printList printBackward
.Node
None
None .
.
printBackward
.
.
-5-17
) (
.
:
list

cargo

4-17

cargo

225

printList
printBackward .
.
.
.
printList
PrintBackward . :
.

.
. .
-6-17
printBackward :
head = list
tail = list.next

head list .

. head
list .
.
.
.
node list
. .
printBackward head tail
:
def printBackward(list):
if list == None: return
)printBackward(list.next
print list,

226

. printBackward
print
.
:

.
-7-17

. )
( .
.
:
def removeSecond(list):
if list == None: return
first = list
second = list.next
# make the first node refer to the third
first.next = second.next
# separate the second node from the rest of the list
second.next = None
return second

.
:
)printList(node1
3
)removed = removeSecond(node1
)printList(removed
)printList(node1

>>>
1 2
>>>
>>>
2
>>>
1 3

:
first

second

3
None

cargo
next

cargo
next

227

cargo
next

5-17



.
-8-17
.
] [3, 2, 1 printBackward 3, 2,
.
printBackwardNicely:
def printBackwardNicely(list):
print "[",
if list != None:
head = list
tail = list.next
)printBackward(tail
print head,
print "]",


.

printBackwardNicely printBackward
. printBackwardNicely
printBackward .

228

-9-17 LinkedList
.

.
LinkedList .
. LinkedList
Node :
class LinkedList:
def __init__(self):
self.length = 0
self.head = None

LinkedList
printBackwardNicely
LinkedList:
class LinkedList:
...
def printBackward(self):
print "[",
if self.head != None:
)(self.head.printBackward
print "]",
class Node:
...
def printBackward(self):
if self.next != None:
tail = self.next
)(tail.printBackward
print self.cargo,

printBackwardNicely .
printBackward ) Node (
) LinkedList( . self.head.printBackward
self.head Node.

229

LinkedList
. addFirst LinkedList .
:
class LinkedList:
...
def addFirst(self, cargo):
)node = Node(cargo
node.next = self.head
self.head = node
self.length = self.length + 1


.
-10-17
.
.
. length LinkedList
.

.

.

. addFirst
length .
.
.

230

-11-17
) embedded reference (
.
) linked list (
.

) node(

.
) cargo(
.
) link(
.
) precondition(
)( .
) fundamental ambiguity theorem (
.

) wrapper(

.

231

) helper(

.
) invariant(
)( )
(.

234

.
.

.
-1-18
) .
(. Card
.
.

(Abstract Data Type) ADT

) ( .
.



.
ADT
.
ADT

.
ADT
. ADT ADT
- - ADT - -
.

235

-2-18

ADT .

.
. ADT
. :

__ :__init .
:push .
:pop .
.
:isEmpty .
" "LastsIn First Out LIFO
.
-3-18
.
ADT
.

ADT .

.
ADT :
class Stack:
def __init__(self):
][ = self.items
def push(self, item):
)self.items.append(item
def pop(self):
)(return self.items.pop
def isEmpty(self):
)][ == return (self.items

236

items
. items .
push items .
pop
.
items isEmpty
.

.

.
-4-18
) (generic .
. :
)(s = Stack
)s.push(54
)s.push(45
)"s.push("+

>>>
>>>
>>>
>>>

isEmpty pop :
while not s.isEmpty():
print s.pop(),

+ 45 54 .
.
.
printBackward 4-17 .
printBackward
printBackward

237

.
Stack
.
-5-18 postfix

. 1 + 2 infix .
postfix . postfix
. 1 2 +
postfix
postfix :
) ( .
push. .
.
.

:1-18 * 1 2 + 3 .
postfix :
. infix
(1n+n2)n*n3.

:2-18 postfix 1 + 2 * 3.

238

-6-18

. - -
) ( . 1 .

split string (regular expression) re


. string.split )(delimiter
. :
>>> import string
)" ">>> string.split("Now is the time",
]'['Now', 'is', 'the', 'time

re.split
. .
] [A-z ] [0-9 . ^
] [^0-9 .
postfix :
>>> import re
)">>> re.split("([^0-9])", "123+456*/
]'' ['123', '+', '456', '*', '', '/',

string.split .
.

123 456 * / .
.
-7-18 postfix
postfix
) ( .
+ * :

239

def evalPostfix(expr):
import re
)tokenList = re.split("([^0-9])", expr
)(stack = Stack
for token in tokenList:
if token == '' or token == ' ':
continue
if token == '+':
)(sum = stack.pop() + stack.pop
)stack.push(sum
elif token == '*':
)(product = stack.pop() * stack.pop
)stack.push(product
else:
))stack.push(int(token
)(return stack.pop


. .
.
.
postfix (56+47)*2 :
)"* >>> print evalPostfix ("56 47 + 2
206

.
-8-18
ADT -
aADT - - ADT - .
ADT .
ADT
.
.

240

ADT
. .
.
-9-18
)) abstract data type (ADT (
) (
.
) client(
) ( ADT .
) provider(
) ( ADT .
) stack(
ADT .
) interface (
ADT .
) implementation(
.
) veneer(
ADT )
( .
.
) generic data structure (
.

241

infix

.
postfix

) parse(
.
) token(

.

244

ADT ADT .

ADT : .
.
.
.
.

FIFO ) .(First In, First Out


.
.

.
.
ADT ADT . :
FIFO ) (
.
ADT -1-19
ADT :
__ :__init .
:insert .
:remove .
.
:isEmpty .
-2-19
ADT
Node . :

245

class Queue:
def __init__(self):
self.length = 0
self.head = None
def isEmpty(self):
return (self.length == 0)
def insert(self, cargo):
node = Node(cargo)
node.next = None
if self.head == None:
# if list is empty the new node goes first
self.head = node
else:
# find the last node in the list
last = self.head
while last.next: last = last.next
# append the new node
last.next = node
self.length = self.length + 1
def remove(self):
cargo = self.head.cargo
self.head = self.head.next
self.length = self.length - 1
return cargo

removeFirst isEmpty remove isEmpty


. insert .
head .
.

. None next .
length . Queue
. None next

246

-3-19
.
: .

remove .

. - .


.
insert .
. .
-
- .
-4-19
ADT - .

1-19 .
last

cargo
next

length

cargo
next

head

cargo
next

1-19

:
class ImprovedQueue:
def __init__(self):
self.length = 0
self.head = None
self.last = None
def isEmpty(self):
)return (self.length == 0

247

last remove insert


:
class ImprovedQueue:
...
def insert(self, cargo):
)node = Node(cargo
node.next = None
if self.length == 0:
# if list is empty, the new node is head and last
self.head = self.last = node
else:
# find the last node
last = self.last
# append the new node
last.next = node
self.last = node
self.length = self.length + 1

last .
- . .
last None remove
:
class ImprovedQueue:
...
def remove(self):
cargo = self.head.cargo
self.head = self.head.next
self.length = self.length - 1
if self.length == 0:
self.last = None
return cargo

.
insert remove -
.

:1-19 ADT .
ImprovedQueue
.

248

-5-19
ADT ADT .
:
__ :__init .
:insert .
:remove .
.
:isEmpty .
.
.
.
.

.
.

.

:
class PriorityQueue:
def __init__(self):
][ = self.items
def isEmpty(self):
][ == return self.items
def insert(self, item):
)self.items.append(item

isEmpty insert .
remove:

249

class PriorityQueue:
...
def remove(self):
maxi = 0
for i in range(1,len(self.items)):
if self.items[i] > self.items[maxi]:
maxi = i
]item = self.items[maxi
][ = ]self.items[maxi:maxi+1
return item

maxi ) (
. i .
maxi i .
for maxi .
. :
)(q = PriorityQueue
)q.insert(11
)q.insert(12
)q.insert(14
)q.insert(13
)(while not q.isEmpty(): print q.remove

>>>
>>>
>>>
>>>
>>>
>>>
14
13
12
11


.
.
__ __cmp .
remove > __ __cmp
. __ __cmp
.

250

-6-19 Golfer
Golfer

.
__ __init __ __str :
class Golfer:
def __init__(self, name, score):
self.name = name
self.score= score
def __str__(self):
)return "%-16s: %d" % (self.name, self.score

__ __str
.

__ __cmp
. __cmp__ self other 1
other -1 0 .
class Golfer:
...
def __cmp__(self, other):
if self.score < other.score: return 1 # less is more
if self.score > other.score: return -1
return 0

Golfer :
)>>> tiger = Golfer("Tiger Woods", 61
)>>> phil = Golfer("Phil Mickelson", 72
)>>> hal = Golfer("Hal Sutton", 69
>>>
)(>>> pq = PriorityQueue
)>>> pq.insert(tiger
)>>> pq.insert(phil
)>>> pq.insert(hal
)(>>> while not pq.isEmpty(): print pq.remove
Tiger Woods: 61
Hal Sutton: 69
Phil Mickelson: 72

251

:2-19 ADT
.
- . .
-7-19
) Queue(
ADT .
) Priority Queue (
ADT
.
) queueing policy (
.
FIFO

" ." First In First Out


.

) linked queue (
.
) constant time-(
.
) linear time-(
.

254

17 .

.
) ( .
)( .
) (cargo . :
tree

cargo

1
right

3
right

None

left

cargo

right

left

None

None

cargo
left

None

1-20

None .
) tree ( .

None .
!
- - : .

.
.
.
) /( )

/( .
.

255


.

.
:
None
.
-1-20
.
.
class Tree:
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
def __str__(self):
)return str(self.cargo

cargo left right


left . right None.
.
.
:
)left = Tree(2
)right = Tree(3

:
)tree = Tree(1, left, right

:
))>>> tree = Tree(1, Tree(2), Tree(3

256

-2-20
:
.
:
def total(tree):
if tree == None: return 0
return total(tree.left) + total(tree.right) + tree.cargo

0 .
.
.
-3-20
.
. ) 1+2*3
infix( .
:
tree

+
right

*
right

3
right

cargo
left

cargo
left

2
right

cargo
left

1
right

cargo

cargo
left

2-20

left

1 2 + * .
) .
(.

257

:
)))>>> tree = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3


.
.
prefix postfix infix .
.
-4-20
:
def printTree(tree):
if tree == None: return
print tree.cargo,
)printTree(tree.left
)printTree(tree.right


.
preorder
. :
)))>>> tree = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3
)>>> printTree(tree
+ 1 * 2 3

postfix infix .
prefix .
.
.
:

258


def printTreePostorder(tree):
if tree == None: return
)printTreePostorder(tree.left
)printTreePostorder(tree.right
print tree.cargo,

1 2 3 * + postfix! postorder
.
inorder
:
def printTreeInorder(tree):
if tree == None: return
)printTreeInorder(tree.left
print tree.cargo,
)printTreeInorder(tree.right

1 + 2 * 3 infix .
.
infix .
inorder infix .

.

printTreePreorder :1-20
.

inorder
:
def printTreeIndented(tree, level=0):
if tree == None: return
)printTreeIndented(tree.right, level+1
)print ' '*level + str(tree.cargo
)printTreeIndented(tree.left, level+1

259

level .
. level+1
.
. :
)>>> printTreeIndented(tree
3
*
2
+
1

.
-5-20
infix
. (3+7)*9 :
*

3-20

.
+ *
.
. (3+7)*9 :
]'['(', 3, '+', 7, ')', '*', 9, 'end

end .

260

:2-20
.
getToken
.
true false
:
def getToken(tokenList, expected):
if tokenList[0] == expected:
]del tokenList[0
return 1
else:
return 0

tokenList
.
getNumber . tokenList
getNumber
None :
def getNumber(tokenList):
]x = tokenList[0
if type(x) != type(0): return None
]del tokenList[0
)return Tree (x, None, None

getNumber .
tokenList .
:
]'>>> tokenList = [9, 11, 'end
)>>> x = getNumber(tokenList
)>>> printTreePostorder(x
9
>>> print tokenList
]'[11, 'end

getProduct
. .3*7

261

getProduct .
def getProduct(tokenList):
)a = getNumber(tokenList
if getToken(tokenList, '*'):
)b = getNumber(tokenList
)return Tree ('*', a, b
else:
return a

getNumber
a . * b a
.
a .
:
]'>>> tokenList = [9, '*', 11, 'end
)>>> tree = getProduct(tokenList
)>>> printTreePostorder(tree
* 9 11
]'>>> tokenList = [9, '+', 11, 'end
)>>> tree = getProduct(tokenList
)>>> printTreePostorder(tree
9


. .
3*5*13 .
) .3*(5*13 :
*

13

4-20

getProduct :

262


def getProduct(tokenList):
)a = getNumber(tokenList
if getToken(tokenList, '*'):
)b = getProduct(tokenList
# this line changed
)return Tree ('*', a, b
else:
return a

*
.
.
:
]'tokenList = [2, '*', 3, '*', 5 , '*', 7, 'end
)tree = getProduct(tokenList
)printTreePostorder(tree
* * * 5 7

>>>
>>>
>>>
2 3

.
. +
.
:
) ( .
.
getSum
+ :
def getSum(tokenList):
)a = getProduct(tokenList
if getToken(tokenList, '+'):
)b = getSum(tokenList
)return Tree ('+', a, b
else:
return a

9 * 11 + 5 * 7 :
]'>>> tokenList = [9, '*', 11, '+', 5, '*', 7, 'end
)>>> tree = getSum(tokenList
)>>> printTreePostorder(tree
9 11 * 5 7 * +

263

.
.
getNumber :

def getNumber(tokenList):
if getToken(tokenList, '('):
x = getSum(tokenList) # get the subexpression
getToken(tokenList, ')') # remove the closing parenthesis
return x
else:
]x = tokenList[0
if type(x) != type(0): return None
][ = ]tokenList[0:1
)return Tree (x, None, None

9 * (11 + 5) * 7 :
]'>>> tokenList = [9, '*', '(', 11, '+', 5, ')', '*', 7, 'end
)>>> tree = getSum(tokenList
)>>> printTreePostorder(tree
* * 9 11 5 + 7

.
getNumber .
-6-20
.
.
:
def getNumber(tokenList):
if getToken(tokenList, '('):
)x = getSum(tokenList
if not getToken(tokenList, ')'):
'raise 'BadExpressionError', 'missing parenthesis
return x
else:
# the rest of the function omitted

raise
BadExpressionError . getNumber

264

.
.

:3-20

raise

. .
-20-7


.
.
:
Are you thinking of an animal? y
Is it a bird? n
What is the animals name? dog
What question would distinguish a dog from a bird? Can it fly
If the animal were dog the answer would be? n
Are you thinking of an animal? y
Can it fly? n
Is it a dog? n
What is the animals name? cat
What question would distinguish a cat from a dog? Does it bark
If the animal were cat the answer would be? n
Are you thinking of an animal? y
Can it fly? n
Does it bark? y
Is it a dog? y
!I rule
Are you thinking of an animal? n

5-20 :

265

?Can it fly

bird

?Does it bark

dog

cat

5-20

.

. .
.
.
:
def animal():
# start with a singleton
)"root = Tree("bird
# loop until the user quits
while 1:
print
if not yes("Are you thinking of an animal? "): break
# walk the tree
tree = root
while tree.getLeft() != None:
" ?" prompt = tree.getCargo() +
if yes(prompt):
)(tree = tree.getRight
else:
)(tree = tree.getLeft
# make a guess
)(guess = tree.getCargo
" ?" prompt = "Is it a " + guess +
if yes(prompt):
"!print "I rule
continue
# get new information

266

" ?"What is the animal's name


)raw_input(prompt
" ?"What question would distinguish a %s from a %s
))= raw_input(prompt % (animal,guess

= prompt
= animal
= prompt
question

# add new information to the tree


)tree.setCargo(question
" ?prompt = "If the animal were %s the answer would be
if yes(prompt % animal):
))tree.setLeft(Tree(guess
))tree.setRight(Tree(animal
else:
))tree.setLeft(Tree(animal
))tree.setRight(Tree(guess

yes . .
y Y true :
def yes(ques):
from string import lower
))ans = lower(raw_input(ques
)'return (ans[0] == 'y

1 break .
.
while .
) (cargo
.

.

:4-20 .
.

-8-20
) binary tree (
.

267

) root(
.
) leaf(
.
) parent (
.
) child(
.
) sibling(
.
) level(
.
) binary operator (
.
preorder

.
prefix

postorder

inorder

268

) subexpression (
.

270

20 . 20
.

.

.
.
.
-1-21

. 1-8
.

.
.

.

. .

.
. ][
. :
">>> String="Python
]>>> print String[3
h


)( ) ( .
:

271

]'>>> S=['James', 'Michel', 'Guido

.
-2-21

:
]]>>> matrix=[[2,3],[4,5],[6,7
]>>> matrix[2][0
6


][ . .

. :
]">>> S=["James", "Michel", "Guido
]>>> S[2][0
G

.
.
. :
}>>> mathematics = {'midterm':5, 'final':11


:
)>>> mathematics = (5,11

]>>> mathematics = [5,11

272

][ :
]>>> midterm = mathematics[0
>>> print midterm
5

.
.
:
}]>>> student = {'mathemathics':[5,11], 'Phisycs':[3,10


:
]]>>> student = [[5,11], [3,10

:
]>>> print student[1][0
3

1 0 .

.


100 .
100 .
5
. :
>>>scomputings=s[[[5,11],[3,10]],[[2,7],[3,8]],[[4,7],[3,9]],[[3
]]],9],[2,7]],[[6,12],[5,10


. 4 5
2 .

273


.

.
10 100
5 .
10000 .
10000 midterm final
5000 . 500
student ) (student23 5
!

.

.
university . .
:
}{'Computing':0, Mathematics:1
}{'student1':0, 'student2':1, 'student3':2
}{'mathematics':0, 'phisycs':1, 'programming':2
}{'midterm':0, 'final':1

=
=
=
=

branches
students
lessons
numKind

:
]'>>>sprintsuniversity[branches['Computing']][students['student2
]]'][lessons['mathematics']][numKind['final
7

274

-3-21

.
. 3
5 . 2
.
) ( .
.
.
0 :
def zeroList(n):
][=zl
for inin range(n):
)zl.append(0
return zl

!
-4-21
.
.

.
0 :
])>>> print [0 for i in range(5
][0, 0, 0, 0, 0

for i 0 5 0
. 0
:

275

])>>> print [i**2+1 for I in range(1,10,2


][2, 10, 26, 50, 82

.
:
])>>> zl=[0 for i in range(10
>>> print zl
][0, 0, 0, 0, 0, 0, 0, 0, 0, 0

if .
:
]>>> print [i for i in range(2,25) if i%2!=0 and i%0!=0
][5, 7, 11, 13, 17, 19, 23

:
def zeroList(n):
])return [0 for i in range(n

lambda -5-21
.
:
])>>> zeroList = lambda n:[0 for i in range(n

zeroList lambda
.
lambda ) (:
. :
)>>> zeroList(4
][0, 0, 0, 0

276


>>> prefix=lambda x,y='Mr.': y+' '+x
)'>>> print prefix('Janson
Mr. Janson
)'>>> print prefix('Janson','Mrs.
Mrs. Janson

reduce
. reduce
. reduce
reduce .
.
.
. reduce .

:
>>> mult=lambda x, y : x*y

) range(1,-n+1 reduce n .
5 :
))>>> print reduce(mult,range(1, 5+1
120

4 6 . 24 720 .
. factorial :
def factorial(n):
)return reduce(lambda x, y : x * y, range(1, n+1), 0

.
. 0 1:
)>>> factorial(0
1

277

:
)>>> factorial(-1
1

:1-21 .
-6-21
. 3-21
.

def sequence(a, b):
])zeroList = lambda n : [0 for i in range(n
)zl = zeroList(a
for i in range(len(zl)):
)zl[i] = zeroList(b
return zl

sequence zeroList
0 .
b . 0
:
)>>> print sequence(2, 3
]][[0, 0, 0], [0, 0, 0


.
.

zeroList .
.
:

278


def sequence(d):
])zeroList = lambda n:[0 for i in range(n
)]zl = zeroList(d[0
if len(d) == 1:
return zl
else:
for i in range(len(zl)):
)]zl[i] = sequence(n[1:
return zl

:
))>>> print sequence((2,3,2
]]][[[0, 0],[0, 0],[0, 0]],[[0, 0],[0, 0],[0, 0

-7-21
5-14 .

.
sequence
. sequence .
.
:
>>> def func(a, *b): print a ; print b
)>>> func(2, 3
2
)(3,

func . );(
print .
.
.

279

* . print b
3 .
:
)]'>>> func(2,3,{'key':'value'},'string',('tuple',),['list
2
)]'(3, {'key': 'value'}, 'string', ('tuple',), ['list


.
.
)**(
. :
>>> def func2(a, *b, **c): print a ; print b ; print c
)'>>> func2(2,3,4,5,key='value
2
)(3, 4, 5
}'{'key':'value


.
.
)(a, *b, **c
.
.

. sequence :
def sequence(*n):
])zeroList = lambda x:[0 for I in range(x
)]zl = zeroList(n[0
if len(n) == 1:
return zl
for i in range(len(zl)):
)]zl[i] = sequence(n[1:
return zl

280

. ] zl[i .

sequence *n .

*n
:
def sequence(*n):
from types import TupleType
if type(n[0]) == TupleType:
]n = n[0
])zeroList = lambda x:[0 for i in range(x
)]zl = zeroList(n[0
if len(n) == 1:
return zl
for i in range(len(zl)):
)]zl[i] = sequence(n[1:
return zl

8-5 type
. types
. .
types .
Type
ListType .TupleType
sequence .
:
)>>> sequence(2,3,2
]]][[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0

:
)>>> d = sequence(2,3,2
>>> d[2][1][0] = 123
>>> print d
]]][[[0, 0], [0, 0], [0, 0]], [[0, 0], [123, 0], [0, 0


. .

281

.
) ( input raw_input

:
def inputItems(Sequence):
from types import ListType
for i in range(len(Sequence)):
if type(Sequence[i]) != ListType:
)(Sequence[i] = input
else:
)]inputItems(Sequence[i
return Sequence

sequence inputItems

.

lambda .
.
-8-21

.
.
.
15-8 4-10
. . .

.
:
class Matrix:
pass

. sequence
__ __init

282

.
6-21 :

sequence

def __init__(self, dimension1=0, dimension2=0):


])zeroList = lambda n:[0 for i in range(n
)self.matrix = zeroList(dimensoin1
))for i in range(len(self.matrix
)self.matrix[i] = zeroList(dimension2
)self.dimensions = (dimension1, dimension2

__ __init matrix .
matrix self
Matrix .
dimensions __ __init matrix
. .
. __str__
.
:
def __str__(self):
''=s
for i in range(self.dimensions[0]):
for j in range(self.dimensions[1]):
's+=`self.matrix[i][j]`+'\t
's+='\n
]return s[:-1

s . i j
. ] matrix[i][j .
s.
: )`( =.+
str .
.
.
= +
. + = )

283

( . )=* /= = (-
. :
n += x
n = n+x

('\t') tab

)' ('\n .
' '\n
.
print
. :
)>>> m = Matrix(2,3
>>> print m
0
0
0
0
0
0

matrix

.
) ( .
inputItems 7-21


.
matrix inputItems .
:
class Matrix:
...
def inputItems(self):
for i in range(self.dimensions[0]):
for j in range(self.dimensions[1]):
while 1:
try:
)'self.matrix[i][j]=input('Item['+`i`+']['+`j`+']:
break
except NameError:
pass

284

__ __str
for ] matrix[i][j
.
input

.
input
. Matrix :
)>>> m = Matrix(2, 3
)(>>> m.inputItems
Element[0][0]:1
Element[0][1]:2
Element[0][2]:3
Element[1][0]:4
Element[1][1]:5
Element[1][2]:6
>>> print m
1
2
3
4
5
6


matrix :
>>> m.matrix[0][1] = 300
>>> print m
1
300
3
4
5
6

. matrix
:
>>> m.matrix[0] = 300
>>> print m
Traceback (most recent call last):
? File "<pyshell#7>", line 1, in
print m
__File "<pyshell#2>", line 32, in __str
' 's+=`self.matrix[i][j]`+
TypeError: unsubscriptable object

285

.

matrix .
-9-21

matrix . .

.
matrix .
)_(

.

.
matrix __matrix
:
class Matrix:
def __init__(self, dimension1=0, dimension2=0):
])zeroList = lambda n:[0 for i in range(n
)self.__matrix = zeroList(dimensoin1
))for i in range(len(self.__matrix
)self.__matrix[i] = zeroList(dimension2
)self.dimensions = (dimension1, dimension2
def __str__(self):
''=s
for i in range(self.dimensions[0]):
for j in range(self.dimensions[1]):
's+=`self.__matrix[i][j]`+'\t
's+='\n
]return s[:-1
def inputItems(self):
for i in range(self.dimensions[0]):
for j in range(self.dimensions[1]):
while 1:
try:
)' self.__matrix[i][j]=input('Item['+`i`+']['+`j`+']:
break
except NameError:
pass

286


:
)>>> m = Matrix(2, 3
>>> print m.__matrix
'AttributeError: Matrix instance has no attribute '__matrix


:
>>> m._Matrix__matrix
]][[0, 0], [0, 0

)_(
.
.

:2-21

.
.
-10-21

.

.
__ __mul
. __ __mul :
def __mul__(self, other):
)]product = Matrix(self.dimension[0], other.dimensions[1
for i in range(self.dimension[0]):
for k in range(other.dimensions[1]):
for j in range(self.dimensions[1]):
\ * ]product.__matrix[i][k] += (self.__matrix[i][j
)]other.__matrix[j][k
return product

287


.
. .

.

.

print :
)>>> m1 = Matrix(3, 1
)(>>> m1.inputItems
Element[0][0] = 1
Element[1][0] = 2
Element[2][0] = 3
)>>> m2 = Matrix(1*2
)(>>> m2.inputItems
Element[0][0] = 4
Element[0][1] = 5
>>> print m1 * m2
4
5
8
10
12
15

:3-21 __ __sub__ __add


__ __rmul Matrix .

-11-21 else

.
lambda
for .
.

288


.
.
6-19 .
.
.
.
.
listOfStrings
. sortedList
. listOfStrings sortedList .
sortedList
. sortedList
. sortedList
:
def sort(listOfStrings):
][ = sortedList
)]sortedList.append(listOfStrings[0
for i in range(1, len(listOfStrings)):
for j in range(len(sortedList)):
if len(listOfStrings[i]) < len(sortedList[j]):
]sortedList[j:j] = listOfStrings[i:i+1
break
if listOfStrings[i] not in sortedList:
)]sortedList.append(listOfStrings[i
return sortedList

for .
sortedList
. .
else .
else
. else

289

break return else


.
else :
def sort(listOfStrings):
][ = sortedList
)]sortedList.append(listOfStrings[0
for i in range(1, len(listOfStrings)):
for j in range(len(sortedList)):
if len(listOfStrings[i]) < len(sortedList[j]):
]sortedList[j:j] = listOfStrings[i:i+1
break
else:
)]sortedList.append(listOfStrings[i
return sortedList


.

.
-12-21
) Array(
.
) singel-dimensional sequence (

.
) multi-dimensional sequence (
) ( .
) list comprehension (
.

292


IDLE win32 wxPython Tkinter . ...

.
IDLE PythonWin.
-1- IDLE
IDLE 1.5.2 .
Guido van Rossum
IntegratedaDeveLopmentaEnvironment )
Monty Python ( .
.
IDLE Python Shell Window
File Editor .
. Path Browser
.
Class Browser IDLE .
Find in Files

. IDLE Debug Control Panel
) (.
-1-1- IDLE
IDLE Python 1.5.2
. Tcl/Tk
) . IDLE (.
IDLE Python... Start IDLE
) (Python GUI . idle.pyw . :
C:\program files\PYTHON23\Tools\idle\idle.pyw

293

1-

Tcl/Tk Path .
95/98 C:\autoexec.bat Notepad Path
C:\PROGRA~1\Tcl\bin . :
PATH=c:\windows;c:\windows\COMMAND;C:\PROGRA~1\Tcl\bin

NT XP Path System Control Panel

-2-1- Python Shell


IDLE .
) >>>( Enter
.
) (... .

.
CTRL + C .
.

294

-3-1-
IDLE .
.
:




2-

.
. ) console(
.
-4-1-
IDLE .
3- Enter def While
.
.
numa=anuma-a1 . BackSpace
)( . return .
continue break return pass raise )(
.

295

3-

-5-1-
Alt + / .
4- divisible .
d Alt + / .

4-

.
Alt + /
. 4- Alt + / not num
numList . nu num numList
.
-6-1-
IDLE
:

296


Enter


.


Alta+aP Alta+aN

.


Enter

.

) Alta+aP Alta+aN
(
Enter .
-7-1-

.

6-

297

.
) (
- .

. 7-
) ( .
:

7-

-8-1-
(File Editor) IDLE
.
:

Ctrl+N Ctrl+X

Ctrl+N

File > New...

Ctrl+F Ctrl+X

Ctrl+O

File > Open...

Ctrl+M Ctrl+X

Ctrl+M

File > Open Modue...

298

New Window )
( . Open
Open Module
. Shelve Shelve.py
) (sys.path .

8-

File Editor ) Path Browser (


Debugger ) ( .

Untitled .
-1-8-1-
Shell Window

. .
.
Shell Window Tab .
Paste Copy Cut . . . Shell Window .
.
:

299

] Ctrl +

Edit > Indent region

[ Ctrl +

Edit > Dendent region

Alt + 3

Edit > Comment out region

Alt + 4

Edit > Uncomment region

Tab

Alt + 5

Edit > Tabify region

Tab

Alt + 6

Edit > Untabify region


. Tabify region Tab )
Tab ( Untabify region . Tab
.

.
.
-2-8-1-
) ( *


* .
. Save Save as .
) (Save Copy As Save As
.

Save

Ctrl+S Ctrl+X

Ctrl+S

File > Save

Save As

Ctrl+W Ctrl+X

Alt+S

File > Save As ...

Alt+Shift+S

File > Save Copy As ...

Save Copy As

Ctrl+XW

300

-3-8-1-
import
Shell Window ) (Reload.
Import Module File Editor
import reload Shell Window .

Import

F5


Edit > Import Module

Ctrl + F5

Edit > Run Script

Import module import


) (Reload Shell Window .

Run Script . Shell Window
.
Ctrl + S Ctrl + F5
.
-9-1- Find/Replace
Find... Edit 9- :

9-

Wrap around ) Dawn (


) (

301

. regularaexpression
.
MatchaCase
WholeaWord
.
Replace... Edit 10- .
Search Dialog
.

10-
Find in Files... Edit . IDLE


) (*.py .
.
Recurse down subdirectories
.
-10-1- )(Path Browser
) (Path Browser
.
) .(11-

302

11-

PythonWin -2-
PythonWin IDLE
. .
-1-2-
) (Interactive
. Enter
.
) ">>>"
" ( "... . Enter
. Enter .
Enter " "....
.
Undo Edit Undo Ctrl+Z
.

303

-2-2-
Save Close Open Print Locate File .
.
sys.path .
Import Import .
PythonWin Import . Reload
Undo Import/Reload Save Open
Print Paste Copy Cut Run Redo . . .
.

306


.
-1-

:
"!>>> while 1 print "Hello world
Traceback ( File "<interactive input>", line 1
"!while 1 print "Hello world
^
SyntaxError: invalid syntax

) (
.
) ( .
print ) (: print .

.
-2-
) (
.
. .
) (
:
)>>> 10 * (1/0
Traceback (most recent call last):
? File "<interactive input>", line 1, in
ZeroDivisionError: integer division or modulo by zero
>>> 4 + Spam*3
Traceback (most recent call last):
? File "<interactive input>", line 1, in
NameError: name 'Spam' is not defined

307

>>> '2' + 2
Traceback (most recent call last):
? File "<interactive input>", line 1, in
TypeError: cannot concatenate 'str' and 'int' objects

.
.
NameError ZeroDivisionError .TypeError
.
-
) ( .
) (.
.

.
.
.
-3-
.
:
>>> while 1:
...
try:
...
))" x = int(raw_input("Please enter a number:
...
break
...
except ValueError:
...
"print "Oops! That was no valid number. Try again...
...


) Ctrl+C
( .
KeyboardInterrupt .
try :

308

try ))( try (except


except try
.
try
except
except try .
except
try
) (
.
try
except .
try
try .
except
. :
except ValueError:
pass

...
...

except except
. .
.
:
import string, sys
try:
)'f = open('myfile.txt
)(s = f.readline
))i = int(string.strip(s
except IOError, (errno, strerror):
)print "I/O error(%s): %s" % (errno, strerror
except ValueError:

309

"print "Could not convert data to an integer.


except:
]print "Unexpected error:", sys.exc_info()[0
raise

tryexcept else
except .
. :
for arg in sys.argv[1:]:
try:
)'f = open(arg, 'r
except IOError:
print 'cannot open', arg
else:
'print arg, 'has', len(f.readlines()), 'lines
)(f.close

else try
.
tryexcept .

. .
except ) (
.:
>>> try:
...
)(spam
... except NameError, x:
...
print x
...
name 'spam' is not defined

)(
. try
try
. :

310


>>> def this_fails():
...
x = 1/0
...
>>> try:
...
)(this_fails
... except ZeroDivisionError, detail:
...
print 'Handling run-time error:', detail
...
Handling run-time error: integer division or modulo by zero

-4-
raise :
'>>> raise NameError, 'Hi there
Traceback (most recent call last):
? File "<interactive input>", line 1, in
NameError: Hi there

raise
.

raise :
>>> try:
...
'raise NameError, 'Hi there
... except NameError:
...
'!print 'An exception flew by
...
raise
...
!An exception flew by
Traceback (most recent call last):
? File "<interactive input>", line 2, in
NameError: Hi there

-5- -

. :

311

>>> class MyError(Exception):


...
def __init__(self, value):
...
self.value = value
...
def __str__(self):
...
`return `self.value
...
>>> try:
...
)raise MyError(2*2
... except MyError, e:
...
print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4
'!>>> raise MyError, 'oops
Traceback (most recent call last):
? File "<interactive input>", line 1, in
'!MyError: 'oops


.
-6-
try
. . :
>>> try:
...
raise KeyboardInterrupt
... finally:
...
'!print 'Goodbye, world
...
!Goodbye, world
Traceback (most recent call last):
? File "<interactive input>", line 2, in
KeyboardInterrupt

finally try
.
finally .
try break return
finally .

312

finally )
( .
try except finally
.

Downey Allen B., Elkner Jeffrey, Meyers Chris; Wellesley, Massachusetts; April
2002 ; How to Think Like a Computer Scientist: Learning with Python
Pilgrim,Mark ; January 2002 ; Dive Into Python
v.Rossum Guido, Drake Fred L. ; December 2001 ; Python Tutorial

http://www.python.org

http://www.ibiblio.org/obp/thinkCSpy
http://www.orgmf.com.ar/condor/pyshelf22.zip
http://www.DiveIntoPython.org
http://www.BruceEckle.com

You might also like