You are on page 1of 445

32.973.

2-018
004.42
18

., .
Hello World! . .: , 2016. 400 .:
. ( ).

ISBN 978-5-496-01273-7

! ? -
? , ,
, ! -
! , .
, , , ...
. ? ,
. ,
. , -
, , ,
Python (). , -
. .
Python . -
. , ,
, , .
, . e-mail,
, mp3, .
!

12+ ( 29 2010 . 436-).

ISBN 978-1617290923 . .
ISBN 978-5-496-01273-7 .
.
Manning Publications, 2014
.
, 2016
.
 ,
, 2016 . , .
, 2016 .

Manning Publications , 192102, -,


Co. . . (. ), . 3, , . 7.
-
.
034-2014, 58.11.13.000
.
, , ,
16.12.15. 84108/16.
. , . . . . 42,000. 3000. 0000
, -
- -. 170546, ,
, -1, 3,
. www.pareto-print.

6 Python 7
8 Python 9 10
11 12 12
14 14
14 16
1.
Python 17 Python IDLE 18
, ! 19 Python 21
23 25 -
26 27 30
30 30
2 . :
, , 31 32 37
38 39 40
42 42 43
3.
44 47 -
47 49 51
54 55 55
4.
56 59
60 60
60 61 61
5 .
raw_input() 62 print 63 66
67 69 69
69
6.
GUI? 70 GUI- 70 GUI- 72
73 76 GUI-
77 78 78 78
7. ,
, 79 81 ? 81 -
82 84 86
and 86 or 87 not 88
? 88 89 89
8 .
92 94 range() 95
97 99 101
102 103
104 104 105
4

9 .
106 107 -
107 107 -
108 108 109
109 110
110 110
10.
111 114
1 1 .
115 117
118 120
122 125 127
127 128
12.
129 130 130
131 131
132 133 135
135 137 -
139 140 140
144 : 144
148 152 153 153
1 3 .
155 157 -
158 161 , -
163 164
168 168
169 169 169
1 4 .
171 Python 172 = +
173 ? 173 174
179 184 -
185 187 188
188 189
1 5 .
190 190 191
191 191 193
197 199 200
200
1 6 .
Pygame 201 Pygame 201
203 212 217
! 219 220 221
223 225 226
227 227
5

17.
229 ! 235 240
244 244 244
18.
245 247 252
253 PyPong 257 267
267 267
1 9 .
mixer 268 268 269
272 274
PyPong 275 276
PyPong 279 283 283
283
20. G U I -
PyQt 284 GUI- 289
291 292
GUI- 293 TempGUI 293 ? 299
304 305 305
2 1 .
307 309 311
312 317
319 325 325
326
22.
327 328 329
332 333 336
337 pickle 341 -
343 349 349 350
23.
351 352 358
362 375 375
375
24.
376 377
383 384 388
390 400 400
400

http://goo.gl/VPoZ48
25. .
2 6 .
.

, ,
, ? , ,
, ... ,
. .


-, -
. , ,
. ,
.

,
.
7


,
.

. -
,
, , . -
, ,
, , -.



.

,

: .


1 0.
, .
,
.
, 1 0.
, ?

Python
. , , -
. , .
.
, -
.
8

1110001101
0001110011
0100101000


-
!

>>> print "Hello"


! !
-!
!

. -
, Python.

Hello World,
Python. www.manning.com/books/hello-
world-second-edition.

( -
), -
:
!
, ;
, -
, , , -
;
9

, , -
, , ;
. ,
, , . -
.

Python
( !)
Python? :
Python , . -
Python , ,
;
Python . ,
, ;
Python . ,
, Python-
(
- ). ,
;
Python . -
, ,
NASA Google. , Python -
.
Python ;
Python .
Windows PC, Mac Linux.
Python-, Windows, -
MacOSX.
, ,
Python ( , -
Python, );
Python. -
, .
10

prin
: pyp
'Usage rint f (0)class # Increment th

t > >>
ful message if len(sy

if #
.exit
print
nt
help pri 'sys
e pa
Hello

>>>H
f#
s ge
ello i
prin

ile
ta me c

t >>>
if #

na
2:
Hello

.ar
v)!=

in

oun
g
ere given, pr

t
d rese

, an

Python,

t th
e line co self.header
w

ents
m
argu .
u
no

nt
Python,

If
#
e,
string
tim ,

ort sys,

_wr
tte

i
n=If no If
.

n o ar
=1 ; #
imp

nt u
er

.co
der hon
and foot

ea

v pyt

gu
f me

!/
#P bin sel

ah
/env nts
ing ate a
agin
!/bin/en # arguments 1 ;
, add text file



.
.
, :

( ),
, -
,
. !

. ,
, , .
,
.
, , ,
. ,
, .


Python. Python
, .
.
(!).
Windows, Mac OS X Linux. -

Windows. ( www.manning.com/books/hello-world-second-edition
Mac Linux.)
( ,
..). , -
.
Python ( ,
, ).
Hello
World. Python,
. www.manning.
com/books/hello-world-second-edition.
12

,
.


- -
.
. , ,
,
www.manning.com/books/hello-world-second-edition.
. .


,
.
.
.
.
!

if timsAnswer == correctAnswer:
print " !"
score = score + 10

, . ( , .)
.
- . ,
.

Python

Python. -
Hello World,
Python, . Hello World
: www.manning.com/books/hello-world-second-edition.
13

Python ,
, , , -
, ,
.



( ). : www.
manning.com/books/hello-world-second-edition. -
, .
, Python -
. ( !)


,
. . ,
-, . -
.
. (,
, .)

.

,

!

.
, !
, ,

. ,
, ,
.
,
. ,

.
14 

!
.
, ,
. ,
!
- . , -
! .
, .
- , ,
.


. Python2
Python3. 1.
, .
, Python2 Python3.
12 , Python-.
20 ,
PythonCard PyQt.
22
24.
251 Skier,
10.
26
.


cp4khelp@gmail.com.


Python .
www.manning.com/
books/hello-world-second-edition. ,
, -.

1
25 26 http://goo.gl/VPoZ48.

-
. ,
, :
. ,
. , , .
. ,
, ,
. ,
.
, . -
, : , !
, ,
. , , -
, .
, .
; , -
. ,
Manning Publications.
.
,
. ,
, ,
.
-
. -
. ,
.
16

, : Perl?
, , Python.
. -
.
. .
, . -
, , , , ,
, , , , , .,
, , , , , -
, , , ,
, , . , .
, .

, -
, , ,
, , , ,
.


Hello World! , -
. , , -
, . ,
., , , , ,
, , .
-
.
Manning,
Hello World! .
1


Python
, , Python .
Python .
Hello World, Python,
. www.
manning.com/books/hello-world-second-edition.
.


() .
BASIC.
.
READY (),
( basic ,
). , ?
, READY .
, , .
-,
!
, , -, ,
. ,
- . ,
, .

Python Windows, Mac OS X Linux. ,


, Windows, Python Mac OS X
Linux . ,
.
18 1

Python 2.7.3.

,
Python
, . ,
, -

. - Python.
(w w w.m an ni ng
.c om /b oo ks / 2.7.3. ,
he llo -w or ld -s ec on
d- ed iti on )

, -
. 2.x, -

, .
-


w w w.m an ni ng .c om
/b oo ks /
he llo -w or ld -s ec on
d- ed iti on .


Python Python 3.
,
.
Python3, Python2. Python
Python 2, Python 3.

Python 2.7.3 3.3.0.

2.7.3, , ,
2.x.

Python IDLE
Python. -
IDLE, .
, Python 2.7, IDLE (Python GUI).
, IDLE. :
19

IDLE (Integrated DeveLopment Environment ) -


(shell) Python. , ,
.
Python
Python Shell. IDLE (GUI),
Python GUI. , IDLE -
, -
.
>>>
.
(Graphical User Interface, GUI)
, ,
, , , ,
- . >>> - .. ,
, ,
Python ,

. .

, !
Python . -
>>> :

print "Hello World!"

Enter ( Return). -
Enter .
20 1

Enter :

Hello World!
>>>

, IDLE.

Python (print
) . ( ,
- , -
.)
Python . , !
!



! >>> d`, cnqondhm...

, : , ,
Hello World!, , !
. .
!
21


IDLE

! IDLE - ?
.
. ( , -
-
, Python.) ,
, .


- :

>>> pront "Hello World!"


SyntaxError: invalid syntax
>>>

, , Python
. print (pront), Python
, . , -
, , .
. , print
Python, pront .
pront

,
print.


,

Python (
).

Python
Python . (-
), Python .
22 1


, -

, .
.
>>> :

>>> print 5+3

8
>>>

, Python ! ,
.
:

>>> print 5*3


15
>>>

*
. , .
5 3 5 3,
Python *. (
, 8.)


5 3
.
Python,
!

, ?

>>> print 2345*6789


15920205
>>>
23

>>> print 1234567898765432123456789


* 9876543212345678987654321
121932632007315960006096522024081660
,
72245112635269
>>> -

,


! . -

.
-, Python:

>>> print "cat" + "dog"


Catdog
>>>

>>> print "Hello " * 20


Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello

-
. Python Hello 20 .
,


, ,

,
, , F ile Ne w ,

Python ( - (
Fi le ) -
.
). -
,
Python, -
(
. ,
Ne w )
Fi le .
, . , -

Python.

.
24 1

- . -
, Python . -
( Windows, TextEdit Mac OS X vi Linux),
. IDLE
, , , , . ,
IDLE FileNew Window.
, . Untitled
(), .

1.1.
print "I love pizza!"
print "pizza" * 20
print "yum" * 40
print "Im full."

, ,
FileSave FileSave as.
pizza.py. (
, , -
-
). ,
1.1.
,
Python-. .py

, ,
Python,

- , Python, -
,

.
\e xa
m p le s , , ,
-.
. -
, .
25

, IDLE , Python.
, ,
, . , Python-.


Run ( IDLE-)
Run Module ( ).
.

Python Shell (, IDLE) -


, - :

RESTART , . ( ,
.)
. ,
, , .
.
26 1

-
, ? -
, . ,
, .


IDLE . - -
, , , .
, ,
-, Python.
:

print "Hello, and welcome to Python!"


print "I hope you will enjoy learning to program."
print Bye for now!"

print "Bye for now!".


, : Theres an error in
your program: invalid syntax ( : ).
, , . IDLE
. , ,
- .


, Python ( IDLE)
. ,
.
:

print "Hello, and welcome to Python!"


print "I hope you will enjoy learning to program."
print "Bye for now!" + 5

, .
, :
27

>>> ============================ RESTART ============================


>>>
Hello, and welcome to Python!
I hope you will enjoy learning to program.


Traceback (most recent call last):
File "C:/HelloWorld/examples/error1.py", line 3, in <module>
print "Bye for now!" + 5
TypeError: cannot concatenate 'str' and 'int' objects
>>> -
Python

, Traceback, .
.
. .
, , , . -
Python ,
.
, , print "Bye for
. Python now!" * 5 ?
, print "Bye for
. print "Bye now!" + 5 ?
for now!" + 5 .
: -
, ? ,
? .
, , -
-. ( 5,
!) print "Bye for now!" * 5 .


. - .
- . 1.2 -
, . IDLE-
, , FileNew Window.
1.2, . , ,
.py. , NumGuess.py.
28 1

unt, and reset


page co the ad er_written=1 ; sel p yt h
on # Paginate
th e line f.he f.c env a >>Hel

nt te
>Hell

cou el
> > He

rint >
lo if
me in/

int >>
# p

o if #
rint >
ll o i f
pr

oun
ts

xt
# p

/b
cr

file
#! t
ile e'sys.exit(0)class # In

, a d d in
ga
-

#!/bin/
. , t ho
env
, n
py

#
n am

. -

Pag
inate
ge: pyprint f

, .

a text file
,
, .
Usa

, ad
t'

rin i

mp o
sys. r

di
argv)!=2: p ote ng
en(

header and fo a

er

rt
eg
sw ys,

s
fl

iv
en,
ei prin ent m tim
a helpful messag t string # If no argu e,

18 Python ,
. ,
. , , .
.

1.2.
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print " ! , !"
print " 1 99. 6 ."
while guess != secret and tries < 6:
guess = input(" ?")
if guess < secret:

print " , !" 6
elif guess > secret:
print " , !"

tries = tries + 1

if guess == secret:
print "! !"
else:
print " !"

print " ", secret


29

, ,
while, , if
elif. . -
, , .
RunRun Module,
. , . -
:

>>> ======================= RESTART =======================


>>>
! , !
1 99. 6 .
? 40
, !
? 20
, !
? 10
, !
? 11
, !
? 12
! !
>>>

5 , 12.
while, if, else, elif input -
. , ,
, .
1. .
2. .
3.
: ?
4. ,
.
, .
30 1


! . :
Python;
, IDLE;
;
Python , ;
, Python ( -
!);
IDLE, -
;
;
;
Python- .
1
1. IDLE?
2. print?
3. Python ?
4. IDLE ?
5. ()?

1. Python
.
2. : ,
.
:
.
1 1970.
.

. - ,
, - , -
.

1
http://goo.gl/VPoZ48.
2

:
? ! 1?
, .
. - -
:
;
;
.
, ,
(.1.1) , .
. .
-
.
.
.
.

.


, -
, -
, -

, -

.
32 2

, : , , .
? - -
, , - . ,
( ), .


, .
, .
,
,

.
,
.
,
, - .
,
. !
( -
) (,
, ).

Python,
? ?
, Python - -
, . , ,
, Python
. , -
.
Python
, .

Python Shell ( IDLE -


1, ). :

>>> Teacher = "Mr. Morton"


>>> print Teacher
: 33

, >>> Python-.
Enter. :

Mr. Morton
>>>

, "Mr.
Morton", Teacher.
(=) Python
, -
-. "Mr. Morton" Teacher.
"Mr. Morton" - .
. Python,
Teacher.
, , -
. >>> print Teacher.


Python - Teacher?
. ,
. -

. Mr. Morton.
( 5), -
(5 + 3) (Teacher).
Teacher, -
Python ,
"Mr. Morton".

, - : ,

:

( ...)
34 2



,
5 -
4 .
, : 123


3,
. 12
B
. 4

" ", . -
Python , . :

>>> print "53 + 28"


53 + 28
>>> print 53 + 28
81

, -

53 + 28.
-
- Python
,
53 + 28 -
Python.
.
,
. .
Python ,

.
. print -
( ).
.
. ?

>>> 5 + 3
8
: 35

#!/bin/env
and pytho
header_written=0def # Increme unt, n#
r:self. nt the age co Pag
atte p ina
p ri n t
orm t e a text file, addin
ga

> > >H

PrinterF
he

f#
print
ello i

>>>He
#

ade
llo if

e+ 1
print

pag

r an
>>>H
f#
ello i

d foote mport sys


.
f self.page=self
"Mr. Morton" Teacher), -

ri
.
,
rint
tim

,
e, s

pyp
.
tring
#
If
:
ge
Usa
nt ' i Python
: pr

no
argu
.
)!=
2

ments were g
ge if len(sys.argv

,
, , .

ive
n, p
,
rint a
hel
ssa

p
Python ,
me

ful
ul
p f

mes
.
hel

sage
ta


prin

if len(
en,

. -
rguments were giv

sys.argv)!=2: print 'Usa


, Python.
, Python, -
.
If no a

ge: p
g#

, , ,

ypr
trin

in
tf
s

ilen

e,

ame'
m

sy
t i

.
sys,

s .ex
port

it(0)
r im , Python

class # Increment
te

:
foo
ng a header and

=
. ,
the
, Python
pag
e coun d reset t he l
, addi

t, an ine
.
coun
file

t sel
f.head
xt

te er_wri
tten=1 ;
self.count=1 ;# ate a
!/bin/env python # Pagin


Python
. ,
,
. ,
, , ,
.
.
,
.
, .


. ,
.
, .
36 2

>>> First = 5
>>> Second = 3
>>> print First + Second
8

First Second. 5 First, -


3 Second. .
-:

>>> Third = First + Second


>>> Third
8


, , print.
( .)

print. -
First Second ,
Third. Third First Second.

. -
:

>>> MyTeacher = "Mrs. Goodyear"


>>> YourTeacher = MyTeacher
>>> MyTeacher
"Mrs. Goodyear"
>>> YourTeacher
"Mrs. Goodyear"

.
YourTeacher, MyTeacher, "Mrs.
Goodyear".
: 37


MyTeacher
, . - Mrs.Tysick,
. "Mrs.

Tysick". MyTeacher
YourTeacher?
"Mrs. Goodyear" "Mrs.
Tysick". - (
),
, .


(, ).
, , -
(_).
.
. ,
. teacher TEACHER . first
First.
, .
. , 4fun .
.




.
,
,
26 : AZ!
26,

.
38 2


, () . -
Python , 5 3, "5" "3"? ,
.
(, ) .
Python, ,
. Python ,
. :

>>> teacher = "Mr. Morton"


>>> teacher = 'Mr. Morton'

.
Python ,
. , :

>>> first = 5
>>> second = 3
>>> first + second
8
>>> first = '5'
>>> second = '3'
>>> first + second
'53'

5 3 , .
"5" "3" ,
"53".
, 1:

>>> print "cat" + "dog"


catdog

,
. .
: 39



,
.

.
(,
), .



. :

long_string = """ , :
, .
, .
,
."""

.
, ,
:

long_string = ''' , :
, .
, .
,
.'''

, ,
.


. , !
. Python
, ().
MyTeacher . MyTeacher
"Mrs. Goodyear" "Mrs. Tysick".
MyTeacher .
40 2

. Teacher?
IDLE, . :

>>> Teacher
'Mr. Morton'

>>> Teacher = 'Mr. Smith'


>>> Teacher
'Mr. Smith'

"Mr. Smith"
Teacher. -
.
"Mr. Morton"?



( ). -

"Mr. Morton" - -
, . ,
, Python
.
. -
, .
, "Mr. Morton"
"Mr. Smith". ( )
. Python ( ), -
. ( ),
.
Python . 12,
.

>>> Score = 7
>>> Score = Score
: 41

, . .
: . -
:

>>> Score = Score + 1


>>> print Score Score 7 8
8

? Score 7.
Score + 1, 7 + 1. 8.
Score (7) (8). -
Score .

(=). . ,
. -
( )
( ).

1. Score = 7. Score

2. ,
1 ( 8). Score

3. Score
Score.

Score 7 8.
.
(
).
-
.
-
. :

t = 'Mr. Morton'
42 2

x1796vc47blahblah = 'Mr. Morton'

-
. .
,
.
. , -
. , teacher Teacher
.
e count, and res
me nt the pag et th
# Incre e li
ne ount self.header_written=1 ; self.count=1
ss c ;s
pri cla elf.
pag
e=s
sys.exit(0)
o if #
nt > >

prin


t >>>

>Hell
if #

Hello
pri

elf
o if #
nt >>

>Hell

.page rinterF
e'
am
Python

+1P
prin ilen


tf

. r:sel
rm

o
y
ag e : p att
f.h
'Us

e

int

ea d
: pr

er_writ
)!=2

,
argv

ten
f#
,
=0d
e if len(sys.

#!
/bin/env python
Python,
essag

.
lm
pfu

#
hel Pagi e
nate a t xt
re given, print a file
s we t , add
gumen ing a h
ader and footer import sys, time, string # If no ar e


:
, ,
;
;
,
.

1. Python,
, ( )?
2. , ?
: 43

3. TEACHER TEACHEr ?
4. Python 'Blah' "Blah"?
5. Python, '4' 4?
6. ? ?
1) Teacher2
2) 2Teacher
3) teacher_25
4) TeaCher
7. "10" ?

1. ( ).
print.
2. ,
. print.
3. ( ). -
print.
4. ,
. . -
DaysPerWeek ( ), HoursPerDay ( )
MinutesPerHour ( ) (
).
5. , . ,
26? (: HoursPerDay.)
3


Python ,
, . , Py-
thon . , , -
! .
, , -
, .
.
, . - 30
+
, 2 e-15
- . ** 3197 3 7

3) .85 ) *
-
( a
+
=
2
+ 5
(2
. -
-
= eed
z sp
Python.

, ,
,
.
Python.


, Python,
1: (+),
(*).
45

(-) ( ), , Python
:

>>> print 8 - 5
3

(),
(/):

>>> print 6/2


3

, , :

>>> print 3/2


1

? .
, :
3 / 2 = 1.5
?
, Python .
, , .
, , .


(integers) ,
, 1, 2, 3. ,
0 1, 2, 3 ..

(decimal numbers),
(real numbers),
, 1.25, 0.3752
101.2.


(floating-point numbers).
.
,
0.00123456 12345.6.
46 3

3 2 , Python ,
. 1.5 ,
. 1. .
:

>>> print 3.0 / 2


1.5

, Python , -
.


Python 2
(floor division). Python3 -. Python3
:
>>> print 3/2
1.5
, Python 3
:
>>> print 3//2
1
Python2 Python 3,
,
Python2, Python3, .

!
, Python 2
.
,
Python- (
), ,
.
47

+, -, * / . .
= ,
.


,
.
,
.
myNumber + yourNumber

+, -, * /,
(), .

,
, . ,


.


?
2 + 3 * 4 = 20
2 + 3 * 4 = 14
. ,
:
2 + 3 = 5 , , 5 * 4 = 20.
, :
3 * 4 = 12 , , 2 + 12 = 14.
.
, ,
, .
48 3

, + *, -
. Python , -
. ,
:

>>> print 2 + 3 * 4
14

Python ,
( ) . -
, -
, .


2 + 3? . :

>>> print (2 + 3) * 4
20

Python 2 + 3
( ), 5.
5 * 4, 20.

, , -
. .
!

, . Python
( )
.
49


. -
, , 99% .


3 , :

>>> print 3 * 3 * 3 * 3 * 3
243

, 35, .
Python :

>>> print 3 ** 5
243

!


. ^ ( 3^5).
Python-,
,
. , ^
,
, .
.

**.


, .
, ** . :

>>> print 3 ** 5.5


420.888346239

.
50 3


Python , -
Python2 .
(Python3 //.) .
.
, ?
, :
7 / 2 = 3, 1.
7 / 2 ( 3)
( 1). Python
. ?
(%).
:

>>> print 7 % 2
1

/ %
:
,
>>> print 7 / 2
3
!
>>> print 7 % 2
1

7 2 3 1 .

:

>>> print 7.0 / 2


3.5
51

.
, - -
.
, . ,
,
!


: score = score + 1?
, . score = score - 1 -
, .
, -
: += () -= ().
:

>>> number = 7
>>> number += 1 number 1
>>> print number
8

>>> number = 7
number 1
>>> number -= 1
>>> print number
6

. ( 7 8.)
. ( 7 6.)


, 1 ? -
. Python
-. :

>>> print 9938712345656.34 * 4823459023067.456


4.79389717413e+025

, .
.
52 3

e -
-
e?
, e-.
( )

. .
, , -
, -
38000000000000000, 38,000,000,000,000,000
38000000000000000. ( 38 !)
, .
,
10.
3.8 1016. ( ,
16 ?)
,
3.8 16 , :
3.800000000000000000000

16

3 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 = 3 . 8 1 0 16
, 16
, ,
. ,
, .



, ,
1013. 13 .

.

,
, log2.
2 .
53

-
e-. .

E-
e- 3.8E16 3.8e16.
E 10. 3.81016.

, Python, E
(E), (e) .

, 0.0000000000001752, -
. 1.7521013, 1.752e-13.
,
, :
00000000000000001.752

13
0.00000000000011752 = 1.752e-13
Python ,
( ,
). , Python
.
:
>>> a = 2.5e6
>>> b = 1.2e7
>>> print a + b
14500000.0

e, .
, Python -
, ( )
. :
>>> c = 2.6e75
>>> d = 1.2e74
>>> print c + d
2.72e+75
54 3

,
73!
, , 14500000,
Python . ( 21).

-


!
,
.
,
.
,
, ,

. ,
Python-
5.673745e16,
, ,
.

,
e-:
3**5 35, , 3 * 3 * 3 * 3 * 3, 243.
3e5 3 * 105, , 3 * 10 * 10
* 10 * 10 *10, 300000.
,
. ,
10.
3e5, 3**5 ,
. , ,
.


:
Python;
;
55

;
;
.


1. Python ?
2. Python 2 8 / 3?
3. 8 / 3?
4. Python 2 8 / 3 ?
5. Python 6 * 6 * 6 * 6?
6. 17000000 ?
7. 4.56e-5 ( E)?

1. -
:
1) 35.27-
. 15%.
?
2) 12.5
16.7.
2. -
. C= 5 / 9 * (F 32). (:
!)
3. , ? -
: , .
, ,
200 80 , .
4


, ( -
) : ,
. Python ,
, . -
, ,
.


. , -
.
print, ,
(
print ). -
(type conversion). ?
Python .
. ,
:
float() ()
.
int() .
str() ( ).
, Python ( print),
.
,
, .
. IDLE.
57


float()
:

>>> a = 24
>>> b = float(a)
>>> a
24
>>> b
24.0

0 b.
, , .
a , float()
.
( print),
Python . ( 2.)
.


-
int() :

>>> c = 38.0
>>> d = int(c)
>>> c
38.0
>>> d
38


d, Python 0.1 0.2

0.30000000000000004,
c.
print,

. ?
58 4

! ? , , !
. .

?
, ,

?
Python
. 0.1 0.2 Python

( )
(),
15 .
0.3,
.
( 0.000000000000004.)
.
0.1 + 0.2
Python .
print ,
,
0.3.
, ,
. : ,
.
:
, ,
.

.

,
.
, , ,
.
59

>>> e = 54.99
>>> f = int(e)
>>> print e
54.99
>>> print f
54

54.99 55, - !
54.
int() , -
. -
,
.
,
21.

>>> a = '76.3'
>>> b = float(a)
>>> a
'76.3'
>>> b
76.3

, a . Python
, . b .


,
. .
Python type(), .
, :

>>> a = '44.2'
>>> b = 44.2
>>> type(a)
60 4

<type 'str'>
>>> type(b)
<type 'float'>

type() a type 'str', ,


b type 'float'. !


int() float() - , .
:

>>> print float('fred')


Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print float('fred')
ValueError: could not convert string to float: fred

, , Python
, "fred" . ?


,
. , -
, 5 5.0 9 9.0?

cel = 5.0 / 9 * (fahr - 32)

float():

cel = float(5) / 9 * (fahr - 32)

cel = 5 / float(9) * (fahr - 32)


:
(, ,
) : str(), int() float();
61

, print;
type();
.

1. -
int()?
2. , ?
cel = float(5 / 9 * (fahr - 32))

cel = 5 / 9 * float(fahr - 32)

, ?
3. ( ) , ,
int(), , ? (,
, 13.2 13, 13.7 14.)

1. float() '12.34' . ,
!
2. int() 56.78 .
?
3. int() . , -
!
5

, ,
. , -
, 3, -
. ,
.
,
, ? ,
: , . -
.
( )
, .
-
(input) .
,
.
-
, -
.
Python raw_input(), -
. .

raw_input()
raw_input() . -
.
, Python- str(), int(), float() type(),
4, .
, , ,
.
63


Python 3 raw_input() input().
raw_input()
Python2.

someName = raw_input()

,
someName.
. IDLE -
5.1.

5.1. raw_input
print " : "
somebody = raw_input()
print ", ", somebody, " ?"

IDLE, , .
:

:

, , ?

, somebody.

print
, ,
:

print " : "


64 5

raw_input() :

someName = raw_input()

, -
, print . :

print " : ",


someName = raw_input()

, .
:

, print.
:
. 5.1.
IDLE- 5.2.

5.2.
print "",
print "",
print "."

, ,
? Python
print .
65


Python3
. ,
print()
. , Python3, 5.2
:
print("", end=" ")
print("", end=" ")
print(".", end=" ")
raw_input()?

 , !


.
raw_input() ,
print :

someName = raw_input (" : ")

, raw_input() print.
.

!

raw_input(),
!

print.
print,

raw_input()?!

$99.95!
66 5


, , raw_input() .
, ? -
.
, 4, . int()
float() raw_input() .
:

temp_string = raw_input()
fahrenheit = float(temp_string)

raw_input()
. , float(), .
,
fahrenheit.
, , :

fahrenheit = float(raw_input())

. -
. .
-
. 5.3.

5.3. raw_input()
print " "
print " : ",
fahrenheit = float(raw_input()) -

celsius = (fahrenheit - 32) * 5.0 / 9
print "", float(raw_input())
print celsius,
print " "

5.3 :

print "", celsius, " "

print, -
.
67

rp nirp

# fi o
>> tni

>>> t
# fi
rp
Hello
>Hell

# fi o
>> tni
>Hell

f.count=1 ;
a self.p
Form age=
ter self
n
lf.page+1Pri
+

.pag
e 1 wr
se .

ite_header
e=

Python 2 input(),
lf.count=1 ; self.pag

(se
lf):#
the heade
, ,
If
r fo
r
1 ; se

this
int()

page
en=

itt
de

has ju
hea
float().
r_wr

st been written, don'telf.header_wri


lf.

1 ,
t se
e coun

,
nt, and reset the lin

.

raw_input().
e page cou

tten
, Python 3

=1 ;
ent th

input() .

sel f
m

.cou
ncre

nt =
f.pag
las raw_input().
1 ; se
#I

e=s
s l

,
c
t(0)

elf
print filename'sys.exi

.page
, Python 2

+1 write_header
raw_input(), Python 3
input(),

(se
f):#
ge: py

l
, t
If
'Usa

prin
t he
hea
. der
2:
f len(sys.argv)!=

for
, this p
age has just be
Python 2
raw_input() input().
sa g e i
mes

en

oot writ
and f er import sys, t ful ten,
header ime, string help
#!/bin/
env python # Paginate a text file, adding a # If no arguments were given, print a

int() raw_input()
, (
), int():

response = raw_input(" : ")


numberOfStudents = int(response)


. -
. (
, 22) .
5.4.
.
68 5

5.4.
import urllib2
file = urllib2.urlopen('http://manning.com/data/message.txt')
message = file.read()
print message

, . -
,
.
( ,
), .

p ri n t prin
en, print a helpful message if len(sy
>>>H

ort sys, time, string


f#

footer imp ere giv


t > >>
if #

ello i
prin

and # If w s.arg
t >>>

no uments
Hello
if #

ader v)!=
Hello

2:
a he rg prin
ing t 'U
a

s

d
a text file, ad

age
: pypr
filen

int
am e
'sy
in (Windows, Linux Mac OS X) s.e
ate

Pag xit
#
5.4

(0)
on

cla
h
pyt

\r.

ss
env

#
,

Incr
#!/bin/

eme
- .

nt th
Windows ( MS-DOS)

e page
: CR (Carriage Return )

count, and reset


LF (Line Feed ), Linux
don't

LF, Mac OS X CR.


en,
ritt

,
as j een w

th
e co
el
in
u
us b

, IDLE-, -
t

nt
se

,
lf.header_written
ag e h

.
):# If the header for this p

,
.
=1 ; s


elf.
cou

( IDLE
nt=
1

).
;s
self

elf
page .
write_head r(

e =sel
f.page+1Pr



oun o
unt, a

in

c
page erF
f.c
+1

t=1
self.page=self.page
, . -
; el ;s nd ent th
e orm
atter:
n=1 self.header_written=0def # Increm
-
set t re
he line cou ritte
nt self.header_w


-. -

,

.
-
,

.

,

.
69


:
raw_input();
raw_input() ;
, int() float() raw_input();
.

1. 12, -
answer? ?
answer = raw_input()
2. raw_input() ?
3. raw_input() ?
4. raw_input() (-
)?

1. ,
. print -
.
2. , , ,
.
3. ,
() .
4. , 3,
. :
;
(1 = 10000 -
);
.
5. . :
50 ?;
10 ?;
5 ?;
1 ?.
.
6


IDLE.
.
. -
,
, ..

GUI?
GUI Graphical User Interface ( -
). GUI
.
-
, , ..
(text-mode),
(command-line).
. GUI -
, ,
. .

, GUI (gooey),
, . -
, -
, !

GUI-
GUI-. -
GUI-. IDLE GUI.
71

GUI-.
Python, EasyGui.
, ( 15),
Python ,
.
Python -
, , EasyGui .
easygui.sourceforge.net/.

EasyGui
easygui.py zip-.
, Python.
?

Python
, Python .
Windows, MacOSX Linux .
easygui.py , Python,
. Python27
easygui.py.

GUI-
IDLE :

>>> import easygui

Python
EasyGui. , ,
. (www.manning.
com/books/hello-world-second-edition) .
OK:

>>> easygui.msgbox("Hello There!")


72 6

msgbox() EasyGui . -
EasyGui
( message box).
msgbox() -
:
OK -
.

GUI-
GUI-
. ?
OK -
. ,
:
>>> import easygui
>>> easygui.msgbox("Hello there!")
'OK'

'OK' Python EasyGui ,


OK. EasyGui , -
GUI-,
, ..
( ). :
>>> user_response = easygui.msgbox("Hello there!")

OK, . :
>>> print user_response
OK

OK -
user_response.
EasyGui. , ,
, (dialog box).
GUI-,
.
( OK), - ().
73

msgbox EasyGui -
OK. -
.


-
EasyGui
.


( ) -
. buttonbox,
(button box).
.
IDLE 6.1.

6.1.
import easygui
flavor = easygui.buttonbox("What is your favorite ice cream flavor?",
choices = ['Vanilla', 'Chocolate', 'Strawberry'] )
easygui.msgbox ("You picked " + flavor)

(list). -
12, , EasyGui .
( ice_cream1.py) . :

, , :
74 6

? , ,
.
flavor. raw_input(),
, . GUI-
.


. EasyGui
choicebox (choice box), .
OK.
6.1:
buttonbox choicebox (6.2).

6.2.
import easygui
flavor = easygui.choicebox("What is your favorite ice cream flavor?",
choices = ['Vanilla', 'Chocolate', 'Strawberry'] )
easygui.msgbox ("You picked " + flavor)

6.2 -
.
:

OK -
.
, -
,
, .

! Cancel
. ,


. ( Vanilla), -
Cancel, .
.
!
, !
easygui.py,
, -
75

. , , ,
. , - !
1. easygui.py , def __choicebox
( 934). ,
.
2. 30 ( 970) :
root_width = int((screen_width * 0.8))
root_height = int((screen_height * 0.5))

0.8 0.4, 0.5 0.25. easygui.py.


-
.



. raw_input(),
? EasyGui
enterbox (enter box),
. , (6.3).

6.3.
import easygui
flavor = easygui.enterbox("What is your favorite ice cream flavor?")
easygui.msgbox ("You entered " + flavor)


:
-
OK,

.
raw_input(),
().


, -
. ,
76 6

(default). ,
.
, .
6.4 , , .

6.4.
import easygui
flavor = easygui.enterbox(" ?", ,
default = '')
easygui.msgbox (" " + flavor)

, -
. , -
,
OK.

?
EasyGui ,
, int() float(),
4.
, EasyGui integerbox,
(integer box). -
.
().
,
float().


1 .
, EasyGui (6.5).

6.5. EasyGui
import random, easygui

secret = random.randint(1, 99)
guess = 0
tries = 0
easygui.msgbox("""AHOY! I'm the Dread Pirate Roberts,
and I have a secret!
77

It is a number from 1 to 99. I'll give you 6 tries.""")


while guess != secret and tries < 6:

guess = easygui.integerbox("What's yer guess, matey?")


if not guess: break

6
if guess < secret:


easygui.msgbox(str(guess) + " is too low, ye scurvy dog!")
elif guess > secret:
easygui.msgbox(str(guess) + " is too high, landlubber!")
tries = tries + 1
if guess == secret:




easygui.msgbox("Avast! Ye got it! Found my secret, ye did!")
else:
easygui.msgbox("No more guesses! The number was " + str(secret))

Python,
, .
:

if, else elif 7, while -


8. 15 random, 23.

GUI-
EasyGui GUI-: , -
, , , ..
.
EasyGui
, . -
GUI-, -
.
EasyGui easygui.sourceforge.net.
78 6

prin
a header
adding ort sys,
t ime, string # If no arguments were g

t > >>
bin/env python # Pagi

if #
e, a
print

fil iven, pr
#!/ r i mp
Hello

>>>H
int a

f#
n
ote
ello i
prin

nd f
elpf

t >>>
if #

t
Hello

ul

a t ex
ate

me
age if len

ss
(
Python,

sys
.arg
.

v )!=2: print 'Usage: p


: >>>help().
: help >.
,

yp
r in t f
. : help> time.sleep.

ilen
ame'sys.e
: help> easygui.msgbox.
text

xit
0)c

(
ea

quit:
la s
nat

s#
Incre
agi

help> quit
ment t
P

he
python pag
nv

>>> ec
e

ount
in/

b and re ,
elf.count=1 ; #!/ wr set the

itte
count self.header_ n=
1;s

line
ts If n
o If no
arguments argumen

:
GUI- EasyGui;
msgbox;
, , -
buttonbox, choicebox, enterbox, integerbox;
, ;
Python.

1. EasyGui ?
2. EasyGui ( )?
3. EasyGui ?
4. EasyGui ()?
5. , ? .

1. 5, ,
GUI, raw_input() print.
2. , , ,
, , , ( EasyGui).
:
124681 ,
. 1 . 1

7

,

. , ,
. , GUI.
, -
.
.
, , .
.
.

,

. :
, ;
, ;
, .
, .
.
Python ,
: (true) (false).





80 7

, Python .
?
?
?
. , , , -
. , ,
Python.
, , , , ,
. :



, .
-
-
(branching).
, , .

.
Python -
if:

if timsAnswer == correctAnswer:
print " !" ,
score = score + 1 ,
print " ."






, 81

(:) if -
Python,
. , - (block)

if, .
.
(,
, - if). Python
. -
, if .
, .
.

, -
. Python .
Python, .
Python, -
if, , -
. if

Python, .
, .
,
, ,
. .
Python -
.
.
?
if (if timsAnswer == correctAn-
swer)? , , .
: ,


: , -

?. ?
?
,
.

, Python -

.
. -
82 7

. ,
. ( -
, ). (
?). Python .
, (=) -
. :

correctAnswer = 5 + 3
temperature = 35
name = "Bill"

Python
(==). :

if myAnswer == correctAnswer:
if temperature == 40:
if name == "Fred":

!
= ==

. -
Python,

.

. , -
(comparison operator). , 3
, ,
?
.


, : (<),
(>) (!=). <>,
!=.
> < =, (>=)
(<=). .
, 83


Python 3 <>
. , !=.

, -
:

if 8 < age < 12:

, age 8 12, -
. age
9, 10 11 ( 8.1, 11.6, ..).
8 12, :

if 8 <= age <= 12:


-
(relational operators),
: ,
.
(conditional test),
(logical test). -
, -
.

7.1 , . -
IDLE- ,
compare.py. Run. ,
. , ,
.
84 7

7.1.
num1 = float(raw_input(" : "))
num2 = float(raw_input(" : "))
if num1 < num2:
print num1, " ", num2
if num1 > num2:
print num1, " ", num2
if num1 == num2:
print num1, "", num2
if num1 != num2:
print num1, " ", num2


, Python -
. , ? .
. ,
Python .
elif ( else if -
, ):
if answer >= 10:
print " 10!"
elif answer >= 5:
print " 5!"
elif answer >= 3:
print " 3!"

if elif elif
answer>=10 answer>=5 answer>=3

3!

5!


10!

elif if .
, 85

- ,
. else.
, if elif:
if answer >= 10:
print " 10!"
elif answer >= 5:
print " 5!"
elif answer >= 3:
print " 3!"
else:
print " , 3."

if elif elif -
answer>=10 answer>=5 answer>=3 else
3!

3!

5!


10!

. if -
, (
) ( ).
if elif elif
answer>=10 answer>=5 answer>=3


3!


5!


10!
86 7

,
:

answer = float(raw_input (" 1 15"))

( ).
, , .


, ? , -
,
. . :
age = float(raw_input(" ?: "))
grade = int(raw_input(" ?: "))
if age >= 8:
if grade >= 3:
print " ."
else:
print ", ."

, print
, . , if -
, .


, Python 3 raw_input()
input(), print :
print(" .")

and
,
. :

age = float(raw_input(" ?: "))


grade = int(raw_input(" ?: "))
, 87

if age >= 8 and grade >= 3:



print " ."
and
else:
print ", ."

and. , -
.
if


age>=8 and grade>=3

( )


and :

age = float(raw_input(" ?: "))


grade = int(raw_input(" ?: "))
color = raw_input(" ?: ")
if age >= 8 and grade >= 3 and color == "":
print " ."
else:
print ", ."

, if
. .

or
or .
:

color = raw_input(" ?: ")


if color == "" or color == "" or color == "":
print " ."
else:
print ", ."
88 7

if

color = "red" or color = "blue" or color = "green"


else

(
)

not

not. :

if not (age < 8):

if age >= 8:

, 8 .
4 +, -, * /.
<, >, == .. and, or not
.
-
, (and, or) (not)
. . 7.1
.
, -
.

?
:
;
;
and or;
not.
, 89

. 7.1.


= ()
+ .


+=
=
*
/ . ,

%
** .


==
< ,
> ,
<= ,
>= ,
!= . (
<> .)


1. ?
my_number = 7
if my_number < 20:
print ' 20'
else:
print '20 '

2. , my_number
25?
3. if, , 30,
40?
4. if, ,
Q?

1. . 10 10%, -
10 20%. ,
(10 20%) .
90 7

2. 10 12 . , -
,
m ( male ) f ( female ).
, ,
.
:
.
3. , .
200. , ,
.
:
?
( )?
?
:

: 60
: 40
: 10
240 .
200 .
.

:
: 60
: 30
: 8
144
200 .
!

5 -
.
4. ,
. - ( ).
, ,
Python, !
. ,
!
8

,
: ?
, ,
. , .
. -
(looping).
:
, .
(counting loops);
, . -
(conditional loops), ,
.
92 8


for, ,
Python, for.
. IDLE ,
FileNew ( ),
8.1.

8.1. for
for looper in [1, 2, 3, 4, 5]:
print "hello"

Loop1.py . (
RunRun Module F5.)
:

>>> ================ RESTART ================


>>>
hello
hello
hello
hello
hello

, . hello ,
print . ? (for looper in [1,
2, 3, 4, 5]:) :
1) looper 1 ( looper = 1);
2) -
( .);

,

...
93

3) looper
.
(print "hello")
, Python
. for -
, , .

.
( ) .
(, .)
- .
, (8.2).

8.2.
for looper in [1, 2, 3, 4, 5]:
print looper

Loop2.py . :

>>> ================ RESTART ================


>>>
1
2
3
4
5

hello -
looper. -
.

-
,
, ! , -
- ( ). !
.

Python- - ?
( )
Ctrl+C. ,
Ctrl
C. !
94 8


. ,
,
.
? , . -
, -
, ,
, !


, . -
. Python
(lists). 12, ,
. -
, looper .


. -
. (8.3).

8.3. 8
for looper in [1, 2, 3, 4, 5]:
print looper, " 8 =", looper * 8

Loop3.py . :

>>> =================== RESTART ===================


>>>
1 8 = 8
2 8 = 16
3 8 = 24
4 8 = 32
5 8 = 40

, .
:

print "1 8 =", 1 * 8


print "2 8 =", 2 * 8
95

print "3 8 =", 3 * 8


print "4 8 =", 4 * 8
print "5 8 =", 5 * 8

( 10
20) ,
( ).
!

range()
-
5 :

for looper in [1, 2, 3, 4, 5]:

, 100
1000 ? !

. range()
, -
. 8.4 range().

8.4. range()
for looper in range (1, 5):
print looper, " 8 =", looper * 8

Loop4.py . (
RunRun Module F5.) :

>>> ================= RESTART =================


>>>
1 8 = 8
2 8 = 16
3 8 = 24
4 8 = 32

, -
- ! ?
, range (1, 5) [1, 2, 3, 4]. -
:
96 8

>>> print range(1, 5)


[1, 2, 3, 4]

5? range() .
, .
, .


Python 3 :
>>> print(range(1, 5))
range(1,5)
, Python 3 range()
, iterable.
.
for ,
. .

8.5 , -
8 10 .

8.5. 8 10
range()
for looper in range(1, 11):
print looper, " 8 =", looper * 8

:
>>> ================== RESTART ==================
>>>
1 8 = 8
2 8 = 16
3 8 = 24
4 8 = 32
5 8 = 40
6 8 = 48
7 8 = 56
97

8 8 = 64
9 8 = 72
10 8 = 80

8.5 range(1, 11) 1 10


, .
looper .
looper,
, .

.
. ,
.
, .
looper. -
. ,
(, )
i, j, k ..
i, j k, -
. , . i, j k
, .


i, j k?
,
, a,
b, c x, y, z .
,
i, j k
.
,
i,
j k, .

:
for i in range(1, 5):
print i, " 8 =", i * 8

. ( !)
98 8

.
, . , -
, , . ,
,
.

range()
range() , -
8.5. :

for i in range(5):

for i in range(0, 5):

: [0, 1, 2, 3, 4].
0, 1. range(5),
5 , . ,
i 0, 1, 4, 5.



0, 1?
1,
0.
, , .

.
0, ,
.

.

, , . -
. ,
. , .
. ,
letter,
. print ,
.
99



>>> for letter in "Hi there":
: print letter

,
!

, ,
!


.
, 2? 5, 10?
?
range() ,
, 1.


, -
.
. -
, -
. ,
13.

.
IDLE ,
. , Enter.
100 8

>>> for i in range(1, 10, 2):


print i
1
3
5
7
9

range() 2.
2. :

>>> for i in range(5, 26, 5):


print i
5
10
15
20
25

5. ?

>>> for i in range(10, 1, -1):


print i
10
9
8
7
6
5
4
3
2

,
?

range() , -
,
. , ,

( ),
-
,
2, 1.
101

.
. IDLE 8.6.

8.6. ?
import time
for i in range(10, 0, -1):
print i
time.sleep(1)

print "!"

, ,
import, time sleep. .
8.6 , .
range (10, 0, -1), -
10 1.


.
.
. ,
(). -.
, . -
8.7 , .

8.7. ?
for cool_guy in [" ", "-",
" ", " "]:
print cool_guy, " !"

, . -
i, cool_guy.
. , -
. Python , ,
. (
, , .)
, , ? ,
? -
!
102 8


for, . -
while, .
for , , -
. , ,
.
while.
, -
?
if. -
while , -
, .
. ,
.

, while -
:
?.. ?..
?... , -
.
Python while. -
8.8. , -
, . (,
Save, Run.)

8.8.
print " 3, ."
someInput = raw_input() ,
while someInput == '3': someInput ='3'
print " 3. ."
print " 3,
."
someInput = raw_input()
print " 3, ."

. -
3, .
, .
103



, for !
!
while .
: -
conti
nue
break. , .
continue
,
continue. 8.9.

8.9. continue
for i in range(1, 6):
print
print 'i =', i,
print ', ',
if i == 3:
continue
print ' ?'

>>> ================== RESTART ==================


>>>
i = 1 , ?

i = 2 , ?

i = 3 ,
i = 4 , ?

i = 5 , ?

, ( i == 3)
(i == 4). -
continue. while.
break
, ,
? break.
104 8

6 8.9, continue break, :

>>> ================== RESTART ==================


>>>
i = 1 , ?
i = 2 , ?
i = 3 ,

3, .
break. while.
break continue
. , ,
break continue , .

:
for ( );
range(), ;
range();
while ( );
continue;
break.

1. ?
for i in range(1, 6):
print ', '

2. ? i
?
for i in range(1, 6, 2):
print ', '

3. range (1, 8)?


4. range (8)?
5. range (2, 9, 2)?
6. (10, 0, -2)?
7.
?
8. while?
105

1. , .
, .
:
?
5
:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

2. , for.
. while.
while, -
for.
3. , ,
. :
?
7
?
12
:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
7 x 11 = 77
7 x 12 = 84

, for, while .
9


, ( -
), .
, , .
( - ), ,
.
.


--, , -
! . -
--
,
.
Python .


,
.
, ,
, :
( );
;
( );
.
,
.
107

Python ,
6, . , -
, , , Python.


, # (
):

# Python
print ' '

, :

. , -
#, , .


. :

area = length * width #

#. , , -
.


.
#. :

# ***************
# , Python
#
#
# ***************


. . -
,
, ,
.
108 9


, Python -
. -
. 2 ,
. , :

""" ,
.
,
.
"""

,
. -
, , , Python .

n (sys.argv)!=2: prin name'sys.exit(0)class


prin if le t 'U t file
If no arguments were given, print a helpful ge sa rin #I
ring #
t > >>
if #

print

e, st m

py p
essa

Hello

nc r
>>>H

tim
ge:
f#

ello i
prin

ement the p
t >>>
if #

Hello
,
port sys

age coun
t
,
er im

,a
oot

nd r

adding a hea and f

e
set the
er
.
d

line count self


.
a t ile,

e
xt f

. he a
, ,
e

der
ython Paginat

wr i
tten _
, =
1 ; sel
#

.
f.

cou
rin

P erFor
t

nt=1
vp

1
n/e
n mat ge+ ; if n
!/bi ter:s lf.pa e=se ents were give
o argum
header_written=0def # # elf. n, gggprintprintself.pag

IDLE- , -
. , .
(
). IDLE . -
Python
, . IDLE ,
.


, . ?
, , .
109

( ). ,
. -
, , ?

,
, , ,
! -
,
. -
, -
.
,
, .
,
, . , , . -
, .
.


.
, .
\examples , ,
.


.
:

#print ""
print ""
>>> =============== RESTART ================
>>>

print "" . ,
.
,
. , , #
.
110 9

, IDLE-, ,

. IDLE- Format.


, :
( ), ;
;
, ,
.

, -
.

(
3) . ,
.
10


,
. !
, ,
.
1 . ,
.

SkiFree. (
: ru.wikipedia.org/wiki/SkiFree.)
, -
. 10.
, 100.

:
Pygame. (-
15.)
, -
, . -
www.
pygame.org. Pygame 16.
:
skier_down.png skier_right1.png;
skier_crash.png skier_right2.png;
skier_tree.png skier_left1.png;
skier_flag.png skier_left2.png.
\examples\skier ( ) -
. , .
Python , .
112 10

10.1. , 100 (
, ), .
, . -
, __init__ .

10.1. Skier
import pygame, sys, random

skier_images = ["skier_down.png", "skier_right1.png",


"skier_right2.png", "skier_left2.png",
"skier_left1.png"]

class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("skier_down.png")
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.angle = 0

def turn(self, direction):


self.angle = self.angle + direction
if self.angle < -2: self.angle = -2
if self.angle > 2: self.angle = 2
center = self.rect.center -
self.image = pygame.image.load(skier_images[self.angle]) -

self.rect = self.image.get_rect()
self.rect.center = center
speed = [self.angle, 6 - abs(self.angle) * 2]
return speed

def move(self, speed):



self.rect.centerx = self.rect.centerx + speed[0]
if self.rect.centerx < 20: self.rect.centerx = 20
if self.rect.centerx > 620: self.rect.centerx = 620

class ObstacleClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, type):
pygame.sprite.Sprite.__init__(self)
self.image_file = image_file
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.center = location
self.type = type
self.passed = False
113

def update(self):
global speed
self.rect.centery -= speed[1]
if self.rect.centery < -32: ,
self.kill()

def create_map():
global obstacles
locations = []
for i in range(10):
row = random.randint(0, 9)
col = random.randint(0, 9)

location = [col * 64 + 20, row * 64 + 20 + 640]
if not (location in locations):
locations.append(location)
type = random.choice(["tree", "flag"])
if type == "tree": img = "skier_tree.png"
elif type == "flag": img = "skier_flag.png"
obstacle = ObstacleClass(img, location, type)
obstacles.add(obstacle)

def animate():
screen.fill([255, 255, 255])
obstacles.draw(screen)
screen.blit(skier.image, skier.rect)
screen.blit(score_text, [10, 10])
pygame.display.flip()

pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]
obstacles = pygame.sprite.Group()
map_position = 0
points = 0
create_map()
font = pygame.font.Font(None, 50)
running = True
while running: 30
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:

running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
114 10

speed = skier.turn(-1)

elif event.key == pygame.K_RIGHT:

speed = skier.turn(1)
skier.move(speed)


map_position += speed[1]

if map_position >=640:
create_map()

map_position = 0

hit = pygame.sprite.spritecollide(skier, obstacles, False)


if hit:
if hit[0].type == "tree" and not hit[0].passed:
points = points - 100
skier.image = pygame.image.load("skier_crash.png")
animate()
pygame.time.delay(1000) -
-
skier.image = pygame.image.load("skier_down.png")
skier.angle = 0
speed = [0, 6]
hit[0].passed = True
elif hit[0].type == "flag" and not hit[0].passed:
points += 10
hit[0].kill()

obstacles.update()
score_text = font.render("Score: " +str(points), 1, (0, 0, 0))
animate()
pygame.quit()

\examples\skier.
, . -
, .
, -
. , , -
.

, , 10.1
. , -
, . !
11

, ( )
, .
1 :

while guess != secret and tries < 6:


guess = input(" ?") while
if guess < secret:
print " , !" if
elif guess > secret:
print " , !" elif
tries = tries + 1

while, - -
if elif, while.
. -
.


, -
8? , , :

multiplier = 5
for i in range (1, 11):
print i, "x", multiplier, "=", i * multiplier

, .
. -
.
.
116 11

(
) , .
. -
11.1.

11.1.
for multiplier in range (5, 8):
for i in range (1, 11):

print i, "x", multiplier, "=", i * multiplier
5,
print 6, 7

, print
for.
5, 6 7 1 10:

>>> ==================== RESTART ===================


>>>
1 x 5 = 5
2 x 5 = 10
3 x 5 = 15
4 x 5 = 20
5 x 5 = 25
6 x 5 = 30
7 x 5 = 35
8 x 5 = 40
9 x 5 = 45
10 x 5 = 50

1 x 6 = 6
2 x 6 = 12
3 x 6 = 18
4 x 6 = 24
5 x 6 = 30
6 x 6 = 36
7 x 6 = 42
8 x 6 = 48
9 x 6 = 54
10 x 6 = 60

1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
5 x 7 = 35
117

6 x 7 = 42
7 x 7 = 49
8 x 7 = 56
9 x 7 = 63
10 x 7 = 70

,
.
.


,
range(), . -
range() for
, .
, -
, .
.
, -
. .
, , -
. ,
. ,
.
, .
, .
,
, :

for i in range(1, numStars):


print '*',
>>> ====================== RESTART ======================
>>>
? 5
* * * *

, , -
, . , -
! , ! ,
118 11

for range.
, , 1:

numStars = int(raw_input (" ? "))


for i in range(1, numStars + 1): 1, , -
print '*', 5 , 5

, , .
( 8.) ,
. :

numStars = int(raw_input (" ? "))


for i in range(0, numStars):
print '*',
>>> ====================== RESTART =====================
>>>
? 5
* * * * *


.
, range() -
. (11.2).

11.2.
numLines = int(raw_input (' ? '))
numStars = int(raw_input (' ? '))
for line in range(0, numLines):
for star in range(0, numStars):
print '*',
print

, , .
:

>>> ============================ RESTART ============================


>>>
? 3
? 5
*****
*****
*****
119

,
.
numLines numStars. :
(for star in range (0, numStars):) -
;
(for line in range (0, numLines):)
.
print . - -
print .
( ), 11.3.

11.3.
numBlocks = int(raw_input (' ? '))
numLines = int(raw_input (' ? '))
numStars = int(raw_input (' ? '))
for block in range(0, numBlocks):
for line in range(0, numLines):
for star in range(0, numStars):
print '*',
print
print

>>> ======================= RESTART =======================


>>>
? 3
? 4
? 8
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *

* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *

* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
120 11


11.4 11.3.

11.4.
numBlocks = int(raw_input(' ? '))
for block in range(1, numBlocks + 1):
for line in range(1, block * 2 ): ,
for star in range(1, (block + line) * 2):
print '*',
print
print

>>> ======================= RESTART =======================


>>>
? 3
* * * *

* * * * *
* * * * * * *
* * * * * * * * *

* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * *

11.4
. ,
,
.
.
,
, 11.5.

11.5.
numBlocks = int(raw_input(' ? '))
for block in range(1, numBlocks + 1):
121

print ' = ', block


for line in range(1, block * 2 ):
for star in range(1, (block + line) * 2):
print '*',
print ' = ', line, ' = ', star
print

>>> ======================= RESTART =======================


>>>
? 3
= 1
* * * = 1 = 3

= 2
* * * * * = 1 = 5
* * * * * * * = 2 = 7
* * * * * * * * * = 3 = 9

= 3
* * * * * * * = 1 = 7
* * * * * * * * * = 2 = 9
* * * * * * * * * * * = 3 = 11
* * * * * * * * * * * * * = 4 = 13
* * * * * * * * * * * * * * * = 5 = 15

, -
. () .

?
!

!

...
, !
122 11


? , , ,
.


,
.
. -
,
. , 1 20,
:
5, 8, 14;
2, 12, 20;
.. -
1 20, :
5, 8, 14;
8, 5, 14.
, -
. -
:
5, 8, 14;
8, 5, 14;
8, 14, 5.
.

. , -
, , -
, , , .
.
. -
-.
: .
-.
, , .

. ,
123

, , . (
.)

..

11.6 IDLE- hotdog1.py.

11.6. -
print "\t \t \t\t\t"
count = 1
for dog in [0, 1]:
for bun in [0, 1]:
for ketchup in [0, 1]:
for mustard in [0, 1]:
for onion in [0, 1]:
print "#", count, "\t",
print dog, "\t", bun, "\t", ketchup, "\t",
print mustard, "\t", onion
count = count + 1

, ?
:
(dog) ;
(bun) .
, 2 2 = 4 ;
(ketchup)
. , 2 2 2 = 8 .
. . ( onion)
2 2 2 2 2 = 32 . . ,
32 . 11.6,
:
124 11

>>> =========================== RESTART ===========================


>>>

# 1 0 0 0 0 0
# 2 0 0 0 0 1
# 3 0 0 0 1 0
# 4 0 0 0 1 1
# 5 0 0 1 0 0
# 6 0 0 1 0 1
# 7 0 0 1 1 0
# 8 0 0 1 1 1
# 9 0 1 0 0 0
# 10 0 1 0 0 1
# 11 0 1 0 1 0
# 12 0 1 0 1 1
# 13 0 1 1 0 0
# 14 0 1 1 0 1
# 15 0 1 1 1 0
# 16 0 1 1 1 1
# 17 1 0 0 0 0
# 18 1 0 0 0 1
# 19 1 0 0 1 0
# 20 1 0 0 1 1
# 21 1 0 1 0 0
# 22 1 0 1 0 1
# 23 1 0 1 1 0
# 24 1 0 1 1 1
# 25 1 1 0 0 0
# 26 1 1 0 0 1
# 27 1 1 0 1 0
# 28 1 1 0 1 1
# 29 1 1 1 0 0
# 30 1 1 1 0 1
# 31 1 1 1 1 0
# 32 1 1 1 1 1

dog, bun,
ketchup, mustard onion.
11.6 . -
\t. ,
, 21.
count . , -,
, 27. ,
. (- , -
.)
!.
125


- !

,
. (, -
, ,
!) -
Python, 3.
, .
. -
. ,
:

dog_cal = 140
bun_cal = 120
mus_cal = 20
ket_cal = 80
onion_cal = 40

. , -
0 1 .
:

tot_cal = (dog * dog_cal) + (bun * bun_cal) + \


(mustard * mus_cal) + (ketchup * ket_cal) + \
(onion * onion_cal)

,
, . ,
.


- (11.7).

11.7. -
dog_cal = 140
bun_cal = 120

ket_cal = 80 -
mus_cal = 20
onion_cal = 40
126 11

print "\t \t \t\t\t \t"


count = 1

for dog in [0, 1]: dog


for bun in [0, 1]:
for ketchup in [0, 1]:
for mustard in [0, 1]:


for onion in [0, 1]:

total_cal = (bun * bun_cal)+(dog * dog_cal) + \
(ketchup * ket_cal)+(mustard * mus_cal) + \
(onion * onion_cal)
print "#", count, "\t",
print dog, "\t", bun, "\t", ketchup, "\t",
print mustard, "\t", onion,
print "\t", total_cal
count = count + 1


(\)
? ,
, Python:
. , .
, ,
. ,
, .
, .
, :
tot_cal = ((dog * dog_cal) + (bun * bun_cal) +
(mustard * mus_cal) + (ketchup * ket_cal) +
(onion * onion_cal))

IDLE 11.7. :

>>> =========================== RESTART ===========================


>>>

# 1 0 0 0 0 0 0
# 2 0 0 0 0 1 40
# 3 0 0 0 1 0 20
# 4 0 0 0 1 1 60
# 5 0 0 1 0 0 80
# 6 0 0 1 0 1 120
# 7 0 0 1 1 0 100
127

# 8 0 0 1 1 1 140
# 9 0 1 0 0 0 120
# 10 0 1 0 0 1 160
# 11 0 1 0 1 0 140
# 12 0 1 0 1 1 180
# 13 0 1 1 0 0 200
# 14 0 1 1 0 1 240
# 15 0 1 1 1 0 220
# 16 0 1 1 1 1 260
# 17 1 0 0 0 0 140
# 18 1 0 0 0 1 180
# 19 1 0 0 1 0 160
# 20 1 0 0 1 1 200
# 21 1 0 1 0 0 220
# 22 1 0 1 0 1 260
# 23 1 0 1 1 0 240
# 24 1 0 1 1 1 280
# 25 1 1 0 0 0 260
# 26 1 1 0 0 1 300
# 27 1 1 0 1 0 280
# 28 1 1 0 1 1 320
# 29 1 1 1 0 0 340
# 30 1 1 1 0 1 380
# 31 1 1 1 1 0 360
# 32 1 1 1 1 1 400

,
!
, .
Python !


:
;
;
;
.

1. Python ?
2. Python ?
128 11

3. ?
for i in range(5):
for j in range(3):
print '*',
print

4. 3?
5. ,
. (
)?

1. , 8?
:
import time
for i in range (10, 0, -1):
print i
time.sleep(1)
print "!"

. -
, :

: ? 4
4
3
2
1
!

2. , -
:
: ? 4
4 * * * *
3 * * *
2 * *
1 *
!

: , .
12


, Python -
. (
, ). ,
(collection), . -
.
(list), (dictionary). -
. , ,
.
. -
,
.
.





, - :

Python :

family = ['', '', '', '']

,
:

Python :

luckyNumbers = [2, 7, 14, 26, 30]


130 12

family, luckyNumbers Python-,


(items). , Python-
. -
, .


family, luckyNumbers .
, .
, , -
. luckyNumbers. ,
:
newList = []

, .
? - ?
, , , -
. , . ,
. ,
. , .


append().
, :

>>> friends = [] ,
>>> friends.append('')
''
>>> print friends

['']

>>> friends.append('')
>>> print friends
['', '']

,
( ). . -
131

: ,
. !


.
!
append
-
.

, -
. -
-
.


friends append() ?
, . 14,
.
(objects) Python. -
- ,
. , friends ,
:

friends.append(-)


, Python. -
, , .
. ,
, , . :

my_list = [5, 10, 23.76, '', myTeacher, 7, another_list]

, -
, , .
:

>>> letters = ['a', 'b', 'c', 'd', 'e']


132 12


. -
0, , letters[0],
:

>>> print letters[0]


a

>>> print letters[3]


d


,
(index)
-.
- . -
, , : -
4. -
Python-
, , ! ,
3, 0, 1.
Python-
.
!
.

, ,
!
!
,
,
?
. -


! .
-
.


.
133


. -
(slicing) :
>>> print letters[1:4]
['b', 'c', 'd']

range() for, -
.
, . ,

(4 1 = 3, ).

, : -
( ). -
(slice) , .
.
, :
>>> print letters[1]
b
>>> print letters[1:2]
['b']

.
. , , .
.
.
134 12

, :

>>> print type(letters[1])


<type 'str'>
>>> print type(letters[1:2])
<type 'list'>

(type) ,
, (str), (list).
, ,
. ,
.


. ,
, , ,
. ,
, , -
. ,
.
,
. :

>>> print letters[:2]


['a', 'b']

. -
(
). :

>>> print letters[2:]


['c', 'd', 'e']

, , -
.
, .
:

>>> print letters[:]


['a', 'b', 'c', 'd', 'e']
135

, , ? ,
letters[:] . ,
- , .

>>> print letters


['a', 'b', 'c', 'd', 'e']
>>> letters[2] = 'z'
>>> print letters
['a', 'b', 'z', 'd', 'e']

.
, 0 4.
:

letters[5] = 'f'

. ( , .)
, . -
, :

>>> letters[2] = 'c'


>>> print letters
['a', 'b', 'c', 'd', 'e']


, append().
. : append(), extend() insert().
append() .
extend() .
insert() , -
. .
append()
append() . :

>>> letters.append('n')
>>> print letters
['a', 'b', 'c', 'd', 'e', 'n']
136 12

>>> letters.append('g')
>>> print letters
['a', 'b', 'c', 'd', 'e', 'n', 'g']

, . ,
append() . ,
. .

extend()
extend() :

>>> letters.extend(['p', 'q', 'r'])


>>> print letters
['a', 'b', 'c', 'd', 'e', 'n', 'g', 'p', 'q', 'r']

, extend() .
, extend ,
.
, extend(),
.

insert()
insert() .
:

>>> letters.insert(2, 'z')


>>> print letters
['a', 'b', 'z', 'c', 'd', 'e', 'n', 'g', 'p', 'q', 'r']

z 2.
( ). c,
, .
.

append() extend()
append() extend() , -
. .
extend():
137

>>> letters = ['a','b','c','d','e']


>>> letters.extend(['f', 'g', 'h'])
>>> print letters
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

append():

>>> letters = ['a', 'b', 'c', 'd', 'e']


>>> letters.append(['f', 'g', 'h'])
>>> print letters
['a', 'b', 'c', 'd', 'e', ['f', 'g', 'h']]

? , append()
. , ? .
, , .
. ,
, .
.
insert() append() ,
, append()
.


, ? :
remove(), del pop().

remove()
remove() :

>>> letters = ['a', 'b', 'c', 'd', 'e']


>>> letters.remove('c')
>>> print letters
['a', 'b', 'd', 'e']

, . ,
. -
:

>>> letters.remove('f')
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
138 12

letters.remove('f')
ValueError: list.remove(x): x not in list

? .
.

del
del . :

>>> letters = ['a', 'b', 'c', 'd', 'e']


>>> del letters[3]
>>> print letters
['a', 'b', 'c', 'e']

( 3), d.

pop()
pop() .
:

>>> letters = ['a', 'b', 'c', 'd', 'e']


>>> lastLetter = letters.pop()
>>> print letters
['a', 'b', 'c', 'd']
>>> print lastLetter
e

pop() :

>>> letters = ['a', 'b', 'c', 'd', 'e']


>>> second = letters.pop(1)
>>> print second
b
>>> print letters
['a', 'c', 'd', 'e']

( 1), b.
second letters.
, pop() , -
. - , pop(n)
, .
139


? -
:
, ;
( ).
in
, ,
in. :

if 'a' in letters:
print " 'a' letters"
else:
print " 'a' letters "

'a' in letters , , .
True, a, False .


, -
: 1 0, true false.

-
( 1 0)
and, or not. 7.

>>> 'a' in letters


True
>>> 's' in letters
False

, letters a, s.
in remove() ,
, :

if 'a' in letters:
letters.remove('a')

, .
140 12


index():

>>> letters = ['a', 'b', 'c', 'd', 'e']


>>> print letters.index('d')
3

, d 3,
. remove(), index(),
, ,
in:

if 'd' in letters:
print letters.index('d')


, -
. range()
. , .
,
. ,
. :

>>> letters = ['a', 'b', 'c', 'd', 'e']


>>> for letter in letters:
print letter
a
b
c
d
e

letter. (
looper, i, j k.)
,
letter .


. ,
().
,
141

insert(), append(), remove() pop().


, . ,
.
sort():

>>> letters = ['d', 'a', 'e', 'c', 'b']


>>> print letters
['d', 'a', 'e', 'c', 'b']
>>> letters.sort()
>>> print letters
['a', 'b', 'c', 'd', 'e']

sort() , -
.
, sort() .
, .
:

>>> print letters.sort()

. :

>>> letters.sort()
>>> print letters


.
, .
, :

>>> letters = ['d', 'a', 'e', 'c', 'b']


>>> letters.sort()
>>> print letters
['a', 'b', 'c', 'd', 'e']
>>> letters.reverse()
>>> print letters
['e', 'd', 'c', 'b', 'a']

reverse(),
.
142 12

sort() ,
( ):

>>> letters = ['d', 'a', 'e', 'c', 'b']


>>> letters.sort (reverse = True)
>>> print letters
['e', 'd', 'c', 'b', 'a']

, reverse, , , -
.
,
.
. ,
, .
:

>>> original_list = ['', '', '', '']


>>> new_list = original_list[:]
>>> new_list.sort()
>>> print original_list
['', '', '', '']
>>> print new_list
['', '', '', '']

, ,

,

, , . ,
-, -
new_list = original_list[:]
( 2),
, name1 = name2 -

,
. ?
new_list = original_list






?
143

, .
new_list original_list
. ( )
. . :

original = [5,2,3,1,4] original 5,2,3,1,4

new = original original


5,2,3,1,4
new

new.sort() original
1,2,3,4,5
new

new,
original, new original .
, new :

original = [5,2,3,1,4] original 5,2,3,1,4

new = original original


5,2,3,1,4
new

new = [6,7,8,9,10] original


5,2,3,1,4

new 6,7,8,9,10

2.
, , new
= original. ,
: new = original[:].
. :

original = [5,2,3,1,4] original 5,2,3,1,4

new = original[:] new 5,2,3,1,4


144 12

. new. -
.

sorted()
-
. Python
sorted(). :

>>> original = [5, 2, 3, 1, 4]


>>> newer = sorted(original)
>>> print original
[5, 2, 3, 1, 4]
>>> print newer
[1, 2, 3, 4, 5]

sorted() .


, 2 ,
.
( , ). -
Python. ,
, , .
. Python
, .

, . Python
? ! , (tuple), -
. :

my_tuple = ("", "", "")

, , .
, ,
- . .

:
, ,
.
145

myTeacher ( ) ( ):

myTeacher Mr. Wilson

( ) ,
:

myFriends Curtis Karla Jenn Kim Shaun

(
, , ):

classMarks Math Science Reading Spelling

Joe 55 63 77 81

Tom 65 61 67 72

Beth 97 95 92 88

? ,
. :

>>> joeMarks = [55, 63, 77, 81]


>>> tomMarks = [65, 61, 67, 72]
>>> bethMarks = [97, 95, 92, 88]

>>> mathMarks = [55, 65, 97]


>>> scienceMarks = [63, 61, 95]
>>> readingMarks = [77, 67, 92]
>>> spellingMarks = [81, 72, 88]

, ?
,
:

>>> classMarks = [joeMarks, tomMarks, bethMarks]


>>> print classMarks
[[55, 63, 77, 81], [65, 61, 67, 72], [97, 95, 92, 88]]
146 12


(data structure) -
, -
. ,
, -
. -
.

, .
. classMarks
.
, classMarks
joeMarks, tomMarks bethMarks. :

>>> classMarks = [ [55,63,77,81], [65,61,67,72], [97,95,92,88] ]


>>> print classMarks
[[55, 63, 77, 81], [65, 61, 67, 72], [97, 95, 92, 88]]

. classMarks
, . -
in:

>>> for studentMarks in classMarks:


print studentMarks
[55, 63, 77, 81]
[65, 61, 67, 72]
[97, 95, 92, 88]

classMarks. -
studentMarks.
. .
( .)
, .
, .


( ) ?
, (joeMarks) ,
classMarks. :
147

>>> print classMarks[0]


[55, 63, 77, 81]

classMarks[0] Joe.
. ? -
.
Joe ( ) 2. ,
, :

>>> print classMarks[0][2]


77

- classMarks Math Science Reading Spelling


classMarks ( - Joe 55 63 77 81
0),
Tom 65 61 67 72
Joe, -
( 2), Beth 97 95 92 88
-
. , ,
classMarks[0][2], , .
classMarks Joe, Tom Beth ,
Math, Science, Reading Spelling. ,
. Python
. -
: , . ,
, , .

!

.

!
148 12

classMarks:
classMarks [0] [1] [2] [3]

classMarks[0] 55 63 77 81

classMarks[1] 65 61 67 72

classMarks[2] 97 95 92 88

, 77 classMarks[0][2].
, classMarks, -
, .
, , ,
.



Python, . -
,

4321
444- . ,


867-
5309 ,


1234
.
555-


6789
Python (dictionary)
555-
.
(key) (value). , -
, . , .
.
. -
, .
. ( , .)
(, ),
(, ).
Python.
:

>>> phoneNumbers = {}
149

,
, .
:

>>> phoneNumbers[""] = "555-1234"

, :

>>> print phoneNumbers


{'': '555-1234'}

, .
, , (
).
:

>>> phoneNumbers = {"": "555-1234"}

.
append(), . -
:

>>> phoneNumbers[""] = "555-6789"


>>> phoneNumbers[""] = "444-4321"
>>> phoneNumbers[""] = "867-5309"

>>> print phoneNumbers


{'': '444-4321', '': '555-1234', '': '555-6789', '':
'867-5309'}

, , , .
- :

>>> print phoneNumbers[""]


'555-6789'

, , , -
, .
150 12

. ,
.
.
, (
), , ,
.
, -
.
.
. ,
, . .
. ,
, , -
.
,
:

>>> print myList[3]


'eggs'
>>> print myDictionary[""]
'555-1234'

, Python ,
. , , ,
.
keys() :
>>> phoneNumbers.keys()
['', '', '', '']

, values() :
>>> phoneNumbers.values()
['444-4321', '555-1234', '555-6789', '867-5309']

, Python-, .
(
). -.
151

, , ,
( , , ),
(, ) ().
, , ,
, . ,
, .
. ,
(, , , ).
,
.
, , , . ,

. , ,
, .
. ,
, , ,
sorted() , :

>>> for key in sorted(phoneNumbers.keys()):


print key, phoneNumbers[key]
444-4321
867-5309
555-1234
555-6789

sorted(),
. , ,
.
, , , -
? ,
. .
, . -
. , :

>>> for value in sorted(phoneNumbers.values()):


for key in phoneNumbers.keys():
if phoneNumbers[key] == value:
print key, phoneNumbers[key]
152 12

444-4321
555-1234
555-6789
867-5309


, , .
.
del:
>>> del phoneNumbers[""]
>>> print phoneNumbers
{'': '444-4321', '': '555-6789', '': '867-5309'}

( ) clear():
>>> phoneNumbers.clear()
>>> print phoneNumbers
{}

-
in:
>>> phoneNumbers = {'': '444-4321',
'': '555-6789', '': '867-5309'}
>>> "" in phoneNumbers
True
>>> "" in phoneNumbers
False

Python-. ,
Python-.
, -
, .


:
;
;
;
, ;
153

;
;
;
;
Python-.

1. .
2. .
3.
.
4. , ?
5. ?
6. ?
7. ?
8. ?
9. ?
10.
?
11.
?

1. , .
. :
5 ( Enter):





:

2. , ,
, .
3. , -
:
:
154 12

4. ,
. , ,
. :
5 ( Enter):





:
? (1-5): 4
:
:

5. ,
, . , -
. :
(a/l)? a
:
: ,
!
(a/l)? l
:
,
(a/l)? l
: qwerty
.
13

. -
,
.
. ,
.
. ,
. ,
. , -
, , .


,
. , -
. ,
. Python , -
, def.
, , . .


13.1 , . -
.

13.1.
def printMyAddress():
print "Warren Sande"
print "123 Main Street" ()
print "Ottawa, Ontario, Canada"
print "K2M 2E9"
print
printMyAddress() ()
156 13

1 def.
, () :

def printMyAddress():

, . Python,
( for while if).
.
13.1 :
, . -
. -
.
-
, -
-
.
def , -

, def. -
, . ,
.

def printMyAddress():
print "Warren Sande"
print "123 Main Street"
2 3 print "Ottawa, Ontario, Canada"
print "K2M 2E9"
print
4
1 printMyAddress()

print "Done the function"

.
1. . .
2. .
3. .
4.
.
157


. ,
, .
, .
- , . 13.1
, . :

>>> =================== RESTART ===================


>>>
Warren Sande
123 Main Street
Ottawa, Ontario, Canada
K2M 2E9
>>>

-
:
print "Warren Sande"
print "123 Main Street"
print "Ottawa, Ontario, Canada"
print "K2M 2E9"
print

13.1 ?
, ,
, . ,
:
printMyAddress()
printMyAddress()
printMyAddress()
printMyAddress()
printMyAddress()


Warren Sande
123 Main Street
Ottawa, Ontario, Canada
K2M 2E9
Warren Sande
123 Main Street
158 13

Ottawa, Ontario, Canada


K2M 2E9
Warren Sande
123 Main Street
Ottawa, Ontario, Canada
K2M 2E9
Warren Sande
123 Main Street
Ottawa, Ontario, Canada
K2M 2E9
Warren Sande
123 Main Street
Ottawa, Ontario, Canada
K2M 2E9

,
. , ...

,
. ,
!
.
.
-
,
. , ,
.



, : -
, - !

, ,
?
. -

. .
, ,
. ,
. Warren Sande -
, .
.
159

- -





, . 13.2
,
. , , .
myName.
myName
. .
13.2 myName "Carter Sande".

13.2.
def printMyAddress(myName): myName
print myName
print "123 Main Street" "Carter
print "Ottawa, Ontario, Canada" Sande"
,
print "K2M 2E9" myName
print
printMyAddress("Carter Sande") "Carter Sande"

13.2 , :

>>> ===================== RESTART =====================


>>>
Carter Sande
123 Main Street
Ottawa, Ontario, Canada
K2M 2E9

, -
. :
160 13

printMyAddress("Carter Sande")
printMyAddress("Warren Sande")
printMyAddress("Kyra Sande")
printMyAddress("Patricia Sande")

.
, :

>>> ========================== RESTART ==========================


>>>
Carter Sande
123 Main Street
Ottawa, Ontario, Canada
K2M 2E9

Warren Sande
123 Main Street
Ottawa, Ontario, Canada
K2M 2E9

Kyra Sande
123 Main Street
Ottawa, Ontario, Canada
K2M 2E9

Patricia Sande
123 Main Street
Ottawa, Ontario, Canada
K2M 2E9


, -

?
.

, -
. ,
. .
161


13.2 . -
. , .
, , .
.

- -





, :
.
. :
.

, (
),
( ).


!
-
! - -





, ,
.
162 13

,
:
(13.3).

13.3.
def printMyAddress(someName, houseNum):
print someName
print houseNum,
print "Main Street"
print "Ottawa, Ontario, Canada"
print "K2M 2E9"
print

printMyAddress("Carter Sande", "45")


,
printMyAddress("Jack Black", "64")
printMyAddress("Tom Green", "22")
printMyAddress("Todd White", "36")

( ) , ,
.

?
, ,
. , --
, .
. -
(), ,
.

- -




163

,
, , - .
- .
, (),
. ,
, .






- -

- -





return. ,
, :

def calculateTax(price, tax_rate):


taxTotal = price + (price * tax_rate)
return taxTotal

taxTotal ,
. ? -
. :

totalPrice = calculateTax(7.99, 0.06)

calculateTax 8.4694, -
totalPrice.
, -
. ( ),
, :
164 13

>>> print calculateTax(7.99, 0.06)


8.4694
>>> total = calculateTax(7.99, 0.06) + calculateTax(6.59, 0.08)

, :

>>> calculateTax(7.49, 0.07)

,
.
. 13.4 -
calculateTax().
, .
. ,
, (=) .
, calculateTax().

13.4. ,
def calculateTax(price, tax_rate):
total = price + (price * tax_rate)
return total

my_price = float(raw_input (" : "))



totalPrice
totalPrice = calculateTax(my_price, 0.06)
print " = ", my_price, " = ", totalPrice

, 13.4. ,
, 0.06 ( 6%- ),
. , -
, ,
, .


, , -
, totalPrice, , total.
. , 2
YourTeacher = MyTeacher?
calculateTax totalPrice total
, . -
165

. MyTeacher
. -
Python ,
. r
che
Python u rTea
Yo
, ,
. :

.
.
, . , -
( ) ,
(scope).


13.4 price total .
, price, total tax_rate
calculateTax(). .
, price, total tax_rate calculateTax().
. 13.4 ,
price .

13.5.
def calculateTax(price, tax_rate): ,
total = price + (price * tax_rate)
return total

my_price = float(raw_input (" : ")) ,




totalPrice = calculateTax(my_price, 0.06)
print " = ", my_price, " = ", totalPrice
print price

Traceback (most recent call last):


File "C:/.../Listing_13-5.py", line 9, in <module>
print price
NameError: name 'price' is not defined
166 13

: price
calculateTax(). . -
, ,
.

price, my_price totalPrice
13.5 , . -
. -
13.5, my_price totalPrice
, ,
.
. ,
.
13.5
, , . -
; . ,
, :
?
13.6 my_price
calculateTax(). , .

13.6.
def calculateTax(price, tax_rate):
total = price + (price * tax_rate)
print my_price
return total my_price

my_price = float(raw_input (" : "))

totalPrice = calculateTax(my_price, 0.06)


print " = ", my_price, " = ", totalPrice

? ! ?
, , , Python

. . -
, ,
, .
167

:
print my_price

:
your_price = my_price

,
my_price. - ,
Python . :
my_price = my_price + 10

my_price , -
Python .
13.6 my_price,
. 13.7 , -
()
. .

13.7.
def calculateTax(price, tax_rate): my_price
total = price + (price * tax_rate)

my_price = 10000 my_price
print "my_price ( ) = ", my_price



my_price
return total


my_price = float(raw_input (" : "))
-
totalPrice = calculateTax(my_price, 0.06) my_price
print " = ", my_price, " = ", totalPrice
print "my_price ( ) = ", my_price

13.7 :

>>> ========================== RESTART ==========================


>>>
: 7.99 my_price
my_price ( ) = 10000

= 7.99 = 8.4694 my_price
my_price ( ) = 7.99
168 13

, my_price -
. -, calculateTax(),
10000. -, , -
, 7.99.



, -
Python -
. ,
.
, -
. ?
Python global, -
. :

def calculateTax(price, tax_rate): Python,


global my_price my_price

global Python
my_price, my_price.
, .


,
class Ball:

def __init__(self, color, size, direction):
self.color = color
self.size = size
self.direction = direction .
def bounce(self): Python
if self.direction == "down":
self.direction = "up" ,
myBall = Ball("red", "small", "down")
print "I just created a ball."
global. -
print "My ball is", myBall.size
print "My ball is", myBall.color
-
print "My ball's direction is ", myBall.direction
print "Now I'm going to bounce the ball" .
print
myBall.bounce()
, -
, , , .
. ,
, ().
-
. .
169


:
;
( );
;
;
;

;
.

1. ?
2. ?
3. ()?
4. ?
5. ?
6. ,
?

1. , , -
:

CCCC A RRRRR TTTTTTT EEEEEE RRRRR


C C A A R R T E R R
C A A R R T EEEE R R
C AAAAAAA RRRRR T E RRRRR
C C A A R R T E R R
CCCC A A R R T EEEEEE R R

, .
2. , , ,
, .
: . -
, .
170 13

3. my_price 13.7 , -
.
4. , -
, , ( -
5). . -
, .
:
1 : 3
5 : 6
10 : 7
50 : 2
2,03
14

-
, .
, (),
-
.

. .
.
, Python,
. Python
- . ,
( ) .
, .
, ,
. , ,
.


? , -
:

Mi U

.

, . .
? . -

U U U
mi mi mi
172 14

Python. , .
, , ,
. (actions). ,
, . .


, -
, .
. ,
, .
(properties).

:
, ;
, .
.

Python
Python , , , -
(attributes), , ,
(methods).
, , Python, ,
.
(, ) :

ball.color
ball.size
ball.weight

, .
( , )
:

ball.kick()
ball.throw()
ball.inflate()

, .
173

?
, ( ).
, ..
? , . .
:

print ball.size

ball.color = 'green'

, :

myColor = ball.color

, :

myBall.color = yourBall.color

?
, . ,
. ? ,
, .
, , -
.

= +
, (,
, , ) .
, .

?
, , -
. , -
Python, :
. .(). . -
.
, . -
!
174 14


Python
? , .
?
,

,
. -
. , -
.
, ,
. .
. , -

.
Python , ,
(class).

. (instance) .
. 14.1
Ball.

14.1. Ball
class Ball:
Python,
def bounce(self):
if self.direction == "":

self.direction = ""

14.1 bounce(),
. ?
.
.
. .


, . .
.
175

Ball:

myBall = Ball()

, :

myBall.direction = ""
myBall.color = ""
myBall.size = ""

.
.
bounce() . :

myBall.bounce()

, print,
, (14.2).

14.2. Ball
class Ball:
,
def bounce(self): ,
if self.direction == "":
self.direction = ""

myBall = Ball()
myBall.direction = ""

myBall.color = ""
myBall.size = ""

print " ."


print " ", myBall.size
print " ", myBall.color

print " ", myBall.direction
print " "
print
myBall.bounce()
print " ", myBall.direction

14.2:
176 14

>>> ========================== RESTART ==========================


>>>
.




bounce()

, bounce() (direction)
, , , .


size, color direction -
. .
.
.


(initializing) -
. -
,
, .

__init__(),
.
__init__() ,
(14.3).

14.3. __init__()
class Ball:
def __init__(self, color, size, direction):
self.color = color
self.size = size __init__(),
self.direction = direction
init
def bounce(self):

if self.direction == "":
self.direction = ""
177

myBall = Ball("", "", "")


print " ."

print " ", myBall.size
__init__()
print " ", myBall.color
print " ", myBall.direction
print " "
print
myBall.bounce()
print " ", myBall.direction

14.3, - print myBall
, :
14.2. - <__main__.Ball instance at 0x00BB83A0>

14.3
__init__().
,
__str__()
, . -
,

. ,
print myBall

__str__() .
Python
, ,
__xxxx__() Python!
. ,
! ,
Python . , -
Python, .
__init__(),
. .
, ,
.
__str__() Python,
print .
:
( __main__
);
(Ball);
, (0x00BB83A0).
178 14

>>> print myBall


, !

- , ,
__str__(), .
14.4.

14.4. __str__()

class Ball:
def __init__(self, color, size, direction):
self.color = color
self.size = size
self.direction = direction

__str__()
def __str__(self):
msg = ", " + self.size + " " + self.color + " !"
return msg
myBall = Ball("", "", "")
print myBall

14.4:

>>> ================= RESTART =================


>>>
, !

, <__main__.Ball instance at 0x00BB83A0>.


.

self
self,
. :

def bounce(self):
179

? , ,
? , -
:

cartersBall = Ball("", "", "")


warrensBall = Ball("", "", "")

warrensBall.bounce(),
, .
cartersBall warrensBall ? self
, .
(instance reference).
! warrensBall.bounce() -
, self. ,
? , Python
.
, .
:

Ball.bounce(warrensBall) self P
ython

bounce(), -
.
-


. .
-
, ,

Python .


warrensBall.bounce().

-
11 , - ,

. -
-
,
, -

. .


- . (
.) - .
:
cooked_level , , .
03 , 3 -
180 14

, 5 , 8 ! -
- ;
cooked_string , ;
condiments -, , ..
:
cook() , ;
add_condiment() - ;
__init__() ,
;
__str__()
.
.
__init__(), -, -
:

class HotDog:
def __init__(self):
self.cooked_level = 0
self.cooked_string = ""
self.condiments = []

. :
def cook(self, time):
self.cooked_level = self.cooked_level + time -

if self.cooked_level > 8:
self.cooked_string = ""
elif self.cooked_level > 5:
self.cooked_string = " "
elif self.cooked_level > 3:

self.cooked_string = " "
else:
self.cooked_string = ""

.
- :
myDog = HotDog()
print myDog.cooked_level
print myDog.cooked_string
print myDog.condiments
181

(14.5).

14.5. -
class HotDog:
def __init__(self):
self.cooked_level = 0
self.cooked_string = ""
self.condiments = []
def cook(self, time):
self.cooked_level = self.cooked_level + time
if self.cooked_level > 8:
self.cooked_string = ""
elif self.cooked_level > 5:
self.cooked_string = " "
elif self.cooked_level > 3:
self.cooked_string = " "
else:
self.cooked_string = ""
myDog = HotDog()
print myDog.cooked_level
print myDog.cooked_string
print myDog.condiments

nt >>
rint > r i nt >
pri

>Hell

>>Hel
# p

o if #
>>Hel
# p

l o if

#!/bin/env p
self.count=#!/bin/env py a text d
xt file, a ding a header
lo if
;
tten=1 thon # ate
yth on # a te
_ w ri !Bin agin
and
der Pag
i
e
nat
en P

foo
ea


ter import
t and reset a self.h

sys,

Python
tim

.
e, string # If
d reset the line coun

Ball HotDog, ,

no

arg
ume
mess
.
a ge i f l

nts w
given, print a helpful ere
, an

e: p
g
'Usa

t en(
oun ypri s
filena ge c nt gv)!=2: print
ys.ar
me'sys.exit( the pa
0)class # Increment

14.5 , :

>>> cooked_level
0
cooked_string
[] condiments
182 14

, , cooked_level , cooked_string
"", condiments .
, cook(). 14.5
:

print " -"


myDog.cook(4) 4
print myDog.cooked_level
print myDog.cooked_string

. :

>>>
0

[]
-
4

, cook() . cooked_level 0 4,
( "" " ").
. .
__str__(), -
. 14.6.

14.6. HotDog cook(), add_condiments() __str__()


class HotDog:
def __init__(self):
self.cooked_level = 0
self.cooked_string = ""
self.condiments = []

def __str__(self):
msg = ""
if len(self.condiments) > 0:
msg = msg + " "
for i in self.condiments:
__str__()
msg = msg+i+", "
msg = msg.strip(", ")
msg = self.cooked_string + " " + msg + "."
return msg
183

def cook(self, time):


self.cooked_level=self.cooked_level+time
if self.cooked_level > 8:
self.cooked_string = ""


elif self.cooked_level > 5:
self.cooked_string = " "
elif self.cooked_level > 3:
self.cooked_string = " "
else:
self.cooked_string = ""
def addCondiment(self, condiment):
self.condiments.append(condiment) add_condiments()

myDog = HotDog()
print myDog
print " 4 ..."
myDog.cook(4)
print myDog

,
print " 3 ..."
myDog.cook(3)
print myDog
print " , 10 ?"
myDog.cook(10)
print myDog
print " - "
myDog.addCondiment("")
myDog.addCondiment("")
print myDog

, .
14.5. ,
, \examples . -
, , . :

>>> =============================== RESTART ==============================


>>>
.
4 ...
.
3 ...
.
, 10 ?
.
-
.
184 14

.
-
-
. ,
,
!


, , -
() .
, :

myDog.cooked_level = 5

, :

myDog.cook(5)

(cooked_level = 0),
. cooked_level 5.
? ?
, :

: cooked_level
cooked_string.
, , ;
, -
, :
cooked_level = cooked_level - 2

. -
! , .
, cooked_level .


, -
, -
(data hiding). Python
, .
185

, , .
__init__().
__str__(),
.

, , -
: (polymorphism) (inheritance).
. , .

, ( )
. -
, .
, ,
. :

class Triangle:
def __init__(self, width, height):
self.width = width
Triangle
self.height = height ()

def getArea(self):
area = self.width * self.height / 2.0
return area

class Square:
def __init__(self, size): getArea()
self.size = size Square
()
def getArea(self):
area = self.size * self.size
return area

Triangle, Square getArea(). ,


:

>>> myTriangle = Triangle(4, 5)


>>> mySquare = Square(7)

getArea()
:
186 14

>>> myTriangle.getArea()
10.0
>>> mySquare.getArea()
49

getArea(),
-. .



. , ,
.
-
. , -
,
, .


() () () () (-) ()

, , , -
. , , .
, ,
, , . GameObject.
, name (), , ,
, pickUp() ( ).
.
. Coin
GameObject. GameObject,
name pickUp(). Coin
187

value ( ) spend() (
).
:

class GameObject:
def __init__(self, name):
self.name = name
GameObject
def pickUp(self, player):
# ,
#
Coin GameObject
class Coin(GameObject):
def __init__(self, value): __init__()
GameObject.__init__(self, "")
self.value = value GameObject

def spend(self, buyer, seller):


# , spend()
# Coin
#


.
, . , -
. ,
. ,
.
(code stubs).
- .

,
!
.
, , , -
, .
Python pass,
, . -
:
188 14

class Game_object:
def __init__(self, name):
self.name = name

def pickUp(self):
pass
# ,
#

class Coin(Game_object):
def __init__(self, value):
pass
GameObject.__init__(self, "coin")
self.value = value

def spend(self, buyer, seller):


pass
# ,
#
#

,
. . -
,
, .


:
;
;
;
;
__init__() __str__();
;
;
.

1. ?
2. ?
189

3. ?
4. ?
5. ?
6. ?
7. ?

1. BankAccount .
(), ( )
( ).
, .
2. InterestAccount .
BankAccount ( -
).
. , addInterest()
.
15

, .
, , . ,
Pygame .


(module) , , - -
.
, -
(modular).
LEGO.

.
Python .
.
, .
, ,
.


,
, ,
? ?
:
, ;
.
, -
;
191

.
-
, , LEGO .

13, , ,
. . -

. ,
, .
, . ,
, ,
.


. Python-, , , -
15.1. IDLE- my_module.py.

15.1.
# "my_module.py"
#
def c_to_f(celsius):
fahrenheit = celsius * 9.0 / 5 + 32
return fahrenheit

! ! c_to_f(),
.
my_module.py .


,
Python, . -
192 15

Python import.
:

import my_module

,
.
c_to_f().
( ).
,
, import. -
15.2 my_module.py.

15.2.
import my_module my_module
c_to_f()
celsius = float(raw_input (" : "))
fahrenheit = c_to_f(celsius)
print " ", fahrenheit, " "

IDLE- .
modular.py , , .
, my_module.py.
? :

>>> ========================= RESTART =========================


>>>
: 34

Traceback (most recent call last):


File "C:/MyPythonPrograms/modular.py", line 4, in <module>
fahrenheit = c_to_f(celsius)
NameError: name 'c_to_f' is not defined

! ? ,
c_to_f() . , my_module, -
.
, Python ,
. , ,
:
193

fahrenheit = c_to_f(celsius)

fahrenheit = my_module.c_to_f(celsius)

, c_to_f() my_module.
, .



, -
(namespaces). - :

, >>> from time import sleep


,
>>> from pygame import display
.

? from

,
, - .

. ,
,
. , ,
(, , ), .
, .


!
194 15

, , , -
, . ,
. ,
, .
,
. : , , , ,
. , -
, . ,
, , .
, . :
, .





,
,
.
.


,
.

.
: , , .
, , .
, .
(,
) , (, ) .
195

,

.


, ,
,
. ,
!
,
. ,

.
.
. ,
. -
-

.
-

Python.
: , ,
.
, .
, .
. -, :

import StephenLeacock
196 15

StephenLeacock -
. , ,
, . -
:

call_to_office(StephenLeacock.Fred)

-
(StephenLeacock), (Fred). -
.
, :

fahrenheit = my_module.c_to_f(celsius)

(my_module) (c_to_f).

from
-, :

from StephenLeacock import Fred

, Fred StephenLeacock
, :

call_to_office(Fred)

Fred , -
StephenLeacock Fred.
-
Fred StephenLeacock.
:

from StephenLeacock import *

(*) . .
,
, .

!
, . !
, . -
, .
197


, . ,
? !
Python , -
, ,
( ) . , Python
, .
Python- (Python Standard Library).
?
, Python , -
. Python-
. ,
.
, ( print, for if-else) -
Python,
Python.
( ,
) , .
! , -
, , .
.
.

Tim e
time -
. , -
. (
.)
...
sleep() time.
.
,
sleep(). .
sleep() 15.3.
, , , .
198 15

15.3.
import time
print "",
time.sleep(2)
print "",
time.sleep(2)
print "",
time.sleep(2)
print "?"

time. sleep().
, time,
. , , sleep(),
time.sleep(). :

import time
sleep(5)

, sleep() . -
:

NameError: name 'sleep' is not defined

, :

from time import sleep

Python (
, ) sleep time
.
sleep() time. :

from time import sleep


print ', 5 ...'
sleep(5)
print ' '

-
( ),
, , (*) -
:

from time import *


199

.
, time, .
, .
, 8 (.8.6)?
, time.sleep(1).


random .
. random :

>>> import random


>>> print random.randint(0, 100)
4
>>> print random.randint(0, 100)
72

random.randint()
. 0 100, -
0 100. random.randint() 1
.
random.random().
, -
0 1:

>>> print random.random()


0.270985467261
>>> print random.random()
0.569236541309

0 10 10:

>>> print random.random() * 10


3.61204895736
>>> print random.random() * 10
8.10985427783


:
;
;
200 15

;
;
-
;
.
, Python-.


1. ?
2. ?
3. Python-?
4. , __________.
5. time, -
( , )?

1. , -
, 13. ,
.
2. 15.2 , c_to_f() -
. ,
:
fahrenheit = c_to_f(celsius)

fahrenheit = my_module.c_to_f(celsius)

3. ,
1 20 .
4. , 30 3-
.
16

: ,
, , , , , . ,
!
Python.
,
. -
.

Pygame
( ) - .
,
, . -
Python-, Pygame.

Pygame ,
.
. Pygame -
, .
, .
www.pygame.org.

Pygame
, .
, (16.1).
202 16

16.1. Pygame-
import pygame
pygame.init()
screen = pygame.display.set_mode([640, 480])

. ? -
( ), .
, . ?
, Pygame .
, . Py
game (event loop), ,
- , ,
. Pygame- -
. ,
.
while. -
, . Pygame- , ,
,
(Windows) (Mac OS).
Linux ,
GUI- . , Linux, ,
, , .
16.2 Pygame-,
.

16.2. Pygame-
import pygame
pygame.init()
screen = pygame.display.set_mode([640, 480])
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()

, Pygame-, -
, .
203

while?
Pygame-. 18, Pygame-
.


, Pygame-, , ,
. [640, 480] 16.2
: 640 480 . -
. , ,
16.3.

16.3.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255,255,255])
pygame.draw.circle(screen, [255,0,0],[100,100], 30, 0)

pygame.display.flip()
running = True
!
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
204 16

flip
Pygame- ( -
screen, 3 16.3)
. ,
.
-
,
.
pygame.display.flip().
, , , -
( , ).
.
, . . -
, .


16.3 :

, pygame.draw.circle() .
:
( ,
3 screen);
. ( , -
[255, 0, 0]);
205

( [100, 100],
100 100 );
(
30 );
( width = 0, , ).
.


picture element
. .
,
.
, .



,
.

?
, !
. -
768 ,
1024. , -
1024 768.
, .
Pygame
, :
? Pygame (surface) , .
(display surface) , .
16.3 screen. Pygame-
, -
. , -
( ).
, .
, (double-buffered).

206 16

. , ,
, .

Pygame
Pygame ,
. RGB. R,
G B (red), (green) (blue) .
, , , -
: , .
. , -
0 255. , -
0 255. 0, ,
, . 255,
, . [255, 0,
0] . -
[0, 255, 0], [0, 0, 255].
, [150, 150, 150], . ,
.


Pygame , -
, [R, G, B]. 600
. , -
, colordict.py
.
,
:

from pygame.color import THECOLORS

(
):

pygame.draw.circle(screen, THECOLORS["red"],[100,100], 30, 0)

, -
, , colormixer.py,
207

\examples. -
, .


255? 0 255 256
(, ).
? 200, 300
500?
,
8 .
. , ,
(byte),
, .
,
.
. ,
.
.
.
8 ,
, 16
(2 ).
, , 8 .
(, ),
8 , 24 .
24- . 24 ,
8 .


,
. : x
( ), y ( ). -
Pygame [0, 0], .

[320, 240] ,
.
.

x, y.
208 16

640 480.
, [320, 240].
320 240 .

.
16.4.

16.4.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])
pygame.draw.circle(screen, [255,0,0],[320,240], 30, 0)
pygame.display.flip()

running = True [100, 100] [320, 240]
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()

[320, 240]. -
16.3 .


draw Pygame
. .
, .
Pygame rect ( rectangle
), . -
, :

Rect(left, top, width, height)


209

. :
my_rect = Rect(250, 150, 300, 200)

,
250, 150. -
300, 200.
.
5 16.4 , :
pygame.draw.rect(screen, [255,0,0], [250, 150, 300, 200], 0)


( )

(
) Rect Pygame.
:
my_list = [250, 150, 300, 200]
pygame.draw.rect(screen, [255,0,0], my_list, 0)

:
my_rect = pygame.Rect(250, 150, 300, 200)
pygame.draw.rect(screen, [255,0,0], my_rect, 0)

. ,
, :

150

250 200

300

, pygame.draw.rect -
. , rect .
pygame.draw.circle
, .
210 16

count , and reset the line # Paginate a t


page count nv python
#! bin/e ex
file, addin
g a header and footer im
the por
t

t
/
ime, string # If
s, t

t
# Incremen
no

sy

a rg
Rect(left, top,

uments were
width, height) ,
=0def

Rect: ven
tten

wr i gi
, pr
 : top, left, bottom, right; i
r_
tter:self.heade

nt
 : topleft, bottomleft, topright, bottomright;

a helpful me
 : midtop, midleft, midbottom, midright;
 : center, centerx, centery;
rma

sa

s
>> tni
 : size, width, height.
ge
if le

rp
lleH>
rFo

n(sys.arg o if #

v)!=2: print 'Usa


inte >> > tn

. ,
e+1Pr

olleH
irp
if #

>> tni

,
age=self.pag

rp
lleH>
o if #

ge:
,

pyp
elf.p

ri
nt
. fil
;s

ena
me '
1

t= n sys.
cou the line count et ex
self.header_written=1 ; self. lass # Increment the page count, and res
it(0)c


, ,
. ,
.
.
2
2:

pygame.draw.rect(screen, [255,0,0], [250, 150, 300, 200], 2)

, .
.

?
?
16.5. 16.4
.

16.5. draw.rect
import pygame, sys, random
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])
for i in range (100):
211

width = random.randint(0, 250)


height = random.randint(0, 100)
top = random.randint(0, 400)
left = random.randint(0, 500)
pygame.draw.rect(screen, [0,0,0], [left, top, width, height], 1)
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()

, . :

, ? 100
. ,
, 16.6.

16.6.
import pygame, sys, random
from pygame.color import THECOLORS
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])
212 16

for i in range (100):


width = random.randint(0, 250); height = random.randint(0, 100)
top = random.randint(0, 400); left = random.randint(0, 500)
color_name = random.choice(THECOLORS.keys())
color = THECOLORS[color_name]
line_width = random.randint(1, 3)
pygame.draw.rect(screen, color, [left, top, width, height], line_width)
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()

.
, ,
, !


, , .
, .

-


.
-

, , !
.
,
.
,
.
, .

, Pygame-.

pygame.draw.sinewave() ,
. , ,
213

.
16.7 .

16.7.
import pygame, sys

import math , sin()
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255]) x = 0
639
for x in range(0, 640):
y = int(math.sin(x/640.0 * 4 * math.pi) * 200 + 240)
pygame.draw.rect(screen, [0,0,0],[x, y, 1, 1], 1)
pygame.display.flip()
y
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:

running = False
pygame.quit()

1
1. , 1, 0.
, -
, .
214 16


, , , -
.
,
( ). , ,
.
, . Pygame ,
, , .
pygame.draw.lines() :
surface, ;
color;
closed , .
, False;
list;
width.
pygame.draw.lines() :

pygame.draw.lines(screen, [0,0,0],False, plotPoints, 1)

for ,
draw.lines(). draw.
lines() for. 16.8.

16.8.
import pygame, sys
import math
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255]) y
plotPoints = []
for x in range(0, 640):
y = int(math.sin(x/640.0 * 4 * math.pi) * 200 + 240)

plotPoints.append([x, y])

pygame.draw.lines(screen, [0,0,0],False, plotPoints, 1)
pygame.display.flip()
running = True
while running:
draw.lines()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
215

, .
, 2:


, , ?
Pygame.
16.9 draw.lines() -
. , , .
! \examples
, . ,
216 16

, dots
\examples .

16.9. ,
import pygame, sys
pygame.init()

dots = [[221, 432], [225, 331], [133, 342], [141, 310],


[51, 230], [74, 217], [58, 153], [114, 164],
[123, 135], [176, 190], [159, 77], [193, 93],
[230, 28], [267, 93], [301, 77], [284, 190],
[327, 135], [336, 164], [402, 153], [386, 217],
[409, 230], [319, 310], [327, 342], [233, 331],
[237, 432]]

screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])
pygame.draw.lines(screen, [255,0,0],True, dots, 2)
pygame.display.flip()
running = True
while running:

for event in pygame.event.get(): closed = True
if event.type == pygame.QUIT:
running = False
pygame.quit()


.
, . -
, Surface.
set_at(), .
, :

screen.set_at([x, y], [0, 0, 0])

( 8 -
16.7), ,
. Surface.get_at()
. :

pixel_color = screen.get_at([320, 240])

screen .
217

, -
. ,
. , ,
. -
Pygame image.
: ,
,
,

,
.
be ac h_
images, \examples. - ba ll.p ng

beach_ball.png. - ww w. ma nn ing .co m/ bo
ok s/
, Windows he llo -w or ld- se co nd -ed
iti on .
c:\Program Files\helloworld\
examples\images\beach_ball.png.
beach_ball.png ,
. Python
. beach_ball.png
, 16.10 .

16.10. Pygame-
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])
my_ball = pygame.image.load("beach_ball.png")
screen.blit(my_ball, [50, 50])
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()

Pygame-
:
218 16

16.10 5 6. -
16.316.9. draw ,
.
5 pygame.image.load()

my_ball.
. ( .)

! , .

screen. ( 3.) 6
my_ball screen. -
display.flip()
.
, . ! 6 16.10
: screen.blit(). blit?


-
(
). -

(blitting).
(blit) ( ,
) . -
-
.
, , - .
219

Pygame . -
my_ball screen.
6 16.10
(50, 50). , 50
50 . surface -
rect .
50 ,
50 .
!
, Pygame-, -
. , ! -
( )
. .
. .
, , 100 .
- ( ) , -
. 100
100. ,
, .
16.10 16.11. (
8, 9 10 while.)

16.11.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])
my_ball = pygame.image.load('beach_ball.png')
screen.blit(my_ball,[50, 50])
pygame.display.flip()
pygame.time.delay(2000)
screen.blit(my_ball,[150, 50])
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
220 16

, . ? .
:

,
. , , .
!

.
1. .
2. .
. .
. ?


, ,
. ? ,
, . ? ,
, .
, , . - , -
. ? ,
. ,
.
. 16.11
16.12. .
221

16.12.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])

my_ball = pygame.image.load('beach_ball.png')
screen.blit(my_ball,[50, 50])
pygame.display.flip()
pygame.time.delay(2000)
screen.blit(my_ball, [150, 50])
pygame.draw.rect(screen, [255,255,255], [50, 50, 90, 90], 0)
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()

10, .
90 90 ,
. 16.12 ,
.

?
( ) . ,
? ? ,
. , ,
,
.
, .
, , , .
, .
, .


, !
. -
, .
.
222 16

, , -
(
). 16.12
16.13.

16.13.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])
my_ball = pygame.image.load('beach_ball.png')
x = 50 xy
( )
y = 50
screen.blit(my_ball,[x, y]) for
pygame.display.flip()
for looper in range (1, 100): time.delay
pygame.time.delay(20) 2000 20
pygame.draw.rect(screen, [255,255,255], [x, y, 90, 90], 0)
x = x + 5
screen.blit(my_ball, [x, y])
pygame.display.flip()

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()

,
.


.
.
, x? -
. x = 640 (
) , , .
for 10 16.13 :

for looper in range (1, 200):


223

, ,
! .
.
.
, .


, -
.
, .
, , -
0 ( - ).
-
640
,
. ,
- ,

(
-
550
). , 90

.
, ( )
550. :
( Pygame-).
while, , , , -
( while );
5,
speed,
. ,
10.
16.14.

16.14.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
224 16

screen.fill([255, 255, 255])


my_ball = pygame.image.load('beach_ball.png')
x = 50
y = 50
x_speed = 10

running = True
speed
while running:

for event in pygame.event.get(): while
if event.type == pygame.QUIT:
running = False

pygame.time.delay(20)
pygame.draw.rect(screen, [255,255,255], [x, y, 90, 90], 0)
x = x + x_speed
if x > screen.get_width() - 90 or x < 0:
x_speed = - x_speed
screen.blit(my_ball, [x, y])
pygame.display.flip()
pygame.quit() ,

19 20. 19 (if x > screen.


get_width() - 90 or x < 0:) , , -
20
(x_speed = - x_speed).
, .


,
.
.
16.15.

16.15.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])
my_ball = pygame.image.load('beach_ball.png')
x = 50
y = 50
225

x_speed = 10
y_speed = 10
y (
running = True )
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.time.delay(20)
pygame.draw.rect(screen, [255,255,255], [x, y, 90, 90], 0)
x = x + x_speed
y = y + y_speed y (
if x > screen.get_width() - 90 or x < 0: )
x_speed = - x_speed
if y > screen.get_height() - 90 or y < 0:
y_speed = -y_speed

screen.blit(my_ball, [x, y])


pygame.display.flip()
pygame.quit()

9 (y_speed = 10), 18 (y = y +
y_speed), 21 (if y > screen.get_height() - 90 or y < 0:) 22 (y_speed = -y_speed).
, !
:
(x_speed y_speed).
, -
;
. 16.15 20. -
, .
0.02.
. , .
,
.


.
. ,
.
.
16.6.
226 16

16.16.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])
my_ball = pygame.image.load('beach_ball.png')
x = 50
y = 50
x_speed = 5
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.time.delay(20)
pygame.draw.rect(screen, [255,255,255], [x, y, 90, 90], 0)
x = x + x_speed
if x > screen.get_width():
x = 0
screen.blit(my_ball, [x, y])
pygame.display.flip()
pygame.quit()

17 (if x > screen.get_width():) 18 (x = 0) -


,
.
, , , -
[0, 50]. .
18 (x = 0) x = -90 , .


! ! :
Pygame;
;
;
;
,
;
, ;
.
227


1. RGB- [255, 255, 255]?
2. RGB- [0, 255, 0]?
3. Pygame- ?
4. Pygame- , ?
5. ?
6. Pygame- [0, 0]?
7. Pygame- 600 400-
[50, 200]?

A D

B 400

C E F
600

8. [300, 50]?
9. Pygame- (
) ?
10.
, , ?

1. . Pygame -
, , , -
. .
Pygame www.
pygame.org/docs/ref/draw.html. , -
(
Pygame), . pygame_draw.html.
, Python (
6). ,
IDLE :
>>> import pygame
>>> help()
help> pygame.draw
228 16

.
2. .
\examples\images, -
. .
3. 16.15 16.16 x_speed
y_speed, .
4. 16.15,
, .
5. 16.516.9 ( , -
) pygame.display.flip
while. .
while , :
pygame.time.delay(30)
17


Pygame .
(sprites),
. , , -
, , ,
.

,
. ,
, ,
, .
, .
, .


,
.
Sprite Pygame
, www.pygame.org/docs/tut/
SpriteIntro.html:

,
,
. ,
, .
-
, .
, -
.
.
230 17

, Pygame.
, , -
, Pygame .
.
. -
? ,
, Pygame- sprite.
?
, -
, -
. :
image ;
rect , .
, Pygame-
( ) .
Sprite
sprite Pygame Sprite. (,
?)
. pygame.sprite.Sprite -
. MyBallClass. :

class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
,
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()

self.rect.left, self.rect.top = location

. loca-
tion [x, y], .
, (x y) -
. left top ,
.
, MyBallClass, . (,
,
.)
Pygame-. , -
231

, .
:

img_file = "beach_ball.png"
balls = []
for row in range (0, 3):
for column in range (0, 3):
location = [column * 180 + 10, row * 180 + 10]
ball = MyBallClass(img_file, location)
balls.append(ball)

, . (
? .)

for ball in balls:


screen.blit(ball.image, ball.rect)
pygame.display.flip()

17.1.

17.1.
import sys, pygame
class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file) ball
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location

size = width, height = 640, 480


screen = pygame.display.set_mode(size)
screen.fill([255, 255, 255])
img_file = "beach_ball.png"
balls = []
for row in range (0, 3):
for column in range (0, 3):
location = [column * 180 + 10, row * 180 + 10]
ball = MyBallClass(img_file, location)
balls.append(ball)

for ball in balls:


screen.blit(ball.image, ball.rect)
pygame.display.flip()
232 17

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()

Pygame- :

.
10 11,
Pygame-? :

screen = pygame.display.set_mode([640,480])

size = width, height = 640, 480


screen = pygame.display.set_mode(size)

, ,
width height, .
, size, -
, width height. ,
, Python
.
233

, Python -.
, ( -
). , Python,
. 10 -
, .
move()
MyBallClass,
. move() :

def move(self): -

self.rect = self.rect.move(self.speed) ,
if self.rect.left < 0 or self.rect.right > width: -
x
self.speed[0] = -self.speed[0]
-

if self.rect.top < 0 or self.rect.bottom > height: ,
self.speed[1] = -self.speed[1]
y

(, )
move(). speed, ,
( ) . -
, speed
x y. ,
, .
MyBallClass, speed -
move():

class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, speed): speed
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
,
self.rect.left, self.rect.top = location
self.speed = speed speed

def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > width:
self.speed[0] = -self.speed[0]

if self.rect.top < 0 or self.rect.bottom > height:
self.speed[1] = -self.speed[1]
234 17

, 2 (def __init__(self, image_file, loca-


tion, speed):). , 7 (self.speed = speed)
move() 9 15.

:

speed = [2, 2]
ball = MyBallClass(img_file, location, speed)

, (
), , -
. random.choice():

from random import *


speed = [choice([-2, 2]), choice([-2, 2])]

2 2.
17.2.

17.2.
import sys, pygame
from random import *

class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, speed):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed


def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > width:
self.speed[0] = -self.speed[0]

if self.rect.top < 0 or self.rect.bottom > height:


self.speed[1] = -self.speed[1]

size = width, height = 640, 480


screen = pygame.display.set_mode(size)
screen.fill([255, 255, 255])
235

img_file = "beach_ball.png"

balls = []

for row in range (0, 3):


for column in range (0, 3):
location = [column * 180 + 10, row * 180 + 10]
speed = [choice([-2, 2]), choice([-2, 2])]
ball = MyBallClass(img_file, location, speed)
balls.append(ball)

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.time.delay(20)
screen.fill([255, 255, 255])
for ball in balls:
ball.move()
screen.blit(ball.image, ball.rect)
pygame.display.flip()
pygame.quit()

. 32 (balls.
append(ball)) .
.
( )
.
, , ,
. ,
, !

!

. , ,
.
, -
, ,
. Pygame
. Pygame
(collision detection).
236 17

Pygame -
. ,
- -
- , .

. - -
. -
, -
.
,
, ,
.
( ).
. ,
. ,
, Pygame- group.
, ,
( 17.2) animate().
.
(17.3).

17.3.

import sys, pygame
from random import *

class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, speed):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed

def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > width:
self.speed[0] = -self.speed[0]
if self.rect.top < 0 or self.rect.bottom > height:
self.speed[1] = -self.speed[1]
237

def animate(group):
screen.fill([255,255,255])
for ball in group:
group.remove(ball)
if pygame.sprite.spritecollide(ball, group, False):
ball.speed[0] = -ball.speed[0]
ball.speed[1] = -ball.speed[1] animate()


group.add(ball)
ball.move()
screen.blit(ball.image, ball.rect)
pygame.display.flip()
pygame.time.delay(20)
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
screen.fill([255, 255, 255])
img_file = "beach_ball.png"
group = pygame.sprite.Group()

for row in range (0, 2):
for column in range (0, 2):
location = [column * 180 + 10, row * 180 + 10]
speed = [choice([-2, 2]), choice([-2, 2])]
ball = MyBallClass(img_file, location, speed)
group.add(ball)

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
animate(group) animate(),
pygame.quit()

. Pygame-
sprite spritecollide(), -
.
.
1. .
2. , .
3. .
for 21 29 (
animate()). spritecollide()
238 17

, .
, .
, .
? :
, ;
.

? -
animate(). ,
, ,
,

. -,

, .. ,
2 5,

20 50.
.
, 28 (ball.move())
:

def animate(group):
screen.fill([255,255,255])
for ball in group:
ball.move()
for ball in group:
group.remove(ball)

if pygame.sprite.spritecollide(ball, group, False):
ball.speed[0] = -ball.speed[0]

ball.speed[1] = -ball.speed[1]

group.add(ball)

screen.blit(ball.image, ball.rect)
pygame.display.flip()
pygame.time.delay(20)

, , .
, , ( time.de-
lay()), , , ..
239


, , -
. , spritecollide() -
, rect, .

. :

img_file = "b_ball_rect.png"

(
),
. spritecollide() ,
.
, . -
.
, :




240 17

. (
.) -
.
, Pygame,
.
,
, .
, Pygame (
).
.



time.de-
00:00:00:12
lay(). ,
.
(-
), (-
). ,
, . ,
,
. ,
. ,
25 25.
, 15.
while, time.delay()
. , time.delay(20)
20. 20 + 15 = 35,
1000. 35, 1000
35, 28.57. ,
29 . (frame),
, ,
(frame rate) (frames per second).
29 , 29/.
, -
. . ,
( -
241

), . ,
, .
15 10 20.
. , Pygame- time
Clock.

pygame.time.Clock()
pygame.time.Clock()
.
, :
! !..

Clock. -
:

clock = pygame.time.Clock()

,
, :

clock.tick(60)

clock.tick() .
, , . , -
, 60 . ,

. 60 , 1000 / 60= 16.66
( 17). 17, -
, clock ,
.
, -
. ,
. ,
90 , -
10 .
Pygame- -
20 30 . -
, ,
, 20 30 .
242 17

.
clock.tick(30).

, , clock.get_
fps(). , 30 ,
( ,
).
, clock.tick ( 200/).

clock.get_fps(). ( .)


, . , -
, , ,
, ,
.
, , clock.tick(30), -
30 . clock.get_fps(), -
, 20 , ,
, .
, -
, .
( ) speed, . ,
speed.
? -
. 10,
30 , 20
, :

object_speed = current_speed * (desired fps / actual fps)


object_speed = 10 * (30 / 20)
object_speed = 15

, , 10, -
15.
17.4 ,
Clock get_fps().
243

17.4. Clock get_fps()


import sys, pygame
from random import *
class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, speed):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed
ball

def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > width:
self.speed[0] = -self.speed[0]
if self.rect.top < 0 or self.rect.bottom > height:
self.speed[1] = -self.speed[1]
time.delay()
def animate(group):
screen.fill([255,255,255])
for ball in group:
ball.move()
for ball in group:
group.remove(ball)
if pygame.sprite.spritecollide(ball, group, False): animate
ball.speed[0] = -ball.speed[0]
ball.speed[1] = -ball.speed[1]
group.add(ball)
screen.blit(ball.image, ball.rect)
pygame.display.flip()

size = width, height = 640, 480


screen = pygame.display.set_mode(size)
screen.fill([255, 255, 255])
img_file = "beach_ball.png" Clock
clock = pygame.time.Clock()
group = pygame.sprite.Group()
for row in range (0, 2):
for column in range (0, 2):
location = [column * 180 + 10, row * 180 + 10]
speed = [choice([-4, 4]), choice([-4, 4])]
ball = MyBallClass(img_file, location, speed)
group.add(ball) #
244 17

running = True while


while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:

running = False
frame_rate = clock.get_fps()
print "frame rate = ", frame_rate
animate(group) (
clock.tick(30) )
pygame.quit() clock.tick

Pygame . -
, Pygame , -
( )
.


:
Pygame-
;
;
;
pygame.clock .

1. ?
2.
?
3. .
4. .
5. pygame.clock ,
pygame.time.delay()?
6. ?

, , -
. , , . , -
!
18

.
raw_input() EasyGui
( 6). , ,
Pygame-, .

(events). , Pygame-
. ,
, ,
Enter.

? , , : , .
, .
, :
;
;
.

, .
, - (event-driven),
-. , ,
. .
Windows (
GUI-). ,
. , .
-
. .
246 18


- ,
. ,
. -
. 8 ,
.
. (event loop).
Pygame-, ,
while. , , .
. (, ,
.)


-
,
. ? .

, ,
-
. , - -
.
, .

, .


GUI- ,
. ,
, ,
. . ,
, .
. -
, .
.
.
.
mouseMove, mouseClick.
- .
,
247

keyDown.
, mouseMove.
, .
Pygame, ,
, Pygame-. Python- -
. 20 PyQ.
Pygame-. , (
)
. , , ,
, .

. ,
. Pygame-
KEYDOWN. 16.15, -
, .
, :
;
clock.tick() time.delay().
, -
__init__() move().
while clock.tick(30).
18.1.

18.1.
Clock.tick()
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
background = pygame.Surface(screen.get_size())
background.fill([255, 255, 255])
clock = pygame.time.Clock()

class Ball(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
Ball
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file) move()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed
248 18

def move(self):
if self.rect.left <= screen.get_rect().left or \
Ball
self.rect.right >= screen.get_rect().right:
self.speed[0] = - self.speed[0] move()
newpos = self.rect.move(self.speed)
self.rect = newpos

my_ball = Ball('beach_ball.png', [10,0], [20, 20])



running = True

while running: ,
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
clock.tick(30)
screen.blit(background, (0, 0))
my_ball.move()

screen.blit(my_ball.image, my_ball.rect)
pygame.display.flip()
pygame.quit()

, - -
. , , ,
: , ,
, .
. -
screen.fill() background
.
screen. ,
.

,
, . Pygame
. pygame.event.
Pygame- ( while). , -
QUIT:

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
249

pygame.event.get() . for -
, QUIT,
running False. while
. , ,
Pygame-.
.
, KEYDOWN.
:

if event.type == pygame.KEYDOWN

if , elif,
7:

while running:

for event in pygame.event.get():


if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN: ,
# -

- , ?
, ,
. :

while True:

for event in pygame.event.get(): 10
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
10
if event.key == pygame.K_UP:
my_ball.rect.top = my_ball.rect.top - 10
elif event.key == pygame.K_DOWN:
my_ball.rect.top = my_ball.rect.top + 10

K_UP K_DOWN Pygame .


, 18.2.

18.2. ,
import pygame, sys

pygame.init()
250 18

screen = pygame.display.set_mode([640,480])
background = pygame.Surface(screen.get_size())

background.fill([255, 255, 255])
clock = pygame.time.Clock()

class Ball(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
Ball
self.speed = speed
move()
def move(self):
if self.rect.left <= screen.get_rect().left or \
self.rect.right >= screen.get_rect().right:
self.speed[0] = - self.speed[0]
newpos = self.rect.move(self.speed)
self.rect = newpos

my_ball = Ball('beach_ball.png', [10,0], [20, 20])


running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:

if event.key == pygame.K_UP:
my_ball.rect.top = my_ball.rect.top - 10
elif event.key == pygame.K_DOWN:
my_ball.rect.top = my_ball.rect.top + 10

clock.tick(30)
screen.blit(background, (0, 0))
my_ball.move()

screen.blit(my_ball.image, my_ball.rect)
pygame.display.flip()
pygame.quit()

18.2 . -
?

, ,
. ,
251

, .
KEYDOWN,
Pygame- KEYDOWN.
(key repeat). ,
.
( ). :

delay = 100
interval = 50
pygame.key.set_repeat(delay, interval)

delay Pygame,
, interval ,
KEYDOWN.
18.2 ( pygame.init, -
while) , .


, KEYDOWN -
K_UP K_DOWN. ?
? , .
Pygame.
Pygame:
www.pygame.org/docs/ref/event.html
:
www.pygame.org/docs/ref/key.html
, :
QUIT;
KEYDOWN;
KEYUP;
MOUSEMOTION;
MOUSEBUTTONUP;
MOUSEBUTTONDOWN.
Pygame . ,
K_UP K_DOWN. ,
K_, , :
252 18

K_a, K_b .. ( );
K_SPACE;
K_ESCAPE
..

,
- . ,
. ,
. -
.
:
MOUSEBUTTONUP;
MOUSEBUTTONDOWN;
MOUSEMOTION.
Pygame-.
rect.center. -
.
while , , ,
:

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEMOTION:
my_ball.rect.center = event.pos

, . -
18.2 . event.pos
( x y) . .
, ,
MOUSEMOVE.
rect.center .
.
- ,
Pygame-, .
253

,
. (dragging).
( MOUSEDRAG) ,
, .
? -
.
MOUSEBUTTONDOWN, MOUSEBUTTONUP.
.
; held_down. :

held_down = False
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
,
held_down = True
elif event.type == pygame.MOUSEBUTTONUP:
held_down = False
elif event.type == pygame.MOUSEMOTION:
if held_down:
my_ball.rect.center = event.pos

( ) -
elif. while -
18.2. , , .
-

-
!

, , -
! , ,
, .
, .
.


, .
,
254 18

.
,
.

.
Pygame- .
, .
? -
(user event).
Pygame . ,
0, , .
, MOUSEBUTTONDOWN KEYDOWN, .
Pygame , .
, ,
. .
Pygame set_timer():

pygame.time.set_timer(EVENT_NUMBER, interval)

EVENT_NUMBER , interval ( ), -
.
EVENT_NUMBER?
, Pygame - .
Pygame- .
:

>>> import pygame


>>> pygame.USEREVENT
24

, Pygame 0 23, ,
24. , 24 -
. ? Pygame-:

>>> pygame.NUMEVENTS
32

NUMEVENTS , Pygame-
32 ( 0 31). 24 , 32. -
:
255

pygame.time.set_timer(24, 1000)

- USEREVENT ,
. :

pygame.time.set_timer(pygame.USEREVENT, 1000)

USER-
EVENT+ 1 .. 1000 1000,
. , .
.
, .
,
, . -
18.2 18.3.

18.3.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
background = pygame.Surface(screen.get_size())
background.fill([255, 255, 255])

clock = pygame.time.Clock()
class Ball(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect() Ball
self.rect.left, self.rect.top = location
self.speed = speed
def move(self):
if self.rect.left <= screen.get_rect().left or \
self.rect.right >= screen.get_rect().right:
self.speed[0] = - self.speed[0]
newpos = self.rect.move(self.speed) 
self.rect = newpos

my_ball = Ball('beach_ball.png', [10,0], [20, 20])


Ball
pygame.time.set_timer(pygame.USEREVENT, 1000)
direction = 1 :
running = True 1000 = 1
256 18

while running:
for event in pygame.event.get():

if event.type == pygame.QUIT:
running = False
elif event.type == pygame.USEREVENT:
my_ball.rect.centery = my_ball.rect.centery + (30*direction)
if my_ball.rect.top <= 0 or \
my_ball.rect.bottom >= screen.get_rect().bottom:
direction = -direction
clock.tick(30) 

screen.blit(background, (0, 0))
my_ball.move()
screen.blit(my_ball.image, my_ball.rect)
pygame.display.flip()
pygame.quit()

, \ .
, . (
\, .)
18.3, ,
( ), 30
. .


Pong ,
.
, !
.
,
.
:

:
Pong,
-!
257

PyPong
, ,
, , Pong.
. :
, ;
, ;
;
;
.
.


, , Pong
. - .
.
.

, , -
-!
, , -
.
Ball __init__() move():

class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed


def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > width:
self.speed[0] = -self.speed[0]

if self.rect.top <= 0 :
self.speed[1] = -self.speed[1]
258 18

, , ,
:

myBall = MyBallClass('wackyball.bmp', ball_speed, [50, 50])

, ,
. , :

ballGroup = pygame.sprite.Group(myBall)

, Pong , -
. , .
:

class MyPaddleClass(pygame.sprite.Sprite):
def __init__(self, location):
pygame.sprite.Sprite.__init__(self)
image_surface = pygame.surface.Surface([100, 20])
image_surface.fill([0,0,0])
self.image = image_surface.convert()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location

paddle = MyPaddleClass([270, 400])

, , -
. image,
Surface.convert().
.
. , x (
) .
. -
, move() .

, .
MOUSEMOTION, Pygame-
. Pygame- ,
. ,
.
259

elif event.type == pygame.MOUSEMOTION:


paddle.rect.centerx = event.pos[0]

event.pos [x, y] . , -
event.pos[0] x .
, , , -
, .
.
.
y ( , ,
).
:

if pygame.sprite.spritecollide(paddle, ballGroup, False):


myBall.speed[1] = -myBall.speed[1]

. ,
, Pong. 18.4.

18.4. PyPong
import pygame, sys
from pygame.locals import *

class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed

def move(self):
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > screen.get_width():
self.speed[0] = -self.speed[0] (

)
if self.rect.top <= 0 :
self.speed[1] = -self.speed[1]
260 18

class MyPaddleClass(pygame.sprite.Sprite):
def __init__(self, location = [0,0]):
pygame.sprite.Sprite.__init__(self)
image_surface = pygame.surface.Surface([100, 20])

image_surface.fill([0,0,0])
self.image = image_surface.convert()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location

pygame.init()
screen = pygame.display.set_mode([640,480]) -
clock = pygame.time.Clock()
Pygame-
ball_speed = [10, 5] ,
myBall = MyBallClass('wackyball.bmp', ball_speed, [50, 50]) ,
ballGroup = pygame.sprite.Group(myBall)
paddle = MyPaddleClass([270, 400])

running = True
while
while running:
clock.tick(30)
screen.fill([255, 255, 255])
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == pygame.MOUSEMOTION:
paddle.rect.centerx = event.pos[0]
,
if pygame.sprite.spritecollide(paddle, ballGroup, False):

myBall.speed[1] = -myBall.speed[1]
myBall.move()
screen.blit(myBall.image, myBall.rect)
screen.blit(paddle.image, paddle.rect)
pygame.display.flip()
pygame.quit()


:
261

, , -
Pygame. - ,
.
, , .


:
. -

. .
.
Pygame font. -
:
font, Pygame- ;
, font,
;
.
-
(
int string).
-
18.4 (render) -
-
( paddle = MyPaddle-
.
Class([270, 400]))
:

score_font = pygame.font.Font(None, 50) font


score_surf = score_font.render(str(score), 1, (0, 0, 0))
score_pos = [10, 10] -
score_surf

None Pygame-,
. None Pygame-
, .
:

screen.blit(score_surf, score_pos)

.
262 18

, ,

score. ( .)
NameError! , font:

score = 0

...

move(),
. :

if self.rect.top <= 0 :
self.speed[1] = -self.speed[1]
score = score + 1
score_surf = score_font.render(str(score), 1, (0, 0, 0))

Traceback (most recent call last):


File "C:...", line 59, in <module>
myBall.move()
File "C:\...", line 24, in move
score = score + 1
UnboundLocalError: local variable 'score'
referenced before assignment

! .
15? .
score, move() -
Ball. score, .
.
move() :

def move(self):
global score

score_font (,
) score_surf (, ),
move(). :
263

def move(self):
global score, score_font, score_surf

! ,
. .


.
. ,
lives 3:

lives = 3

, -
lives , :

if myBall.rect.top >= screen.get_rect().bottom:


lives = lives - 1
pygame.time.delay(2000)
myBall.rect.topleft = [50, 50]

while. , myBall.rect -
get_rect() screen
:
myBall , rect;
screen , , rect . -
, , get_rect().
, ,
.


-
. .
.
. ,
for :

for i in range (lives):


width = screen.get_rect().width
screen.blit(myBall.image, [width - 40 * i, 20])
264 18

while
( screen.blit(score_text, textpos)).

, ,
. font,
, ( -
) .
, , -
. done,
. ( while):

if myBall.rect.top >= screen.get_rect().bottom:


lives = lives - 1
if lives == 0:
final_text1 = " "
final_text2 = " : " + str(score)
ft1_font = pygame.font.Font(None, 70)
ft1_surf = ft1_font.render(final_text1, 1, (0, 0, 0)) -
ft2_font = pygame.font.Font(None, 50)

ft2_surf = ft2_font.render(final_text2, 1, (0, 0, 0))
screen.blit(ft1_surf, [screen.get_width()/2 - \
ft1_surf.get_width()/2, 100])
screen.blit(ft2_surf, [screen.get_width()/2 - \
ft2_surf.get_width()/2, 200])
pygame.display.flip()
done = True
else: # 2
pygame.time.delay(2000)
myBall.rect.topleft = [(screen.get_rect().width) - 40*lives, 20]

PyPong 18.5.

18.5. PyPong
import pygame, sys

class MyBallClass(pygame.sprite.Sprite):

def __init__(self, image_file, speed, location):


pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed
265

def move(self):


global score, score_surf, score_font
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > screen.get_width():
self.speed[0] = -self.speed[0]

if self.rect.top <= 0 :
self.speed[1] = -self.speed[1]
score = score + 1
score_surf = score_font.render(str(score), 1, (0, 0, 0))

class MyPaddleClass(pygame.sprite.Sprite):
def __init__(self, location = [0,0]):
pygame.sprite.Sprite.__init__(self)
image_surface = pygame.surface.Surface([100, 20])
image_surface.fill([0,0,0])
self.image = image_surface.convert()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location

pygame.init()
screen = pygame.display.set_mode([640,480])
clock = pygame.time.Clock()

myBall = MyBallClass('wackyball.bmp', [10,5], [50, 50])
ballGroup = pygame.sprite.Group(myBall)
paddle = MyPaddleClass([270, 400])
lives = 3
score = 0
score_font = pygame.font.Font(None, 50)
score_surf = score_font.render(str(score), 1, (0, 0, 0))
score_pos = [10, 10]
done = False
( while)
running = True
while running:
clock.tick(30)

screen.fill([255, 255, 255]) ,
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

elif event.type == pygame.MOUSEMOTION:
paddle.rect.centerx = event.pos[0]
if pygame.sprite.spritecollide(paddle, ballGroup, False):
myBall.speed[1] = -myBall.speed[1]
myBall.move()
266 18

if not done:
screen.blit(myBall.image, myBall.rect)
screen.blit(paddle.image, paddle.rect)
screen.blit(score_surf, score_pos)

for i in range (lives):
width = screen.get_width()
screen.blit(myBall.image, [width - 40 * i, 20])
pygame.display.flip()
if myBall.rect.top >= screen.get_rect().bottom:

lives = lives - 1
if lives == 0:
final_text1 = " "


final_text2 = " : " + str(score)


ft1_font = pygame.font.Font(None, 70)
ft1_surf = ft1_font.render(final_text1, 1, (0, 0, 0))
ft2_font = pygame.font.Font(None, 50)
ft2_surf = ft2_font.render(final_text2, 1, (0, 0, 0))
screen.blit(ft1_surf, [screen.get_width()/2 - \
ft1_surf.get_width()/2, 100])
screen.blit(ft2_surf, [screen.get_width()/2 - \
ft2_surf.get_width()/2, 200])
pygame.display.flip()
done = True
else:

pygame.time.delay(2000) 2-
myBall.rect.topleft = [50, 50]
pygame.quit()

18.5
:
, -
,
75 ( ).
-
. ,
-
.

Pygame
PyPong -
.
267


:
;
Pygame;
;
;
;
( );
pygame.font ( Pygame-
).
!


1. ?
2. , ?
3. , Pygame ?
4. MOUSEMOVE ,
?
5. Pygame- (
)?
6. Pygame- ?
7. Pygame-?
8. Pygame-?

1. ,
?
. ,
? , ?
, .
2. (. 18.4 18.5),
. ,
-
, . ( random.randint() random.
random() 15, ,
, .)
19

-
PyPong,
, ,
, . -
.

,
.
, .
, -
(
). ,
.
, PyPong.

mixer
, , ,
- -
, .
Pygame.
Pygame pygame.mixer. -

(mixer), Pygame-.


. -,
, ,
269

. -, .
-, MP3 .
.
, . -
.


, ,
( -, - ), -
, .
. :
Wav- .wav, hello.wav;
MP3- .mp3, mySong.mp3;
WMA- (WMA Windows Media Audio) -
.wma, someSong.wma;
Vorbis-, ogg- .ogg, yourSong.ogg.
wav- mp3-. \sounds,
HelloWorld. , -
Windows c:\Program Files\HelloWorld\examples\sounds.
.
, . Python
, :

sound_file = "my_sound.wav"

, -
:

sound_file = "c:\Program Files\HelloWorld\sounds\my_sound.wav"

,
, -
-
.
-
, , ,


.
.
,

ww w.
. ma nn ing .co m/ bo ok s/h
ell o-
wo rld -se co nd -ed iti on .
270 19

pygame.mixer
pygame.mixer. ,
? .
pygame.mixer .
Pygame- :

pygame.mixer.init()

, Pygame,
:

import pygame
pygame.init()
pygame.mixer.init()

.
. -, . , ,
wav-. pygame.mixer
Sound:

splat = pygame.mixer.Sound("splat.wav")
splat.play()

-, . mp3-, wma-
ogg-. Pygame- mixer
music. :

pygame.mixer.music.load("bg_music.mp3")
pygame.mixer.music.play()

( ) .
- . : !.
while,
Pygame-. -
,
! Pygame- . ,
mixer -
.
,
. ,
271

mixer . ,
19.1.

19.1. Pygame-
import pygame, sys
pygame.init()
pygame.mixer.init() Pygame mixer
Pygame-

screen = pygame.display.set_mode([640,480])
pygame.time.delay(1000) ,
mixer
splat = pygame.mixer.Sound("splat.wav")
splat.play()

running = True
while running:
for event in pygame.event.get():
Pygame-
if event.type == pygame.QUIT:
running = False
pygame.quit()

, , .
mixer.music .
19.1 (19.2).

19.2.
import pygame, sys
pygame.init()
pygame.mixer.init()

screen = pygame.display.set_mode([640,480])
pygame.time.delay(1000)

pygame.mixer.music.load("bg_music.mp3")
pygame.mixer.music.play()

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
272 19

, .
, , . -
. ,
.


. Windows
.
. , -
.
, .

.
?
: .
, .
, .
, .
, - .
- ?
.

, Pygame-
.

,
c .

.
, ! .
pygame.
mixer.music.set_volume(). -
, set_volume()
.
splat,
splat.set_volume().
0 1,
0.5 50%, .
. ,
!. ,
. 30%,
50%. 19.3.
273

19.3.
import pygame, sys
pygame.init()
pygame.mixer.init()

screen = pygame.display.set_mode([640,480])
pygame.time.delay(1000)

pygame.mixer.music.load("bg_music.mp3")
pygame.mixer.music.set_volume(0.30)
pygame.mixer.music.play()
splat = pygame.mixer.Sound("splat.wav")
splat.set_volume(0.50)
splat.play()

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False ! -
pygame.quit() ?


, . .
, , ?
, -
. ,
, -

,
. , ,
.

, .
Pygame- , -
.
.
, -
? , -
(, ). , ?
Pygame- mixer.music: ,
. .
274 19

get_busy(). -
, True, False.
,
, (19.4).

19.4.
import pygame, sys
pygame.init()
pygame.mixer.init()

screen = pygame.display.set_mode([640,480])
pygame.time.delay(1000)

pygame.mixer.music.load("bg_music.mp3")
pygame.mixer.music.set_volume(0.3)
pygame.mixer.music.play()
splat = pygame.mixer.Sound("splat.wav")
splat.set_volume(0.5)
running = True
while running:
for event in pygame.event.get(): ,
if event.type == pygame.QUIT:
running = False

if not pygame.mixer.music.get_busy():
splat.play()
pygame.time.delay(1000)
running = False
pygame.quit()

, ,
.


, , ,
. music .
:

pygame.mixer.music.play(3)

.
275

, -

1: -
Pygame-
,
pyga
pygame.mixer.music.play(-1) me.mixer.
music.play(3)


-
(
, Pygame- -
).
-
. ( 1,
-
.)
.

PyPong
, , ,
PyPong. .
, -
.
18.5?

if pygame.sprite.spritecollide(paddle, ballGroup, False):


myBall.speed[1] = -myBall.speed[1]

. ,
pygame.mixer.init()
:

hit = pygame.mixer.Sound("hit_paddle.wav")

hit.set_volume(0.4)

if pygame.sprite.spritecollide(paddle, ballGroup, False):


myBall.speed[1] = -myBall.speed[1]
hit.play()

PyPong 18.5. ,
hit_paddle.wav .
.
276 19


, hit,
. :
;
, ;
;
;
.
. -
pygame.mixer.
init(), while:

hit_wall = pygame.mixer.Sound("hit_wall.wav")
hit_wall.set_volume(0.4)
get_point = pygame.mixer.Sound("get_point.wav")
get_point.set_volume(0.2)
splat = pygame.mixer.Sound("splat.wav")
splat.set_volume(0.6)
new_life = pygame.mixer.Sound("new_life.wav")
new_life.set_volume(0.5)
bye = pygame.mixer.Sound("game_over.wav")
bye.set_volume(0.6)

. -
.
. \examples\sounds .
277

play(). hit_wall
. -
move() , x- (
). 18.5 14:

if self.rect.left < 0 or self.rect.right > screen.get_width():

, .
:

if self.rect.left < 0 or self.rect.right > screen.get_width():


self.speed[0] = -self.speed[0]
hit_wall.play()

get_point. move()
. -
. .
:

if self.rect.top <= 0 :
self.speed[1] = -self.speed[1]
points = points + 1
score_text = font.render(str(points), 1, (0, 0, 0))
get_point.play()

, .
,
.
while, 63 18.5
(if myBall.rect.top >= screen.get_rect().bottom:).
:

if myBall.rect.top >= screen.get_rect().bottom:



splat.play()
#
lives = lives - 1

. -
18.5, else.
:
278 19

else:
pygame.time.delay(1000)
new_life.play()
myBall.rect.topleft = [50, 50]
screen.blit(myBall.image, myBall.rect)
pygame.display.flip()
pygame.time.delay(1000)

( ) -
(1000), ,
. , .
,
. 65 18.5 (if lives == 0:).
bye:

if lives == 0:
bye.play()

, .


! . bye
!
splat while, -
, Pygame-.
, -
.

done, . -
:

if myBall.rect.top >= screen.get_rect().bottom:


if not done:
splat.play()
lives = lives - 1
if lives == 0:
if not done:
bye.play()

.
279

-

-.

. done
, -

. .

?
, -
! , ,
y .
, ,
- ! ,
, x .
move(), , while.
? .
,
[0,0].
, , -
, hit_wall.
done hit_wall,
.
, . .
.
PyPong
, .
, . -
, 1:

pygame.mixer.music.load("bg_music.mp3")
pygame.mixer.music.set_volume(0.3)
pygame.mixer.music.play(-1)

while.
. ,
. fadeout() pygame.mixer.
music. . ,
:
280 19

pygame.mixer.music.fadeout(2000)

2000 2 . ,
done = True. (, .)
, .
, !
, 19.5. ,
wackyball.bmp, , .

19.5. PyPong
import pygame, sys

class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location = [0,0]):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed

def move(self):
global points, score_text
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > screen.get_width():
self.speed[0] = -self.speed[0]
if self.rect.top < screen.get_height():
hit_wall.play()

if self.rect.top <= 0 :
self.speed[1] = -self.speed[1]
points = points + 1
score_text = font.render(str(points), 1, (0, 0, 0))
get_point.play()
(
class MyPaddleClass(pygame.sprite.Sprite): )
def __init__(self, location = [0,0]):
pygame.sprite.Sprite.__init__(self)
image_surface = pygame.surface.Surface([100, 20])
image_surface.fill([0,0,0])
self.image = image_surface.convert()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
pygame.init()
pygame.mixer.init() Pygame-
281

pygame.mixer.music.load("bg_music.mp3")
pygame.mixer.music.set_volume(0.3)
pygame.mixer.music.play(-1)
hit = pygame.mixer.Sound("hit_paddle.wav")
hit.set_volume(0.4)
new_life = pygame.mixer.Sound("new_life.wav")

new_life.set_volume(0.5)
splat = pygame.mixer.Sound("splat.wav")
splat.set_volume(0.6)
hit_wall = pygame.mixer.Sound("hit_wall.wav")
hit_wall.set_volume(0.4)
,

get_point = pygame.mixer.Sound("get_point.wav")
get_point.set_volume(0.2)
bye = pygame.mixer.Sound("game_over.wav")
bye.set_volume(0.6)
screen = pygame.display.set_mode([640,480])
clock = pygame.time.Clock()
myBall = MyBallClass('wackyball.bmp', [12,6], [50, 50])
ballGroup = pygame.sprite.Group(myBall)
paddle = MyPaddleClass([270, 400])
lives = 3
points = 0

font = pygame.font.Font(None, 50)


score_text = font.render(str(points), 1, (0, 0, 0))
textpos = [10, 10]
done = False

running = True
while running:
clock.tick(30)
screen.fill([255, 255, 255])
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEMOTION:
paddle.rect.centerx = event.pos[0]

if pygame.sprite.spritecollide(paddle, ballGroup, False):


hit.play()
myBall.speed[1] = -myBall.speed[1]
myBall.move()

if not done:
screen.blit(myBall.image, myBall.rect)
282 19

screen.blit(paddle.image, paddle.rect)
screen.blit(score_text, textpos)
for i in range (lives):
width = screen.get_width()
screen.blit(myBall.image, [width - 40 * i, 20])
pygame.display.flip()

if myBall.rect.top >= screen.get_rect().bottom:


if not done:
splat.play() ,

lives = lives - 1
if lives <= 0:
if not done:
pygame.time.delay(1000)

bye.play()
final_text1 = " "
final_text2 = " : " + str(points)
ft1_font = pygame.font.Font(None, 70)
ft1_surf = font.render(final_text1, 1, (0, 0, 0))
ft2_font = pygame.font.Font(None, 50)

ft2_surf = font.render(final_text2, 1, (0, 0, 0))


screen.blit(ft1_surf, [screen.get_width()/2 - \
ft1_surf.get_width()/2, 100])
screen.blit(ft2_surf, [screen.get_width()/2 - \
ft2_surf.get_width()/2, 200])
pygame.display.flip()

done = True
pygame.mixer.music.fadeout(2000)
else:
pygame.time.delay(1000)
new_life.play()
myBall.rect.topleft = [50, 50]
screen.blit(myBall.image, myBall.rect)
pygame.display.flip()
pygame.time.delay(1000)
pygame.quit()

! ( 100 , .)
, .
, -
. , ,
.
\examples .
283


: , , -
(GUI).

:
;
( wav-);
( mp3-);
;
;
;
.

1. , .
2. Pygame ?
3. Pygame-?
4. ?
5. , ?

1.
, Pygame-,
. -
\examples\sounds ( ):
Ahoy.wav;
TooLow.wav;
TooHigh.wav;
WhatsYerGuess.wav;
AvastGotIt.wav;
NoMore.wav.
? , ,
Sound Recorder, Windows.
audacity.sourceforge.net/ Audacity
( ).
20

GUI-
6 -
(GUI), EasyGui.
. GUI-
. -
PyQt,
.
PyQt GUI-.
.

PyQt
, PyQt. -
, , PyQt .
www.riverbankcomputing.com/software/pyqt/download.
-
Python ( ,
2.7.3). PyQt4.1.
GUI .
( UI), , -
.
, , , -
.. , ,
PyQt
- , ,
5,

4.
- .

,
, Qt UI
PyQt
4. Qt-. ,
.
GUI- 285

Qt-
PyQt -
, Qt-.
(
Windows) .
,
New Form ( ):
(form)
GUI-. GUI-
, Main Window (
) Create ().
Qt-
.

,
GUI. .
286 20

-
.
,
GUI -
(widgets). ,
. ,
-
.
. /, -
.
. -
Main Window untitled ( ),
.
UI-. Mac
QtDesignerPreferences (Qt-)
Multiple Top-Level Windows (
) Docked Window ( ).
.


GUI- .
Qt- Buttons (),
Push Button ( ).
-
-
-
.
PushButton.

. -
( -
),
. ,
PushButton.
-
, , x y,
.
GUI- 287


-
: .


. ,
,
( ),
.
geometry,
X, Y, Width Height.
.
. -
. text
Im a Button! ( !). ,

, .
Im a Button!.
( objectName)
PushButton. -
,
- .

GUI-
. PyQt GUI-
.ui. ,
. -
Qt-, ,
PyQt-.
UI FileSave As ( )
. MyFirstGui. , -
.ui.
MyFirstGui.ui.
, . ,
Python-, Save ().
, IDLE.
, :
288 20

<?xml version="1.0" encoding="UTF-8"?>


<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>576</width>
<height>425</height> ()
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>60</x>
<y>70</y>
<width>121</width>
<height>41</height>
</rect>
</property>
<property name="toolTip">
<string/>
</property>
<property name="text">
<string>I'm a Button!</string>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>576</width>
<height>21</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
GUI- 289

<resources/>
<connections/>
</ui>

, , -
, , , .
, , .

GUI-
GUI- . , ?
. , -
.
,
.
-
, .
,
. ,
-
. PyQt-
, 20.1.

20.1.
PyQt-
import sys
from PyQt4 import QtCore, QtGui, uic PyQt



form_class = uic.loadUiType("MyFirstGui.ui")[0]

UI-
class MyWindowClass(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
PyQt-,
app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass()
myWindow.show()

app.exec_() GUI-

, [0] , ,
.
290 20

, Python, PyQt-
UI- . , -
,
[0],
uic.lo class.
adUiType()

- PyQt- ,
: form_class QMainWindow. 20.1
base_class.


MyWindowClass ( 6),
form_class, -. , -


item[0]. . -
.
myWindow = MyWindowClass()
. myWindow MyWindowClass.
IDLE- SPE- MyFirstGui.py:
MyFirstGui.py;
UI- MyFirstGui.ui.
,
UI-.
IDLE. ,
. . ,
. ,
.
- .
. 20.2 20.1
10 17.

20.2. 20.1
import sys
from PyQt4 import QtCore, QtGui, uic

form_class = uic.loadUiType("MyFirstGui.ui")[0]

class MyWindowClass(QtGui.QMainWindow, form_class):


def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.button_clicked)

def button_clicked(self):

x = self.pushButton.x()
GUI- 291

y = self.pushButton.y()
x += 50
y += 50
self.pushButton.move(x, y) ,


app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass()
myWindow.show()
app.exec_()

, def
class , . ,
.
.
, .
.


Pygame-, , -
,
. PyQt.
MyWindowClass . -
, MyWindowClass
.

e count, and reset the li


nt the pag ne count n=1 ; self.count=#!
eme and res der_writte /bin/e
et a self.hea nv py
tho
print name'sys.exit(0)class # Incr

n # !Bin/en Paginate a text file, adding a hea


d1
;#
!/bin/env python


.
,
file

# Pa

. PyQt
ginate a text file,

pr
e: py

-
o if #
int >>
sys.argv)!=2: print 'Usag

>Hell

. pri
nt >>>
if #

Hello

pr
o if #
int >>

.
>Hell
#!/bin/env pyth
on #


len(

Pag

nat
.
e if

If no argu ag ea
ments w e ss ng #
text
ere given, print a helpful m e, stri file, a
dding a hea
der and footer import sys, tim
292 20

,
. 20.2 10:

self.pushButton.clicked.connect(self.button_clicked)

(self.pushButton.clicked) -
(self.button_clicked). button_clicked -
12. , (clicked),
(pressed) (released).

self
button_clicked() self. -
14 , self -
.
, , .
self . , -
, , ;
, .


, - ? PyQt
. , self ,
pushButton, , self.
pushButton.
20.2
. geometry,
x, y, width height. .
-, setGeometry(), .
-, move(),
width height ( -
20.2). x , -
y . ,
[0, 0] ( Pygame).
, ,
. (
) . ,
( ,
).
GUI- 293

, Pygame-,
. .
PyQt.

GUI-
GUI-
PyQt, .
, 22 ,
PyQt.
-, PyQt- -
. -, 22 PyQt GUI-
. PyQt
.

TempGUI
3 -
. 5
, ,
. 6 EasyGui -
.
PyQt -
.

TempGUI
GUI- , :
( );
, ;
, , .


.
( -
), -
.
GUI
:
294 20

, , Qt-
. -
. -
, , ,
.

, . .

GUI-
PyQt-.
UI- (MyFirstGui), New Form
( ). , Main Window ( )
Create ().
:
Line Edit ( ), Spin
Box ( ). Label
() Push Button ( ).
,
. GUI.
1. Push Button ,
. :
, -
geometry (
MyFirstGui);
objectName btnFtoC;
text <<< Fahrenheit to Celsius;
font size 12. -
, font,
Font (), , , ,
.
2. Push Button, -
, :
objectName btnCtoF;
text Celsius to Fahrenheit >>>;
12.
GUI- 295

3. Line Edit , -
objectName editCel.
4. Spin Box ,
objectName spinFahr.
5. Label Line Edit:
text Celsius;
10.
6. Label, Spin Box:
text Fahrenheit;
10.
, GUI (, , -
) , .
tempconv.ui, Qt- FileSave As ( ).
, Python-.
IDLE PyQt- ( -
):

import sys
from PyQt4 import QtCore, QtGui, uic

form_class = uic.loadUiType("tempconv.ui")[0]

class MyWindowClass(QtGui.QMainWindow, form_class):


def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)

app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass()
myWindow.show()
app.exec_()


,
. , :
fahr = cel 9.0 / 5 + 32.
Line Edit, -
editCel, Spin Box
296 20

spinFahr.
Celsius to Fahrenheit >>>, -
.
clicked :

self.btn_CtoF.clicked.connect(self.btn_CtoF_clicked)

__init__() MyWindow,
.
. Celsius (-
), Line Edit editCel,
self.editCel.text(). ,
:

cel = float(self.editCel.text())

fahr = cel * 9.0 / 5 + 32

Fahrenheit ( ), -
Spin Box spinFahr. :
.
int. -
value, :

self.spinFahr.setValue(int(fahr))

0.5, int(), -
, ,
. , :

def btn_CtoF_clicked(self):
cel = float(self.editCel.text())
fahr = cel * 9.0 / 5 + 32
self.spinFahr.setValue(int(fahr + 0.5))
app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass()
myWindow.show()
Fahrenheit
app.exec_()
GUI- 297


( )
. :
cel = (fahr 32) * 5.0 / 9.
<<< Fahrenheit to Celsius. -
__init__() .

self.btn_FtoC.clicked.connect(self.btn_FtoC_clicked)

fahr = self.spinFahr.value()

,
. :

cel = (fahr - 32) * 5.0 / 9

Celsius:

self.editCel.setText(str(cel))

, 20.3.

20.3.
import sys
from PyQt4 import QtCore, QtGui, uic
UI-

form_class = uic.loadUiType("tempconv.ui")[0]
class MyWindowClass(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)

self.setupUi(self)
self.btn_CtoF.clicked.connect(self.btn_CtoF_clicked)
self.btn_FtoC.clicked.connect(self.btn_FtoC_clicked)

def btn_CtoF_clicked(self):
cel = float(self.editCel.text()) Celsius to
fahr = cel * 9 / 5.0 + 32 Fahrenheit
self.spinFahr.setValue(int(fahr + 0.5))

def btn_FtoC_clicked(self):
fahr = self.spinFahr.value() Fahrenheit to Celsius
298 20

cel = (fahr - 32) * 5 / 9.0


self.editCel.setText(str(cel)) Fahrenheit to Celsius

app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass(None)
myWindow.show()
app.exec_()

TempGui.py. , -
.


, ,
; -
, .
, .
, 21 -
, .
btn_FtoC_clicked :

cel_text = '%.2f' % cel


self.editCel.setText(cel_text)

,

!

, .
Celsius 50,
58 -
-
. ?
- ?

0!

!


GUI- 299


,
. .
, -
.
btn_CtoF_clicked 20.3 :

print 'cel = ', cel, ' fahr = ', fahr

Celsius to Fahrenheit >>> IDLE-


cel fahr.
cel , . :

>>> ============================ RESTART ============================


>>>
cel = 50.0 fahr = 122.0
cel = 0.0 fahr = 32.0
cel = -10.0 fahr = 14.0
cel = -50.0 fahr = -58.0

, fahr .
Fahrenheit 0 ( 99, !)?
Qt- spinFahr,
.
. minimum maximum ( )?
? , ?

?
GUI- , -
.
. ,
.
?
-
.
. , -
, , ,
.
300 20

, -
. FileExit
(), .

, ,

...
.




PyQt -
. , -
, Type Here ( ).
. -
File (),
. Type Here, File
Enter. File ,
.


File Exit (). Type Here File Exit
Enter.
( ,
). Type
Here File Convert (),
C to F F to C.
.
GUI- 301

,
,
:

File Convert Exit, C to F F to C.


PyQt QAction. ,
, (actions).

tempconv_menu.ui. M
ac
na
, ( ), - tiveMenuBar
menubar
( -
.

C to F F to C ).

,

Python
. , - -
, Py
. Qt--

Fi le .
.
() , . ,
, action_CtoF.
btn_CtoF_clicked. -
:

self.action_CtoF.triggered.connect(self.btn_CtoF_clicked)

F to C.
Exit -
. menuExit_selected,
:

self.actionExit.triggered.connect(self.menuExit_selected)

Exit
, :

def menuExit_selected(self):
self.close(
302 20

UI- ( ), -
tempconv_menu.ui.
20.4.

20.4.

import sys UI-
from PyQt4 import QtCore, QtGui, uic

form_class = uic.loadUiType("tempconv_menu.ui")[0]

class MyWindowClass(QtGui.QMainWindow, form_class):


def __init__(self, parent=None): Convert
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.btn_CtoF.clicked.connect(self.btn_CtoF_clicked)
self.btn_FtoC.clicked.connect(self.btn_FtoC_clicked)
self.action_CtoF.triggered.connect(self.btn_CtoF_clicked)
self.action_FtoC.triggered.connect(self.btn_FtoC_clicked)
self.actionExit.triggered.connect(self.menuExit_selected)

def btn_CtoF_clicked(self):
cel = float(self.editCel.text())
fahr = cel * 9 / 5.0 + 32 Exit

self.spinFahr.setValue(int(fahr + 0.5))

def btn_FtoC_clicked(self):
fahr = self.spinFahr.value()
cel = (fahr - 32) * 5 / 9.0
self.editCel.setText(str(cel))

def menuExit_selected(self):
self.close() Exit

app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass(None)
myWindow.show()
app.exec_()
GUI- 303


, , -
, .
,
. ,
.
(
) -
.
Windows Linux
Alt.

(
). , -
. ,
File Alt+F.
, Alt,
F.
File
. IDLE-.
, Alt+F+N ( Alt, -
F, N).
GUI-, -
. , ,
&. ( File) Title,
( Exit) Text. File
F; Exit X. File &File, Exit E&xit.

, Convert. -
C Convert, C
F . -
, &Convert, &C to F &F to C,
304 20

Alt+C+C ( ) Alt+C+F
( ).
.
PyQt
. UI-.
, tempconv_menu_hotkeys.ui. -
20.4, UI-:

form_class = uic.loadUiType("tempconv_menu_hotkeys.ui")[0]

Mac,
Option,
Alt,

- . Mac
( -
. ), -

MacOS ,
Mac OS X?
.
MacOS -
.
,
. ,
Windows, .
GUI-
. 22 PyQt .


:
PyQt;
Qt-;
, ,
GUI-;
,
;
.
GUI- 305


1. , , ,
, GUI-.
2. , Alt -
?
3. Qt-?
4. , GUI- -
PyQt.
5. ( ) - ,
_____________________________.
6. ?
7. PyQt _______________________________.

1. 1 , 6
GUI-. GUI-
PyQt.
2. , 0? (
20.2.) ,
. ,
, -
. (
, !)
21


-, 1, print.
Python, . , ( 5),
print Python
. ( Python2. Python3
.) raw_input(), ,
.
(print formatting)
. -
:
( );
( );
;
,
, .
Python .
:
;
;
;
;
;
( ).
( GUI-) ,
GUI- . Python
, -
, 99% .
307


print. , -
? :

print ""
print ""

>>> =================== RESTART ===================


>>>

?
:

Python
, print.
,
. Python .
Enter .

tn i r p
> tn i r
H> > >

If no arguments were g helpful message if len


ello i
#f
p #

ring # iven, print a


eH>>

llo if
ooter import
and f sys, t me, st
(sys
tnirp

er .arg
H>>>

ello i
#f

v)!
=2

i
d
hea

rint 'Usage: pyp


:p
ile, adding a

rin
t
, 5
fil
ena

, CR LF (
me'sys
ate a text f

)? ,
.exit(0)class

in ,
Pag
#
.
bin/e python


#I

ncr
em
nv

ent

(newline). Windows CR + LF, Linux


t he pa
#!/

LF, Mac OS X CR. ,


ge

.
count, an
x t f ile ,

,
a te

dr

.
set
e
ate

the
en=

in ine cou ritt 1 ; f.co l


t xt Pag nt self.header_w
e

un
t=1head
er_written=1 # P ag i nate a /bin/env python #
; #!/bin/env python
308 21

print
print
. ? (
5):

print '',
print ''
>>> =================== RESTART ===================
>>>

( : Python 3 .) ,
. ,
Python , .
-
:

print '' + ''


>>> =================== RESTART ===================
>>>

, , , ,
.


, ? ,
.
print:

print ""
print
print ""

, :

>>> =================== RESTART ===================


>>>


309


. Python -
, .
(\). \n.
:

>>> print " "



>>> print " \n"

\n ,
, .

(
, ).
.
. ,
, , .
.
.
. \t.
:

>>> print 'ABC\tXYZ'


ABC XYZ

, XYZ ABC .
XYZ . .
, -
>>> print 'ABC\tXYZ'
. ABC XYZ

>>> print 'ABCDE\tXYZ'


ABCDE XYZ
print, , >>> print 'ABCDEF\tXYZ'
. ABCDEF XYZ

>>> print 'ABCDEFG\tXYZ'


( ABCDEFG XYZ

) >>> print 'ABCDEFGHI\tXYZ'


ABCDEFGHI XYZ
310 21

. , ABC XYZ
. \t Python,
XYZ , -
. ABC ,
Python XYZ .
, .
-
. IDLE
21.1. . squbes.py,
squares and cubes ( ).

21.1.
print "Number \tSquare \tCube"
for i in range (1, 11):
print i, '\t', i**2, '\t', i**3

>>> ====================== RESTART ======================


>>>
Number Square Cube
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000


(\) . ,
?
Python? , . -
:

>>> print '\\'


\
311


\
Python, , - -
,

\. (escaping) -
. ,
, -


, -
: .

name = ' '


print ' ', name, ' .'

, :

, -
, .
(format strings), (%). ,
, print,
.
:

name = ' '


print ' %s ' % name

% . ,
, , Python,
.
%s .
, %i; %f.
:

age = 13
print ' %i .' % age

13 .
312 21

average = 75.6
print ' %f .' % average

, :

75.600000 .

%s, %f %i
.
,
. ,
. (, 3?)
.


. :
;
;
;
+ .
, !
, :

.: 23.45672132, 15.4985756
: 23, : 15

? -
.
. ,
. :

>>> dec_number = 12.3456


>>> print ' %.2f .' % dec_number
12.35

print .
%f, %.2f. Python
313

. ( ,
Python , .)
%, , Python,
, .
. .
,
%

, ! % -
, - !

, 3,
.
Python
.

: %d %i
%d %i ( , -
,
.):

>>> number = 12.67


>>> print '%i' % number
12

, . -
. 13, 12.
,
.
.

.
, , .
.
Python .
int(), 4,
. .
12,67 , Python
12. number . -
:
314 21

>>> print number


12.67

number . -
.

: %f %f
f
(%F) (%f) :

>>> number = 12.3456


>>> print '%f' % number
12.345600

%f . f .n,
n , n :

>>> print '%.2F' % number


12.35

, 12.3456 : 12.35.
,
Python :

>>> print '%.8f' % number


12.34560000

,
, .
%f -.
, , ,
% + ( ,
):

>>> print '%+f' % number


+12.345600

,
+, % + :
315

>>> number2 = -98.76


>>> print '% .2f' % number2
-98.76
>>> print '% .2f' % number
12.35

12 .
12 98 , ,
, .

: %e %E
3 , , -
. :

>>> number = 12.3456


>>> print '%e' % number
1.234560e+01

%e -
. .
, .n
%, :

>>> number = 12.3456


>>> print '%.3e' % number
1.235e+01
>>> print '%.8e' % number
1.23456000e+01

%.3e , %.8e,
, .
e , ,
:

>>> print '%E' % number


1.234560E+01

: %g %g
, Python ,
, ,
316 21

%g. , E ,
:

>>> number1 = 12.3


>>> number2 = 456712345.6
>>> print '%g' % number1
12.3
>>> print '%g' % number2
4.56712e+08

, , Python -
?


, ,
(%)?
Python , %
, . :

>>> print ' 90% !'


90% !

% , , ,
Python , % .
,
, . -
. ,
, :

>>> math = 75.4


>>> print ' %.1f%% ' % math
75.4%

% . %% -
Python, %. %,
, .


, print -
? :
317

>>> math = 75.4


>>> science = 82.1
>>> print ' %.1f %.1f ' % (math,
science)

print ,
. ,

. Python
, . -
; . (
.)
( ) ( ),
.


,
. :

>>> my_string = '%.2f' % 12.3456


>>> print my_string
12.35
>>> print '', my_string
12.35

,
my_string.
.
GUI-
, .
, , :
, , .


Python.
Python2.6
.
Python2.7, .
, , , .
318 21

,
.

format()
Python- ( 2.6 ) format().
%, -
. f, g, e ,
- . .
:

print ' %.1f , %.1f ' %


(math, science)

print ' {0:.1f} , {1:.1f} '.


format(math, science)

%,
. 0 1 Python,
.
, Python ,
( math) 0, ( science) 1.
.1f, .
, . -
, %:

distance = 149597870700
myString = ' {0:.4e} '.format(distance)

% ,
:

>>> print ' {0:.1f}% '.format(math)


87%

, Python,
format(), Python3.
.
%.
319


( 2) , -
+:

>>> print '' + ''


.
Python ( ,
) , ,
. .
format(), .


.
, - . , ,
, . :

>>> name_string = 'Sam,Brad,Alex,Cameron,Toby,Gwen,Jenn,Connor'

, , -
. , ,
. Python split(). :

>>> names = name_string.split(',')

, ,
, .
, :

>>> print names


['Sam','Brad','Alex','Cameron','Toby','Gwen','Jenn','Connor']
>>> for name in names:
print name
Sam
Brad
Alex
Cameron
Toby
Gwen
Jenn
Connor
320 21

,
!

. ,
'Toby,', :

>>> parts = name_string.split('Toby,')


>>> print parts
['Sam,Brad,Alex,Cameron', 'Gwen,Jenn,Connor']
>>> for part in parts:
print part
Sam,Brad,Alex,Cameron
Gwen,Jenn,Connor

: ,
'Toby,', , . , 'Toby,'
. , .
. Python
:

>>> names = name_string.split()

, .


, . -
?
2 , +.
.
join().
, .
split(). -
:

>>> word_list = ['', '', '']


>>> long_string = ' '.join(word_list)
>>> long_string
' '
321

, . -
join().
, ''.join().
, ,
join() Python. -:

>>> long_string = ' '.join(word_list)


>>> long_string
' '

, , join(), ,
.


, ,
GUI-. . -
, :


:
2
75
1 . .
500
:
180

30

, ,
. ? Python
.
startswith() ,
. :

>>> name = "Frankenstein"


>>> name.startswith('F')
True
>>> name.startswith("Frank")
True
>>> name.startswith("Flop")
False
322 21

Frankenstein F,
True. Frankenstein Frank,
True. Flop
, False.
startswith()
True False, -
?
if:

>>> if name.startswith("Frank"):
print " ?"

endswith(), -
,
:

>>> name = "Frankenstein"


>>> name.endswith('n')
True
>>> name.endswith('stein')
True
>>> name.endswith('stone')
False

. -
:

i = 0
while not lines[i].startswith(""):
i = i + 1

, . ,
lines[i] i .
lines[0] ( ), lines[1] ( ) .. -
while i , ,
, , .


startswith() endswith() .
, ?
, :
323

657 Maple Lane


47 Birch Street
95 Maple Drive

Maple. -
Maple, .
?
.
(12), , :

if someItem in my_list:
print "!"

in.
. , , ,
, , :

>>> addr1 = '657 Maple Lane'


>>> if 'Maple' in addr1:
print " 'Maple'."

in , -
.
.
index(). ,
Maple
, index() , 657 Maple Lane,
- .
. :

>>> addr1 = '657 Maple Lane'


>>> if 'Maple' in addr1:
position = addr1.index('Maple')
print " 'Maple' ", position

, :

'Maple' 4

Maple 4 "657 Maple Lane". ,


( ) , M
4.
324 21

6 5 7 M a p l e L a n e
0 1 2 3 4 5 6 7 8 9 10 11 12 13

, index()
"Maple" . ,
index() . -
in . 12.


, (strip off ), . -
, . Python
strip(). ,
:

>>> name = 'Warren Sande'


>>> short_name = name.strip('de')
>>> short_name
'Warren San'

de. ,
:

>>> name = 'Bart Simpson'


>>> short_name = name.strip('de')
>>> short_name
'Bart Simpson'

strip(), .
. , -
, .
, :

>>> name = "Warren Sande "


>>>> short_name = name.strip()
>>> short_name
'Warren Sande' ?

.
strip(), .
, .
325


. -
, . , Hello hello,
, . .
lower(). :

>>> string1 = "Hello"


>>> string2 = string1.lower()
>>> print string2
hello

upper():

>>> string3 = string1.upper()


>>> print string3
HELLO

( )
, , .

:
(
);
;
;
: %
format();
split() join();
startswith(), endswith() index(),
in;
, , strip();
upper() lower().

1. print:
print " "
print " ?"

?
326 21

2. ?
3. ?
4.
?

1. , ,
.
:
>>> ======================== RESTART ========================
>>>
?
? 12
?
12

2. , , 8
(.8.5)?
.
3. , 8 ( 1/8, 2/8,
3/8, 8/8)
.
22


, -
?
? .
, : ,
.
.
( ). -
. ,
, - . ,
.
, -
. - , , ,
. ,
.
. -
. ,
.
,
, . ,
. -
.
, , .


,
, , .
, ,
. ,
328 22

. ,
, -, DVD-,
- .
. , , , -
, ..
, .
. ( Windows,
MacOSX Linux) , .
:
;
, (, , );
( );
( ).

( Windows) -
.
. , , . -
(extension).
:
my_letter.txt .txt, text
;
my_song.mp3 .mp3, MP3, -
;
my_program.exe .exe,
executable (). ;
my_cool_game.py .py, Python-
.

Mac OS X .app,
application ().
, .

.
( ) , , my_notes.
mp3. . ,
329

. ,
, , , .
,
.


-
,
. -
,
.
.

,
, .
. ,
, !
- , -
. , . -
,
.
.
Windows -
, C E -
. MacOSX Linux -
( hda FLASH DRIVE).
,
Music (), Pictures (), Programs ().
Windows Explorer :
, , ,
, ..
:
330 22

Music. New
Music ( ) Old Music ( ), -
Kind of old music ( ) Really
old music ( ).


, , .
,
.

Windows Explorer (
) . ,
C: E:. .
, ..
. -
.
. ,
-. Windows Explorer
:

E:\Music\Old Music\Really old music\my_song.mp3

(path). .
.
1. E:.
2. Music.
3. Music Old Music.
4. Old Music Really old music.
5. Really old music my_song.mp3.
. -
. :

image_file = "c:/program files/HelloWorld/examples/beachball.png"

, .
, ( ,
C:). .
331

?
(\ /).
Windows (/),
(\), Python c:\test_results.
txt, - \t. , 21 -
, ? \t
. \ -
. Python ( Windows) \t ,
. /.
:

image_file "c:\\program files\\HelloWorld\\images\\beachball.png"

, \ -
. .
(/).

. -
, .

?
(
Windows) -
(working directory), -
(current working
directory). ,
.
, (C:) -
Program Files Hello
World. ,
, C:/Program Files/Hello World.
beachball.png Examples.
/Examples/beachball.png. -
, .
, 19 splat.wav
? . ,
332 22


.
Windows Explorer
:
, Python- (-
.py)
( .wav).
Python-
,
.py.
e:/programs,
e:/programs. , -
. ,
. :

my_sound = pygame.mixer.Sound("splat.wav")

, (
e:/programs/splat.wav). ,
.

!
, , .. ,
. -
, , ,
, ,
-, , .

, .


, , .
( -
, ), .
,
.
, .
333

, Python . (-
, , Python ?)
open() :

my_file = open('my_filename.txt','r')

, .
'r' , .
.
.
, .
, Windows
( Linux, MacOSX).
.
-. , , ,
. , , ,
fweasley. , -
( ), ,
( ).
.
. , ,
notes.txt, :

notes = open('notes.txt', 'r')

some_crazy_stuff = open("notes.txt", 'r')



, .
.

, open() .
Python-. ,
'r':

my_file = open('notes.txt', 'r')


334 22

,
. ( , , , ?)
Python
. readlines():

lines = my_file.readlines()

, .
, notes.txt :

Wash the car ( )


Make my bed ( )
Collect allowance ( )

, , -
. notes.txt Python-.
.
Python-
22.1.

22.1.
my_file = open('notes.txt', 'r')
lines = my_file.readlines()
print lines

(
):

>>>======================= RESTART =========================


>>>
['Wash the car\n', 'Make my bed\n', 'Collect allowance']

lines.
. \n
. , .
Enter, .
Enter, \n .
22.1 . ,
:

my_file.close()
335

, ,
, , ,

.
, . ?

,
, .
Python-
. , -
, , ..
. -
, int float (
), GUI
.


readlines() , .
readline():

first_line = my_file.readline()

. -
readline() Python
. ,
. -
22.2.

22.2. readline()
my_file = open('notes.txt', 'r')
first_line = my_file.readline()
second_line = my_file.readline()
print " = ", first_line
print " = ", second_line
my_file.close()

>>>================== RESTART ====================


>>>
=
=
336 22

readline() ,
. readline() .


readline()
, seek():

first_line = my_file.readline()
second_line = my_file.readline()
my_file.seek(0)
first_line_again = my_file.readline()

seek() Python -
. . 0
.



. , ,
. -
, , , .
, .
, ,
, .
. ,
, - , , -
.
readline() readlines() .
.wav,
. , - :

>>> f = open('splat.wav', 'r')


>>> print f.readline()
RIFF WAVEfmt "V "V datap

zvvy{|
}trv~ut|yrqrtxtv|mlfWR]jnmpx r"}`ORj{hZZgwy{
mWLISjzrvytv~}yrifjt}mSCFZlrty
|pd\UME@;99:>EJMW]YTZfu~{|{yxzzuiZNGHLSbs~
wrnf\TPQU]`jvos}
337

wav- , , -
. , wav- .
. readline() readlines() .
, ,
Pygame- , 19:

pygame.mixer.music.load('bg_music.mp3')

( ) -
Pygame-.
.
, , ,
, b:

my_music_file = open('bg_music.mp3', 'rb')

'rb' , .
, , ,
. ,
. .


,
. , !
, -
, , ,
.
. , ,
Python- .
, .
.
-
.
, .
open(), .
'r':
my_file = open('new_notes.txt', 'r')
338 22

'w':
my_file = open('new_notes.txt', 'w')

'a':
my_file = open('notes.txt', 'a')


!
, , . -
.

,
.
.
!

'a' , -
. .

!

. !

'w', ,
!
.
,
.
,
,
.
.
339


- notes.txt. "
". readlines(), -
, \n. ,
(22.3).
write().

22.3.
todo_list = open('notes.txt', 'a')
todo_list.write('\n ')
todo_list.close()

, ,
. close() -
. , ,
.
22.3 notes.txt (
) , .
.


. ,
. 22.4
.

22.4.
new_file = open("my_new_notes.txt", 'w')
new_file.write(" \n")
new_file.write(" \n")
new_file.write(" ")
new_file.close()

, ? , -
22.4. my_new_notes.txt.
, :




340 22

.
,
, , . ,
.
( ). ,
,
, .
, - -
. notes.txt? 22.3
:

.
22.5.

22.5.
the_file = open('notes.txt', 'w')
the_file.write("\n")
the_file.write(" ")
the_file.close()

notes.txt . :

notes.txt .
22.5 .

print
write().
print. ,
:

my_file = open("new_file.txt", 'w')


print >> my_file, ", !"
my_file.close()
341

> ( ) print,
, . -
(redirecting) .
print, -
.. , , -
print write().
pickle

.
.
, ! !
?
-
, - !
. ?

,
. !
-
, .
, Python
.
pickle.
. . -
. Python -
,
. !

, :

my_list = ['Fred', 73, 'Hello there', 81.9876e-13]

pickle
:

import pickle

, -, ,
dump(). . ,
342 22

, . dump() -
, , :

pickle_file = open('my_pickled_list.pkl', 'w')

'w', -
. .
.pkl ( pickle).
(
) :

pickle.dump(my_list, pickle_file)

, 20.6.

20.6. pickle
import pickle
my_list = ['Fred', 73, 'Hello there', 81.9876e-13]
pickle_file = open('my_pickled_list.pkl', 'w')
pickle.dump(my_list, pickle_file)
pickle_file.close()

. ?

. -
. Python
,
.
load().
, .
. 22.6
my_pickled_list.pkl.
22.7 , .

22.7. load()
import pickle
pickle_file = open('my_pickled_list.pkl', 'r')
recovered_list = pickle.load(pickle_file)
pickle_file.close()

print recovered_list
343

['Fred', 73, 'Hello there', 8.1987599999999997e-012]

, ! .
,
, 16- . -
, 4.
, , -
.

, , ? ,
, ,
. . ,
PyQt, , Pygame
.
,
. , -
. ,
.
GUI-
GUI-
:
-
,
. -
-
.
-
, !
, -
-
. .
Previous guesses ( )
. ,
.
344 22

, . :
;
;
;
;
, .
Guess () :
, ;
:
;
, , ,
;
, ;
Previous guesses;
, ( ).
:
;
You
won! ( !), .
You lost ( ) -
.

, , -
. :

f = open("words.txt", 'r')
self.lines = f.readlines()
for line in self.lines:
line.strip()
f.close()

words.txt , -
readlines().
random.choice():

self.currentword = random.choice(self.lines)
345



. :

def wrong(self):
self.pieces_shown += 1
for i in range(self.pieces_shown):
self.pieces[i].setHidden(False)
if self.pieces_shown == len(self.pieces):
message = "You lose. The word was " + self.currentword
QtGui.QMessageBox.warning(self,"Hangman",message)
self.new_game()

self.pieces_shown
. ,
.


.
, .
, lever, e,
.
. -, find_letters()
. -
e lever [1, 3],
1 3. (, 0.) :

def find_letters(letter, a_string):


locations = []
start = 0
while a_string.find(letter, start, len(a_string)) != -1:
location = a_string.find(letter, start, len(a_string))
locations.append(location)

start = location + 1
return locations

replace_letters() find_letters()
.
----- -e-e-. , ,
.
:
346 22

def replace_letters(string, locations, letter):


new_string = ''
for i in range (0, len(string)):
if i in locations:
new_string = new_string + letter
else:
new_string = new_string + string[i]
return new_string

, , -
find_letters() replace_letters():

if len(guess) == 1: ,

if guess in self.currentword:
locations = find_letters(guess, self.currentword)
? self.word.setText(replace_letters(str(self.word.text()),
locations,guess))
if str(self.word.text()) == self.currentword:


self.win()
else: ,
(
self.wrong() )

95 , , -
(. 22.8 ). -
, \Examples\
Hangman. . hangman.py,
hangman.ui words.txt. Mac,
hangman.ui QtDesigner nativeMenuBar menubar.

22.8. hangman.py
import sys
from PyQt4 import QtCore, QtGui, uic
import random

form_class = uic.loadUiType("hangman.ui")[0]

def find_letters(letter, a_string):


locations = []
start = 0
while a_string.find(letter, start, len(a_string)) != -1:
location = a_string.find(letter, start, len(a_string))
locations.append(location)
start = location + 1
return locations
347

def replace_letters(string, locations, letter):


new_string = ''
for i in range (0, len(string)):

if i in locations: ,
new_string = new_string + letter
else:
new_string = new_string + string[i]
return new_string

def dashes(word):
letters = "abcdefghijklmnopqrstuvwxyz"
new_string = ''


for i in word:
if i in letters:
new_string += "-"
else:
new_string += i
return new_string

class MyWidget(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.btn_guess.clicked.connect(self.btn_guess_clicked)
self.actionExit.triggered.connect(self.menuExit_selected)
self.pieces = [self.head, self.body, self.leftarm, self.leftleg,
self.rightarm, self.rightleg]
self.gallows = [self.line1, self.line2, self.line3, self.line4]
self.pieces_shown = 0
self.currentword = ""
f=open("words.txt", 'r')
self.lines = f.readlines()

f.close()
self.new_game()


def new_game(self):
self.guesses.setText("")
self.currentword = random.choice(self.lines)
self.currentword = self.currentword.strip()
for i in self.pieces:
i.setFrameShadow(QtGui.QFrame.Plain)
i.setHidden(True)
,
for i in self.gallows:
i.setFrameShadow(QtGui.QFrame.Plain)
self.word.setText(dashes(self.currentword))
self.pieces_shown = 0
348 22

def btn_guess_clicked(self):
guess = str(self.guessBox.text())
if str(self.guesses.text()) != "":
self.guesses.setText(str(self.guesses.text())+", "+guess)
else:
self.guesses.setText(guess)
if len(guess) == 1:

if guess in self.currentword:
locations = find_letters(guess, self.currentword)
self.word.setText(replace_letters(str(self.word.text()),
locations,guess))
if str(self.word.text()) == self.currentword:
self.win()
else:
self.wrong()
else:
if guess == self.currentword:
self.win()
else:
self.wrong()
self.guessBox.setText("")

def win(self):
QtGui.QMessageBox.information(self,"Hangman","You win!")
self.new_game()

def wrong(self):
self.pieces_shown += 1
for i in range(self.pieces_shown):
self.pieces[i].setHidden(False)
if self.pieces_shown == len(self.pieces):
message = "You lost. The word was " + self.currentword

QtGui.QMessageBox.warning(self,"Hangman", message)
self.new_game()


def menuExit_selected(self):
self.close()

app = QtGui.QApplication(sys.argv)
myapp = MyWidget(None)
myapp.show()
app.exec_()

.
, .
349

dashes() . -
, . , , doesnt
- - - - - ' -.
. GUI-
Qt-.
. , .ui
.
, . , .
- , !
, , .
.


:
;
;
: , , ;
: write() print >>;
pickle ,
;
( ),
.
, -
.

1. , Python , -
____________________.
2. ?
3. ?
4. , ?
5. , ?
6. , -?
7. , ?
8. pickle Python- ?
350 22

9. pickle
Python-?

1. , . -
:
_______________ ________________ ______________________ _______________.
() () ( ) ()
:

" ."

, -
, , .
, .
,
, -. ,
, :
: , , , , , , ,
;
: , , , , , ;
: , , ,
;
: , , , , .
, :

2. , , ,
. ,
, .
3. 2, pickle.
(: , .)
23


, , .
. .
,
.
K A
( 1) ,
,
random. - AK
,
.
.

.
( , ). ,
Windows.
.
, .
, random
.
, .


-
, , .
, , . ,
. -
. , .
352 23

, .
, , .
.
, -
. . 4,
. , ( )
. 100 50. 20, 44, 67
100 ! , .
, .
, -
. ,
. 99 , , 100-
,
50%. .
,
.
,
, .

. , , -
,
.
random. -,
randint(), .
(1, 2, 3, 4, 5 6), :

import random
die_1 = random.randint(1, 6)

1 6, -
, .
-,
choice(). :

import random
sides = [1, 2, 3, 4, 5, 6]
die_1 = random.choice(sides)
353

, .
choice() .
1 6.

, ?
:

two_dice = random.randint(2, 12)

, 2 12, ?
, . 2 12, ,
1 6.
, .
? . .
. ,
, .
(23.1).

23.1. 1000
import random

 13
0 12
totals = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(1000):
dice_total = random.randint(2, 12)
totals[dice_total] += 1


for i in range (2, 13):
print "", i, "", totals[i], ""

0 12, ,
0 1 .
, . 7,
totals[7]. totals[2]
, totals[3] , ..
, :

2 95
3 81
4 85
5 86
354 23

6 100
7 85
8 94
9 98
10 93
11 84
12 99

, 80 100.
, ,
, . -
. 10000 100000.
(23.2).

23.2. 1000
import random

totals = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in range(1000):
die_1 = random.randint(1, 6)
die_2 = random.randint(1, 6)
dice_total = die_1 + die_2
totals[dice_total] += 1

for i in range (2, 13):


print "", i, "", totals[i], ""

23.2, :

2 22
3 61
4 93
5 111
6 141
7 163
8 134
9 117
10 74
11 62
12 22

,
. 6 7.
355

, .
, :
11- , % 6- , %
2 9,1 2,8
3 9,1 5,6
4 9,1 8,3
5 9,1 11,1
6 9,1 13,9
7 9,1 16,7
8 9,1 13,9
9 9,1 11,1
10 9,1 8,3
11 9,1 5,6
12 9,1 2,8

? ,
. , ,
.
. :

1 + 1 = 2 1 + 2 = 3 1 + 3 = 4 1 + 4 = 5 1 + 5 = 6 1 + 6 = 7
2 + 1 = 3 2 + 2 = 4 2 + 3 = 5 2 + 4 = 6 2 + 5 = 7 2 + 6 = 8
3 + 1 = 4 3 + 2 = 5 3 + 3 = 6 3 + 4 = 7 3 + 5 = 8 3 + 6 = 9
4 + 1 = 5 4 + 2 = 6 4 + 3 = 7 4 + 4 = 8 4 + 5 = 9 4 + 6 = 10
5 + 1 = 6 5 + 2 = 7 5 + 3 = 8 5 + 4 = 9 5 + 5 = 10 5 + 6 = 11
6 + 1 = 7 6 + 2 = 8 6 + 3 = 9 6 + 4 = 10 6 + 5 = 11 6 + 6 = 12
356 23

36 . ,
:
2 1 .
3 2 .
4 3 .
5 4 .
6 5 .
7 6 .
8 5 .
9 4 .
10 3 .
11 2 .
12 1 .
, 7 , 2. 7
, 1+6, 2+5, 3+4, 4+3, 5+2 6+1. 2 -
1+1. , 7
, 2.
.
-
, -
. , 1000
. !

, -
.

.

? ,
. -
, ?
, ,
, .
1000000!
.
, 5, ,
12, 720. 12 (-
, ), 8640.
357

115 ( 4).
. ( , ,
.)
, 10
. , (counter).
. ,
heads_in_row; 10 ,
ten_heads_in_row. .
heads_in_row 1.
heads_in_row 0.
heads_in_row 10,
ten_heads_in_row 1, heads_in_row 0
.

10 .
23.3.

23.3. 10
from random import *
coin = ["Heads", "Tails"]
heads_in_row = 0
ten_heads_in_row = 0

for i in range (1000000):
if choice(coin) == "Heads":
heads_in_row += 1
else:
10 ,
heads_in_row = 0
if heads_in_row == 10:
ten_heads_in_row += 1
heads_in_row = 0

print " 10 ", ten_heads_in_row, "."

10 510 .

, 500.
, 500,
2000 (1000000 / 500 = 2000).
358 23


, ,
. , , .
.
, ,
( ) .
. , (
). .
, 1/52,
2%. , 52, -
. (
), 1/26, 4%. ,
, ,
1/1, 100%. ,
.
, , ,
. .
52 random.choice()
. remove().


!
,
.
, .
random.choice()
.
, . -
.
: ! -
,
, .

card
, . -
? ? ? ?
?
359

:
(suit) (diamonds), (hearts), (clubs) (spades);
(rank) (ace), 2, 3, 10, (jack), (queen), (king).
(value) ( 2 10) -
, , , , 10,
1, 11 .

1 11 8 8
2 2 9 9
3 3 10 10
4 4 10
5 5 10
6 6 10
7 7

. -
, , .
:
card.suit
card.rank
card.value

suit_id rank_id:
suit_id 1 4, 1 , 2 , 3 , 4
.
rank_id 1 13, :
1 ;
2 2;
3 3;

10 10;
11 ;
12 ;
13 .
, 52
for. ( 1 13),
( 1 4). __init__() card suit_id
rank_id , , .
.
360 23

card .
4H 4 of Hearts (4 ),
JD Jack of Diamonds ( ). -
short_name long_name
. (23.4).

23.4. Card
class Card:
def __init__(self, suit_id, rank_id):
self.rank_id = rank_id
self.suit_id = suit_id
if self.rank_id == 1:
self.rank = "Ace"
self.value = 1
elif self.rank_id == 11:
self.rank = "Jack"
self.value = 10
elif self.rank_id == 12:
self.rank = "Queen" rank value
self.value = 10
elif self.rank_id == 13:
self.rank = "King"
self.value = 10
elif 2 <= self.rank_id <= 10:
self.rank = str(self.rank_id)
self.value = self.rank_id
else:
self.rank = "RankError"
self.value = -1

if self.suit_id == 1:
self.suit = "Diamonds"
elif self.suit_id == 2:
self.suit = "Hearts"

suit
elif self.suit_id == 3:
self.suit = "Spades"
elif self.suit_id == 4:
self.suit = "Clubs"
else:
self.suit = "SuitError"
self.short_name = self.rank[0] + self.suit[0]
if self.rank == '10':
self.short_name = self.rank + self.suit[0]
self.long_name = self.rank + " of " + self.suit
361

, rank_id suit_id -
int.
7 of SuitError,
RankError of Clubs.
, short_name, -
(6 Jack) (Diamonds). (King of
Hearts) short_name KH. (6 of Spades)
6S.
23.4 ,
Card. ,
. cards.py.
!
Card 52,
5 . , , -
23.5.

23.5.
import random
from cards import Card
cards
deck = []

for suit_id in range(1, 5):




for rank_id in range(1, 14):
deck.append(Card(suit_id, rank_id)) for

hand = []
for cards in range(0, 5):


a = random.choice(deck)
hand.append(a)
deck.remove(a)

print
for card in hand:
print card.short_name, '=' ,card.long_name, " Value:", card.value

, -
(13 4 = 52).
. .
23.5, :
362 23

7D = 7 of Diamonds Value: 7
9H = 9 of Hearts Value: 9
KH = King of Hearts Value: 10
6S = 6 of Spades Value: 6
KC = King of Clubs Value: 10

.
, .
, . -
!
, .


, -
.

.
.
, .
. -
,
.
. . -
, .
, :
1. , , :
, ;
,
;
.
2. , , -
.
3. , .
4. , . -
, :
50 ;
10 ;
363

;
1 .
5. , ,
.
.
6. .
, .
card. , -
8 50,
8. , __init__ Card,
, cards.
, .
:

deck = []
for suit in range(1, 5):
for rank in range(1, 14):
new_card = Card(suit, rank)
if new_card.rank == 8:
new_card.value = 50
deck.append(new_card)

, -
. 50.
. :
;
(
);
, :
;
;
,
, .
( -
);
( );
;
.
364 23

. -
, .
, .


, ,
.
, .
23.6.

23.6.
init_cards()
while not game_done:
blocked = 0
player_turn() (p_hand)
if len(p_hand) == 0: , ,
game_done = True
print
print " !"
if not game_done:
computer_turn() (c_hand)
, ,
if len(c_hand) == 0:

game_done = True
print
print " !"  ,
if blocked >= 2:
game_done = True
print " . ."

. , -

. blocked , -
. blocked = 2,
.
23.6 , ,
. .
.
.
while:
365

done = False
p_total = c_total = 0
while not done:
[play a game... see listing 23.6]
play_again = raw_input(" (Y/N)? ")
if play_again.lower().startswith('y'):
done = False
else:
done = True

. , , .
int >>
; self.page=self.page+ lf.header_written=0def #
pr

t=1
>Hell

.coun er:se
p ri n t
1Print
elf
o if #
er For att In
>>>H
f#

the page count


ello i

ent
prin

, an
t >>>
if #

cre
itten=1 ; s

m
Hello

r es
et the li
r_wr
a de

l f. e co
un
t se

n
he

n
.

ts
rese e line cou

elf.header_
C ,
.
th

t wr
=1 ;
itte
. sel
n
f
ent the page count, and

.co
unt
, ,

=1
; #!/bin/env
. .,
.
Increm

pyt
h
n#

o

Pa g
ate a
it(0)class #

in
t ex
. tf
ile,

pyprint ename'sys.ex

a
dding a heade

,
.
fil

ra

nd
foot
er im
po

m rt s
ys, time, string # If no argu ts
ge:

en

sa w er
n(sys.argv)!=2: print 'U e giv
le

en, prin
t a helpful message if


, , -
.
. ,
(.23.5).
. ,
Card. , :

hand.remove(chosen_card)
up_card = chosen_card
366 23



. .
. , , ,
.
,
. active_suit:

active_suit = card.suit

,
.


, .
-
. GUI-
, .
, , -
, ,
.
, ,
. :

: 4S, 7D, KC, 10D, QS : 6C


? "Draw", : KC
KC ( )
8S (8 )

: 4S, 7D, 10D, QS : 8S :


? "Draw", : 10D
10D (10 )
QD ( )

: 4S, 7D QS : QD
? "Draw", : 7D
7D (7 )
9D (9 )
367

: 4S, QS : 9D
? "Draw", : QM
. : QD
. : QS
. ,
, 8
: Draw
3C

: 4S, QS, 3C : 9D
? "Draw", : Draw
8C
2D

: 4S, QS, 3C, 8C : 2D


? "Draw", : 8C
8C (8 )

: 4S, QS, 3C : S

: 4S, QS, 3C : 8C :
? "Draw", : QS
QS ( )
.
.
.

, , , . , , , QS
Draw, . -
.
( 21).

, ,
. :

print "\n : ",


for card in p_hand:
print card.short_name,
print " : ", up_card.short_name
368 23

.
(23.7).

23.7.
print "\n : ",
for card in p_hand:
print card.short_name,
print " : ", up_card.short_name
if up_card.rank == '8':
print" ", active_suit

23.6, 23.7 . -
. ( ), :

: 4S, QS, 3C : 8C : Spades

,
:

Your hand: 4 of Spades, Queen of Spades, 3 of Clubs


: 8 of Clubs : Spades


, , .
:
;
.
. ,
.
? (
?)
?

 ? ( -
-

?)
-,
. , ,

369

. , -
,
.
, (23.8).

23.8.
print " ? ",
response = raw_input (" 'Draw', : " )
valid_play = False ,
while not valid_play:
selected_card = None
while selected_card == None:
if response.lower() == 'draw':
valid_play = True 
if len(deck) > 0: draw
card = random.choice(deck)

draw, p_hand.append(card)
deck.remove(card)
print " ", card.short_name

else:

print " " ,
blocked += 1 -
return -

else: -
for card in p_hand:
if response.upper() == card.short_name:
selected_card = card
if selected_card == None:
response = raw_input(" . :")

if selected_card.rank == '8':
valid_play = True
,
is_eight = True
elif selected_card.suit == active_suit:
valid_play = True
elif selected_card.rank == up_card.rank: ,
valid_play = True


if not valid_play:
response = raw_input(" . : ")

( , , .)
370 23

.
, ,
.
,
:

p_hand.remove(selected_card)
up_card = selected_card
active_suit = up_card.suit
print " ", selected_card.short_name

. player_
turn() ,
get_new_suit(). 23.9.

23.9.
def get_new_suit(): ,
global active_suit
got_suit = False
while not got_suit:
suit = raw_input(" : ")
if suit.lower() == 'd':
active_suit = "Diamonds"
got_suit = True
elif suit.lower() == 's':
active_suit = "Spades"
got_suit = True
elif suit.lower() == 'h':
active_suit = "Hearts"
got_suit = True
elif suit.lower() == 'c':
active_suit = "Clubs"
got_suit = True
else:
print " . . ",
print " ", active_suit

, .
.
371


, , -
. ,
. , :
( );
;
.
,
. , .
, . ,

, .
, .
,
,
.
. ,
, , .
, ,
23.10.

23.10.
def computer_turn():
global c_hand, deck, up_card, active_suit, blocked
options = []
for card in c_hand:
if card.rank == '8':
c_hand.remove(card)
up_card = card
print " ", card.short_name
# : [diamonds, hearts, spades, clubs]
suit_totals = [0, 0, 0, 0]
for suit in range(1, 5):
for card in c_hand: -
,
if card.suit_id == suit: ,
suit_totals[suit-1] += 1 -
long_suit = 0 , -

for i in range (4):
372 23

if suit_totals[i] > long_suit:


long_suit = i
if long_suit == 0: active_suit = "Diamonds" ,
if long_suit == 1: active_suit = "Hearts"
if long_suit == 2: active_suit = "Spades" ,

if long_suit == 3: active_suit = "Clubs"
print " ", active_suit
return
else:
if card.suit == active_suit:
options.append(card)

elif card.rank == up_card.rank: ,


options.append(card)

if len(options) > 0:
best_play = options[0]
for card in options:
if card.value > best_play.value: ( )
best_play = card

c_hand.remove(best_play)
up_card = best_play
active_suit = up_card.suit
print " ", best_play.short_name

else:
if len(deck) >0:
next_card = random.choice(deck)
,
c_hand.append(next_card)
deck.remove(next_card)
print " "
else:
print " " ,
blocked += 1
print " %i" % (len(c_hand))

, . , -
, ,
.
, , .
, .
, -
. :
373

def player_turn():
global deck, p_hand, blocked, up_card, active_suit
valid_play = False
is_eight = False
print "\n : ",
for card in p_hand:
print card.short_name,
print " : ", up_card.short_name
if up_card.rank == '8':
print " ", active_suit
print " ? ",
response = raw_input(" 'Draw', : ")


. ,
,
. , . -
, 23.11.

23.11.
done = False
p_total = c_total = 0
while not done:
game_done = False

blocked = 0
init_cards()
while not game_done:
player_turn()
if len(p_hand) == 0:
game_done = True
print
print " !"
#
p_points = 0
for card in c_hand: -
p_points += card.value
p_total += p_points
print " %i " % p_points

374 23

if not game_done:

computer_turn()
if len(c_hand) == 0:
game_done = True
print

print " !"
#
c_points = 0 -
for card in p_hand: -
c_points += card.value
c_total += c_points
print " %i " % c_points
if blocked >= 2:
game_done = True
print " . ."
player_points = 0
for card in c_hand:
p_points += card.value ,

p_total += p_points
c_points = 0
for card in p_hand:
c_points += card.value
c_total += c_points
print " %i " % p_points
print " %i " % c_points
play_again = raw_input(" (Y/N)? ")
if play_again.lower().startswith('y'):
done = False

print "\n %i " % p_total
print " %i .\n" % c_total
else:
done = True
print "\n :"
print ": %i : %i" % (p_total, c_total)

init_cards(), , ,
5 .
23.11 , , ,
. ,
.
( 200 ),
\Examples www.manning.com/books/
hello-world-second-edition. IDLE.
375


:
() ;
;
random ;
;
;
( ).

1. , . .
2. , 2 12
, , ,
2 12?
3. Python ?
4. ?
5. ?
6. ?

23.3, .
? , , .. ?
- ?
24


- , ?
, , , -
, , , , ,
, ..
.
.
, ,
. .
(simulation) .
, , .
, -
.


.
,
. ,
? -
, .
: , ..? -
, ?
, ,
. ? ?
?
-
. -, ! -,
, -?
377

, -
.
:
, ( -
) ;
;
;
, ,
.
.
.
. -
Lunar Lander ( ).

-
. ,

, .
.

(fuel). ,
. -
,
(velocity), (acceleration),
(height) (thrust).


,
.
.
,
.
.
, .
, .
378 24


-
: velocity speed. .
, speed,
velocity.
,
, -
,
velocity.

. -
, -
.

, , .
, ,
.
,
.
:
, ;
( );
, . , -
;
.
, ;
. ,
.
Pygame
Pygame. -
Pygame-.
, , ,
.
,
.
( ),
. draw.
379

rect() . , PyPong,
pygame.font.
:
Pygame-, -
;
;
, , ;
;
;
( -
);
, , -
, ,
Pygame-;
.
Lunar Lander 24.1. Listing_24-1.
py \Examples\LunarLander www.manning.com/books/hello-world-
second-edition. (
). , -
. ,
,
(, , ,
). , , !

24.1. Lunar Lander


import pygame, sys

pygame.init()
screen = pygame.display.set_mode([400,600])
screen.fill([0, 0, 0])
ship = pygame.image.load('lunarlander.png')
moon = pygame.image.load('moonsurface.png')
ground = 540
start = 90
clock = pygame.time.Clock()
ship_mass = 5000.0
fuel = 5000.0
velocity = -100.0 y = 540
gravity = 10
380 24

height = 2000
thrust = 0
delta_v = 0
y_pos = 90
held_down = False

class ThrottleClass(pygame.sprite.Sprite):
def __init__(self, location = [0,0]):
Sprite
pygame.sprite.Sprite.__init__(self)

image_surface = pygame.surface.Surface([30, 10])
image_surface.fill([128,128,128])
self.image = image_surface.convert()
self.rect = self.image.get_rect()
self.rect.left, self.rect.centery = location

def calculate_velocity(): Pygame-


global thrust, fuel, velocity, delta_v, height, y_pos
delta_t = 1/fps
thrust = (500 - myThrottle.rect.centery) * 5.0
fuel -= thrust /(10 * fps) y
if fuel < 0: fuel = 0.0
- if fuel < 0.1: thrust = 0.0
delta_v = delta_t * (-gravity + 200 * thrust / (ship_mass + fuel))
- velocity = velocity + delta_v
, ,

delta_h = velocity * delta_t


height = height + delta_h
y_pos = ground - (height * (ground - start) / 2000) - 90

def display_stats(): -
v_str = "velocity: %i m/s" % velocity
Pygame-
h_str = "height: %.1f" % height y
t_str = "thrust: %i" % thrust
a_str = "acceleration: %.1f" % (delta_v * fps)
f_str = "fuel: %i" % fuel
v_font = pygame.font.Font(None, 26)
v_surf = v_font.render(v_str, 1, (255, 255, 255)) -
screen.blit(v_surf, [10, 50])

a_font = pygame.font.Font(None, 26)
a_surf = a_font.render(a_str, 1, (255, 255, 255))
screen.blit(a_surf, [10, 100])
h_font = pygame.font.Font(None, 26)
h_surf = h_font.render(h_str, 1, (255, 255, 255))
screen.blit(h_surf, [10, 150])
t_font = pygame.font.Font(None, 26)
t_surf = t_font.render(t_str, 1, (255, 255, 255))
screen.blit(t_surf, [10, 200])
381

f_font = pygame.font.Font(None, 26) -


f_surf = f_font.render(f_str, 1, (255, 255, 255)) -

screen.blit(f_surf, [60, 300])

def display_flames():

flame_size = thrust / 15
for i in range (2):
startx = 252 - 10 + i * 19
starty = y_pos + 83
pygame.draw.polygon(screen, [255, 109, 14], [(startx, starty),
(startx + 4, starty + flame_size),
(startx + 8, starty)], 0)

def display_final():
final1 = " "
final2 = " %.1f /" % velocity
if velocity > -5:
final3 = " !"
final4 = " , NASA !"
elif velocity > -15:
final3 = "! , ."
final4 = " ."
else:
final3 = "! 30 ."
final4 = " ?"
pygame.draw.rect(screen, [0, 0, 0], [5, 5, 350, 280],0)
f1_font = pygame.font.Font(None, 70)
f1_surf = f1_font.render(final1, 1, (255, 255, 255))
screen.blit(f1_surf, [20, 50])
f2_font = pygame.font.Font(None, 40)
f2_surf = f2_font.render(final2, 1, (255, 255, 255))
screen.blit(f2_surf, [20, 110])
f3_font = pygame.font.Font(None, 26)
f3_surf = f3_font.render(final3, 1, (255, 255, 255))
screen.blit(f3_surf, [20, 150])
f4_font = pygame.font.Font(None, 26)
f4_surf = f4_font.render(final4, 1, (255, 255, 255))
screen.blit(f4_surf, [20, 180])
pygame.display.flip()

myThrottle = ThrottleClass([15, 500])


running = True
while running:
clock.tick(30)

fps = clock.get_fps() Pygame-
if fps < 1: fps = 30
382 24

if height > 0.01:


calculate_velocity()
screen.fill([0, 0, 0])
display_stats()
pygame.draw.rect(screen, [0, 0, 255], [80, 350, 24, 100], 2)
fuelbar = 96 * fuel / 5000
pygame.draw.rect(screen, [0,255,0],
[84,448-fuelbar,18, fuelbar], 0)
pygame.draw.rect(screen, [255, 0, 0],

[25, 300, 10, 200],0)
screen.blit(moon, [0, 500, 400, 100])
pygame.draw.rect(screen, [60, 60, 60],

[220, 535, 70, 5],0)
screen.blit(myThrottle.image, myThrottle.rect)
display_flames()
screen.blit(ship, [230, y_pos, 50, 90])
instruct1 = " , "
instruct2 = " : < 15 / : < 5 /"
inst1_font = pygame.font.Font(None, 24)
inst1_surf = inst1_font.render(instruct1, 1, (255, 255, 255))
screen.blit(inst1_surf, [50, 550])
inst2_font = pygame.font.Font(None, 24)
inst2_surf = inst1_font.render(instruct2, 1, (255, 255, 255))
screen.blit(inst2_surf, [20, 575])
pygame.display.flip()

else: .
display_final()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
held_down = True

elif event.type == pygame.MOUSEBUTTONUP:
held_down = False
elif event.type == pygame.MOUSEMOTION:
if held_down:
myThrottle.rect.centery = event.pos[1]
if myThrottle.rect.centery < 300:

myThrottle.rect.centery = 300
if myThrottle.rect.centery > 500:
myThrottle.rect.centery = 500
pygame.quit()

. , !
, ,
383

, .
, , .
. -
.
, .


. -
, ,
, .
, , -
. , ,
.
, .
, .
:
8 time.sleep() ;
Pygame- time.delay clock.tick
.
get_fps() , -
( ).
, , -
. ,
. -
, . ,
, .
, .
,
, -
.
,
-
. ,
, -
Python - (timestamp).
.
.
384 24


Python-,
, date-
time. , -
, , .
(delta),
-
.

date- . -
.
time. (, -
.) datetime
, , , , .
( ):

>>> import datetime


>>> when = datetime.datetime(2012, 10, 24, 10, 45, 56)


, :

>>> print when


2012-10-24 10:45:56

datetime when, .
datetime -
( ): , , , , , .
, .
Python:

>>> when = datetime.datetime(hour=10, year=2012, minute=45, month=10,


second=56, day=24)

datetime .
, ( , ).
. :

>>> print when.year


2012
>>> print when.day
24
datetime
>>> print when.ctime()
Wed Oct 24 10:45:56 2012
385

datetime .
, date, , -
. , ,
time, , . :

>>> today = datetime.date(2012, 10, 24)


>>> some_time = datetime.time(10, 45, 56)
>>> print today
2012-10-24
>>> print some_time
10:45:56

datetime, ,
:

>>> today = datetime.date(month=10, day=24, year=2012)


>>> some_time = datetime.time(second=56, hour=10, minute=45)

datetime date time:

>>> today = when.date()


>>> some_time = when.time()

date time datetime -


combine() datetime datetime:

>>> when = datetime.datetime.combine(today, some_time)

, datetime ,
,
.


,
. , ,
, , .
, .
timedelta datetime. ,
, . timedelta
.
386 24

timedelta :

>>> import datetime


>>> yesterday = datetime.datetime(2012, 10, 23)

>>> tomorrow = datetime.datetime(2012, 10, 25)
>>> difference = tomorrow - yesterday
>>> print difference
2 days, 0:00:00 2
>>> print type(difference)
timedelta
<type 'datetime.timedelta'>

, datetime
datetime, timedelta.
Python .


, . (date,
time, datetime timedelta) .
, .
now(), -
:

>>> print datetime.datetime.now()


2012-10-24 21:25:44.343000

, ,
:

44.343000

,
( ).
, !
, ,
, :
44 343000.
. , time
some_time .
:

seconds_float = some_time.second + some_time.microsecond / float(1000000)


387

float() , -
, .
now() timedelta -
. -
24.2
, .
, ,
. .

24.2.
import time, datetime, random
time
sleep()
messages = [
" , .",
" , .",
" , .",
" , .",
" , , .",
" .",
" , , , .",
", ."
] time
sleep()

print " . . ."


time.sleep(2)
print "\n..."
time.sleep(1)

print "\n..."
time.sleep(1)
print "\n:"
message = random.choice(messages)
print "\n " + message
start_time = datetime.datetime.now()
typing = raw_input('>')
end_time = datetime.datetime.now()
diff = end_time - start_time
typing_time = diff.seconds + diff.microseconds / float(1000000)
cps = len(message) / typing_time
wpm = cps * 60 / 5.0 , 1 = 5
388 24

print "\n %i %.1f ." % (len(message),


typing_time)

print " %.2f , %.1f " %(cps, wpm)


if typing == message:

print " ."
else:
print " ."

timedelta, .
datetime, , , , , -
, ( ), timedelta ,
.
, . -
, .


, -
( ),
. , now() -
,
:

2 , 7 , 23 .

, , , -
.
. ,
, -
. , , , !
, ,
.
, .
. :

timeFile.write ("2012-10-24 14:23:37")

split(),
, , , ,
, , .
389

pickle, 22.
, .
datetime, pickle
.
,
. :
. , ,
, os (
). isfile();
, ,
( );
;
,
, , .
24.3. ,
.

24.3. pickle
import datetime, pickle
datetime, pickle os
import os

first_time = True

if os.path.isfile("last_run.pkl"): ( )
pickle_file = open("last_run.pkl", 'r')
last_time = pickle.load(pickle_file)
pickle_file.close() datetime
print " ", last_time
first_time = False ( )

pickle_file = open("last_run.pkl", 'w')
pickle.dump(datetime.datetime.now(), pickle_file)
pickle_file.close() datetime,
if first_time:
print " ."

.
.
390 24


Virtual Pet ( ), -
.
( ). Neopets
Webkinz, .
. ,
, , .. -
, .
, -
. ,
, -
.
.
.
:
(feed), (walk), (play)
(doctor).
:
(hunger), (happiness) (health).

, -
. .
, .
- , ,
.
, happiness .
, health.
happiness, health.
391

happiness.
health , .
:
;
, ;
;
;
;
.
. , .

GUI
PyQt
GUI-. (
), ,
,
, .
Virtual Pet (
). ?
Qt-
MainWindow .
windowTitle
Virtual Pet ( ).

PyQt-, Toolbar (
). , , ,
.
392 24

, -

Add Toolbar ( ).

.

minimumSize. -
100, 50.


() Qt-
Action Editor ( )
.
New
(). -
.
Text (), Qt-
. -
,
(), . -
Choose File ( ) ,
.
OK, .
. .
. Qt- -
.
Progress Bar ( ).
Push Button ( ),
, ,
, .
Label ().
GUI- Qt- -
( examples) .

.
:
393

60 , .
5 , ,
5;
48 , 12 .
, , !
, 0 8;
,
2 ( ,
);
3 ;
2 ;
, 1 ;
1 2;
1 ;
7, 1 2;
8, 1 ;
4 ;
, ( ), ;
, -
.
, ,
. , , , -
, . .

Pygame-. PyQt -
. , .
.
, ,
, .
-.
GUI- :
, .
(0.5), 5.
.
(, ..)
. .
394 24

.
.


. try-except.
, ,
. .
try-except .
, .
, . ,
.
. try-except .
:

try:
file = open("somefile.txt", "r")
except:
print " . ?"

, ( ),
try. .
except . try , -
except, , .
:

try:
( ...)
except:

try-except Python -
(error handling).
, - , -
. ,
,
Virtual Pet.
, 24.4.
. ( -
), \Examples\VirtualPet.
395

www.manning.com/books/hello-world-second-edition.
PyQt -
. , .

24.4. VirtualPet.py
import sys, pickle,datetime
from PyQt4 import QtCore, QtGui, uic

formclass, baseclass = uic.loadUiType("mainwindow.ui")

class MyForm(baseclass, formclass):


def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.doctor = False
self.walking = False
self.sleeping = False
self.playing = False

self.eating = False
self.time_cycle = 0
self.hunger = 0
self.happiness = 8
self.health = 8
self.forceAwake = False
self.sleepImages = ["sleep1.gif","sleep2.gif","sleep3.gif",


"sleep4.gif"]


self.eatImages = ["eat1.gif", "eat2.gif"]
self.walkImages = ["walk1.gif", "walk2.gif", "walk3.gif",
"walk4.gif"]
self.playImages = ["play1.gif", "play2.gif"]
self.doctorImages = ["doc1.gif", "doc2.gif"]
self.nothingImages = ["pet1.gif", "pet2.gif", "pet3.gif"]

self.imageList = self.nothingImages
self.imageIndex = 0
-


-
-

self.actionStop.triggered.connect(self.stop_Click)
self.actionFeed.triggered.connect(self.feed_Click)

self.actionWalk.triggered.connect(self.walk_Click)
self.actionPlay.triggered.connect(self.play_Click)
self.actionDoctor.triggered.connect(self.doctor_Click)

self.myTimer1 = QtCore.QTimer(self)

self.myTimer1.start(500)
self.myTimer1.timeout.connect(self.animation_timer)
self.myTimer2 = QtCore.QTimer(self)
396 24

self.myTimer2.start(5000)
self.myTimer2.timeout.connect(self.tick_timer)

filehandle = True
try:
file = open("savedata_vp.pkl", "r")
except:
filehandle = False
if filehandle:
save_list = pickle.load(file)
file.close() ,
else:
save_list = [8, 8, 0, datetime.datetime.now(), 0]
self.happiness = save_list[0]

self.health = save_list[1]
self.hunger = save_list[2] ,
timestamp_then = save_list[3] ,
self.time_cycle = save_list[4]

difference = datetime.datetime.now() - timestamp_then


ticks = difference.seconds / 50
for i in range(0, ticks): ,
self.time_cycle += 1
if self.time_cycle == 60:

,
self.time_cycle = 0
if self.time_cycle <= 48:
self.sleeping = False


if self.hunger < 8:
self.hunger += 1
else:
self.sleeping = True
if self.hunger < 8 and self.time_cycle % 3 == 0:
self.hunger += 1
if self.hunger == 7 and (self.time_cycle % 2 ==0) \
and self.health > 0:
self.health -= 1
if self.hunger == 8 and self.health > 0:
self.health -=1
if self.sleeping:
self.imageList = self.sleepImages
else:

self.imageList = self.nothingImages

def sleep_test(self):
if self.sleeping:
result = (QtGui.QMessageBox.warning(self, 'WARNING',
"Are you sure you want to wake your pet up? He'll be unhappy about it",
397

QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No))
,
if result == QtGui.QMessageBox.Yes:
self.sleeping = False
self.happiness -= 4
self.forceAwake = True
return True
else:
return False ,
else:
return True

def doctor_Click(self):
if self.sleep_test():
self.imageList = self.doctorImages
self.doctor = True
doctor
self.walking = False
self.eating = False
self.playing = False

def feed_Click(self):
if self.sleep_test():
self.imageList = self.eatImages
feed
self.eating = True
self.walking = False
self.playing = False
self.doctor = False

def play_Click(self):
if self.sleep_test():
self.imageList = self.playImages
self.playing = True play
self.walking = False
self.eating = False
self.doctor = False

def walk_Click(self):
if self.sleep_test():
self.imageList = self.walkImages
self.walking = True
walk
self.eating = False
self.playing = False
self.doctor = False
398 24

def stop_Click(self):
if not self.sleeping:
self.imageList = self.nothingImages

self.walking = False stop
self.eating = False
self.playing = False
self.doctor = False

def animation_timer(self):
if self.sleeping and not self.forceAwake:
self.imageList = self.sleepImages ( 0.5 )
self.imageIndex += 1
if self.imageIndex >= len(self.imageList):
self.imageIndex = 0
icon = QtGui.QIcon()
-
current_image = self.imageList[self.imageIndex] -
icon.addPixmap(QtGui.QPixmap(current_image),
QtGui.QIcon.Disabled, QtGui.QIcon.Off)
self.petPic.setIcon(icon) ()
self.progressBar_1.setProperty("value", (8-self.hunger)*(100/8.0))
self.progressBar_2.setProperty("value", self.happiness*(100/8.0))
self.progressBar_3.setProperty("value", self.health*(100/8.0))

def tick_timer(self):
self.time_cycle += 1
if self.time_cycle == 60: 5-
self.time_cycle = 0
if self.time_cycle <= 48 or self.forceAwake:
self.sleeping = False ,
else:
self.sleeping = True
if self.time_cycle == 0:
self.forceAwake = False
if self.doctor:
self.health += 1
self.hunger += 1
elif self.walking and (self.time_cycle % 2 == 0):
self.happiness += 1
self.health += 1
self.hunger += 1
elif self.playing:

self.happiness += 1
self.hunger += 1
elif self.eating:
self.hunger -= 2
elif self.sleeping:
399

if self.time_cycle % 3 == 0:
self.hunger += 1
else:
self.hunger += 1
if self.time_cycle % 2 == 0:
self.happiness -= 1
if self.hunger > 8: self.hunger = 8
if self.hunger < 0: self.hunger = 0
if self.hunger == 7 and (self.time_cycle % 2 ==0) : ,
self.health -= 1

if self.hunger == 8:
self.health -=1
if self.health > 8: self.health = 8
if self.health < 0: self.health = 0
if self.happiness > 8: self.happiness = 8
if self.happiness < 0: self.happiness = 0
self.progressBar_1.setProperty("value", (8-self.hunger)*(100/8.0))
self.progressBar_2.setProperty("value", self.happiness*(100/8.0))
self.progressBar_3.setProperty("value", self.health*(100/8.0))

def closeEvent(self, event):


file = open("savedata_vp.pkl", "w")
save_list = [self.happiness, self.health, self.hunger, \
datetime.datetime.now(), self.time_cycle]
pickle.dump(save_list, file)
event.accept()


def menuExit_selected(self):

self.close()

app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
app.exec_()

sleep_test() -
PyQt. ,
,
. -
24.4. -
( ) -
:
, , .
PyQt.
400 24

-
. , -
,
, , , .
,
.
,
.

:
;
, ;
;
;
(try-except);
.

1. .
2. ,
.
3.
?

1. Lunar Lander .
, +100/,
:
. !
2. Lunar Lander
.
3. GUI- Virtual Pet Pause (),
, , .
.
(: c ,
.)
25

.
Skier ()? 10 (
!), . , , -
. ,
, -
, .
Python, , , -
, Skier. .

. , , ,
.
. ( ).
: ,
( )
( ).
, :

skier_images = ["skier_down.png",
"skier_right1.png", "skier_right2.png",
"skier_left2.png", "skier_left1.png"]

, .
angle.
2 +2:
2 ;
1 ;
0 ;
+1 ;
+2 .
2 25

( , .)
angle . ,

.
skier_images[0] :

skier_images[1] :

skier_images[2] :

. , 12, , -
, ?
:
skier_images[-1]
( skier_images[4]):
skier_images[-2]
( skier_images[3]):
, :
angle = +2 ( ) = skier_images[2];
angle = +1 ( ) = skier_images[1];
angle = 0 ( ) = skier_images[0];
angle = 1 ( ) = skier_images[-1] (
skier_images[4]);
angle = 2 ( ) = skier_images[-2] (
skier_images[3]).
, Pygame- Sprite. -
100 ,
, x= 320,
640. , [320,
100]. :

class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
. 3

self.image = pygame.image.load("skier_down.png")
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.angle = 0

, angle,
.
x y. (
x-). y- (
). ,
. :

speed = [self.angle, 6 - abs(self.angle) * 2]

abs angle.
(+ ). , -
. .
, :

def turn(self, direction):


self.angle = self.angle + direction
if self.angle < -2: self.angle = -2
if self.angle > 2: self.angle = 2
center = self.rect.center
self.image = pygame.image.load(skier_images[self.angle])
self.rect = self.image.get_rect()
self.rect.center = center
speed = [self.angle, 6 - abs(self.angle) * 2]
return speed

. -
, :

def move(self, speed):


self.rect.centerx = self.rect.centerx + speed[0]
if self.rect.centerx < 20: self.rect.centerx = 20
if self.rect.centerx > 620: self.rect.centerx = 620

-
. ,
, . 25.1.
4 25

25.1.
import pygame, sys, random

skier_images = ["skier_down.png", -
-
"skier_right1.png", "skier_right2.png", -
"skier_left2.png", "skier_left1.png"]

class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("skier_down.png")
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.angle = 0

def turn(self, direction):


self.angle = self.angle + direction
if self.angle < -2: self.angle = -2
if self.angle > 2: self.angle = 2 +/2
center = self.rect.center
self.image = pygame.image.load(skier_images[self.angle])
self.rect = self.image.get_rect()
self.rect.center = center
speed = [self.angle, 6 - abs(self.angle) * 2]
return speed

def move(self, speed):


self.rect.centerx = self.rect.centerx + speed[0]
if self.rect.centerx < 20: self.rect.centerx = 20
if self.rect.centerx > 620: self.rect.centerx = 620

def animate():
screen.fill([255, 255, 255])
screen.blit(skier.image, skier.rect)
pygame.display.flip()

pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]

running = True
while running:
clock.tick(30)
for event in pygame.event.get(): Pygame-
if event.type == pygame.QUIT: running = False
if event.type == pygame.KEYDOWN:
. 5

if event.key == pygame.K_LEFT:
speed = skier.turn(-1)

Pygame-


elif event.key == pygame.K_RIGHT:


speed = skier.turn(1)
skier.move(speed)
animate()

pygame.quit()

25.1, -
( ),
.

,
.

.
.
640 640 .

, 10 10. 100, -
64 64.
, , ,
.


.
ObstacleClass. , Sprite
Pygame:

class ObstacleClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, type):
pygame.sprite.Sprite.__init__(self)
self.image_file = image_file
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.center = location
self.type = type
self.passed = False
6 25


.
10 10 ,
640640 . 10 ( )
100 . .
2 8, 7 3
, 10.
. .
, -
. .
locations, . -
, :

def create_map():
global obstacles 10

locations = []
for i in range(10):
(x, y)
row = random.randint(0, 9)
col = random.randint(0, 9)
location = [col * 64 + 32, row * 64 + 32 + 640]
if not (location in locations):
locations.append(location)
type = random.choice(["tree", "flag"]) ,
if type == "tree": img = "skier_tree.png"
elif type == "flag": img = "skier_flag.png"
obstacle = ObstacleClass(img, location, type)

obstacles.add(obstacle)

640 ,
, ! ,
.

y?
,
. -
.
640 (
) y .

. -
y . , -
. update(),
ObstacleClass:
. 7

def update(self):
global speed
self.rect.centery -= speed[1]

speed .
, x- y-,
[1].
.
? map_position,
. :

running = True
while running:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False

map_position += speed[1]

if map_position >= 640:


create_map() ,
map_position = 0

, ,
animate(). -
, 25.2.

25.2.
import pygame, sys, random

class ObstacleClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, type):
pygame.sprite.Sprite.__init__(self)
self.image_file = image_file
self.image = pygame.image.load(image_file) ,
self.rect = self.image.get_rect()
self.rect.center = location (
self.type = type )
self.passed = False

def update(self):
global speed
self.rect.centery -= speed[1]
8 25

def create_map():

640 x 640
10

-
global obstacles




locations = []
for i in range(10):
row = random.randint(0, 9)
col = random.randint(0, 9)
location = [col * 64 + 32, row * 64 + 32 + 640]
if not (location in locations):
locations.append(location)
type = random.choice(["tree", "flag"])

if type == "tree": img = "skier_tree.png"
elif type == "flag": img = "skier_flag.png"
obstacle = ObstacleClass(img, location, type)
obstacles.add(obstacle)

def animate():
screen.fill([255, 255, 255])
obstacles.draw(screen)
pygame.display.flip()

pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
speed = [0, 6]
obstacles = pygame.sprite.Group()
map_position = 0
create_map()

running = True
while running:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
map_position += speed[1]

if map_position >= 640:

create_map()
map_position = 0

obstacles.update()
animate()

pygame.quit()
. 9

25.2,
:


,

?

, -
.

, y
-
. , -
. -
.
, .
update()
.
. Pygame kill().
update():

def update(self): ,
global speed
self.rect.centery -= speed[1]

if self.rect.centery < -32:
self.kill()

.
SkierClass ObstacleClass.
animate() , .
.
,
.
, 25.3 25.1 25.2.
10 25

25.3.
import pygame, sys, random

skier_images = ["skier_down.png", "skier_right1.png", "skier_right2.png",


"skier_left2.png", "skier_left1.png"]

class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("skier_down.png")
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.angle = 0

def turn(self, direction):


self.angle = self.angle + direction
if self.angle < -2: self.angle = -2
if self.angle > 2: self.angle = 2
center = self.rect.center
self.image = pygame.image.load(skier_images[self.angle])
self.rect = self.image.get_rect()
self.rect.center = center
speed = [self.angle, 6 - abs(self.angle) * 2]
return speed

def move(self, speed):


self.rect.centerx = self.rect.centerx + speed[0]
if self.rect.centerx < 20: self.rect.centerx = 20
if self.rect.centerx > 620: self.rect.centerx = 620

class ObstacleClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, type):
pygame.sprite.Sprite.__init__(self)
self.image_file = image_file
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.center = location
self.type = type
self.passed = False

def update(self):
global speed
self.rect.centery -= speed[1]
if self.rect.centery < -32:
self.kill()
. 11

def create_map():
global obstacles
locations = []
for i in range(10):
row = random.randint(0, 9)
col = random.randint(0, 9)
location = [col * 64 + 32, row * 64 + 32 + 640]
if not (location in locations):
locations.append(location)
type = random.choice(["tree", "flag"])
if type == "tree": img = "skier_tree.png"
elif type == "flag": img = "skier_flag.png"
obstacle = ObstacleClass(img, location, type)
obstacles.add(obstacle)

def animate():
screen.fill([255, 255, 255])
obstacles.draw(screen)
screen.blit(skier.image, skier.rect)
pygame.display.flip()

pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
points = 0

speed = [0, 6]
skier = SkierClass()
obstacles = pygame.sprite.Group()

create_map()
map_position = 0

running = True
while running:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False

if event.type == pygame.KEYDOWN:

if event.key == pygame.K_LEFT:
speed = skier.turn(-1)
elif event.key == pygame.K_RIGHT:
speed = skier.turn(1)
skier.move(speed)

map_position += speed[1]
12 25

if map_position >= 640:


create_map()
map_position = 0

obstacles.update()
animate()

pygame.quit()

25.3,
.
-, , .
.
:
, ;
.
16. 25.3
,
spritecollide() .
:

, 100:
10 , .
:

hit = pygame.sprite.spritecollide(skier, obstacles, False)


if hit:
if hit[0].type == "tree" and not hit[0].passed:
points = points - 100

skier.image = pygame.image.load("skier_crash.png")
animate() -
pygame.time.delay(1000)
skier.image = pygame.image.load("skier_down.png")
skier.angle = 0
speed = [0, 6] ,
hit[0].passed = True

elif hit[0].type == "flag" and not hit[0].passed:


points += 10
hit[0].kill()
. 13

hit , .
, ,
. ,
hit[0].
passed , . ,
, .
. . -
font, Pygame- Font:

font = pygame.font.Font(None, 50)

font ,
:

score_text = font.render("Score: " +str(points), 1, (0, 0, 0))

animate() :

screen.blit(score_text, [10, 10])

. , 10 -
10.1. .
.


:
Skier;
.

1. Skier, . :
;
;
, .
2. SkiFree, Skier,
.
- ,
.
, .
26


. ,
(Artificial Intelligence, AI). -
, 1980 Pac-Man,
, ,
, .

Python Battle
, , Python
Battle ( ). .
, .
. , , . ,
.
: .
, , , -
, . , ,
Python Battle Python.
, ,
Python Battle .
AI-: CircleAI , Ran-
domAI , NullAI
. , .

Python Battle
.
1. , AI- ,
PythonBattle.py.
2. PythonBattle.py.
15

3. :
Enter red AI:

AI-. .py . ,
CircleAI.py, circleai.
4. AI-.
5. , !
6. Pygame-.

, .
,
. -

:
;
;
;
;
;
.
, . 10
.
, CircleAI RandomAI,
? , , ,
( ). 1000
, -
.


CircleAI RandomAI.
, . .
1. , .
2. , .
3. .
16 26

, CircleAI .
, .
. ( better_than_circleai.py)
:

class AI:
def __init__(self):
pass
def turn(self):
pass

, . __init__() -
AI. turn()
. AI,
Python Battle , .
. :
self.robot.lookInFront();
self.robot.turnRight();
self.robot.turnLeft();
self.robot.goForth();
self.robot.attack().
self.robot.xx(), self
, , . AI
. ,
.
turn(). pass :

self.robot.goForth()

, , .
. , -
. self.robot.lookInFront().
, ,
"bot". turn() :

if self.robot.lookInFront() == "bot":
self.robot.attack()
else:
self.robot.goForth()
17

, . -
. self.robot.
lookInFront() "wall". turn()
self.robot.attack() else :

elif self.robot.lookInFront() == "wall":


self.robot.turnRight()

! ,
, ,
.. -
. . ,
, 180. AI
() .
__init__() :

self.currentlyDoing = "forward"

.
"turnRight", ,
. turn()
26.1.

26.1.
class AI:
def __init__(self):
self.currentlyDoing = "forward"
def turn(self):
if self.robot.lookInFront() == "bot":
self.robot.attack()
elif self.robot.lookInFront() == "wall":
self.robot.turnRight()
self.currentlyDoing = "turnRight"
elif self.currentlyDoing == "turnRight":
self.robot.turnRight()
self.currentlyDoing = "forward"
else:
self.robot.goForth()

, , -
. ,
CircleAI.
18 26


CircleAI.
- .
, . .
, .
, .
:
self.robot.goBack() ;
self.robot.checkSpace(space)
;
self.robot.checkSpace((3,3)) , (3,3).
, "blank".
"bot" ( ), "me" (
) "wall" ( );
self.robot.locateEnemy()
;
self.robot.position ;
self.robot.rotation ;
self.robot.calculateCoordinates(direction, distance, position) -
.
Python Battle.

Python Battle (1,1) (10,10). -
, Pygame.
.
self.robot.position.

0 3, 0 (), 1 -
(), 2 (), 3 ().
. , -
, . .
self.robot.rotation.
calculateCoordinates()
calculateCoordinates() : distance (), di-
rection () position ( ).
19

distance position direction.


, calculateCoordinates(2,3,(5,5)) ,
(3 )
(5, 5). . :
1) ;
2) .
:

class AI:
def __init__(self):
pass
def turn(self):
if self.robot.lookInFront() == "bot":
self.robot.attack()

: .
. turn() :

else:
self.goTowards(self.robot.locateEnemy()[0])

self.goTowards() AI -
. self.robot.locateEnemy() -
. , self.goTowards().

def goTowards(self,enemyLocation):
myLocation = self.robot.position
delta = (enemyLocation[0]-myLocation[0],
enemyLocation[1]-myLocation[1])

.
, , :

if abs(delta[0]) > abs(delta[1]):


if delta[0] < 0:

targetOrientation = 3
else:
targetOrientation = 1
else:
if delta[1] < 0:
targetOrientation = 0
else:
targetOrientation = 2
20 26

. -
, :

if self.robot.rotation == targetOrientation:
self.robot.goForth()

, . -
, :

else:
leftTurnsNeeded = (self.robot.rotation - targetOrientation) % 4

. -
, :

if leftTurnsNeeded <= 2:
self.robot.turnLeft()
else:
self.robot.turnRight()

26.2.

26.2.
class AI:
def __init__(self):
pass
def turn(self):
if self.robot.lookInFront() == "bot":
self.robot.attack()
else:
self.goTowards(self.robot.locateEnemy()[0])
def goTowards(self,enemyLocation):
myLocation = self.robot.position
delta = (enemyLocation[0]-myLocation[0],
enemyLocation[1]-myLocation[1])
if abs(delta[0]) > abs(delta[1]):
if delta[0] < 0:
targetOrientation = 3
else:
targetOrientation = 1
else:
if delta[1] < 0:
targetOrientation = 0
else:
targetOrientation = 2
21

if self.robot.rotation == targetOrientation:
self.robot.goForth()
else:
leftTurnsNeeded = (self.robot.rotation - targetOrientation) % 4
if leftTurnsNeeded <= 2:
self.robot.turnLeft()
else:
self.robot.turnRight()

CircleAI. , -
, !
morecomplicatedai.py Python Battle:

>>>
AI: circleai
AI: morecomplicatedai
.
.
.
10!

?!
CircleAI

!

, CircleAI -
. CircleAI ,
.
,
22 26

. ,
. -
, .
, CircleAI .
, ,
CircleAI. , ,
CircleAI. -
, !


:
, -
;
Python
Battle.

,
CircleAI.


,
. , ,
,
.


1
1. Windows IDLE ,
Python2.7, IDLE (Python GUI). MacOSX
IDLE Dock, . -
IDLE.app Python2.7,
Applications. Linux
, Applications Programs.
, Linux IDLE,
Python vi emacs.
2. print ( IDLE-) -
.
3. Python * ().
4. IDLE :
>>> ======================= RESTART =======================
5. .


1. :
>>> print 7 * 24 * 60
(7 , 24 , 60 ). 10080.
2. (, )
:
print " ."
print " 1 1970."
print " ."


1. Python , .
2
2. , ? -
, . :
myAge = 10
24

, :
myAge = 11
, myAge, myAge
: 10 11. 10 11, :
: .
3. TEACHER TEACHEr ,
.
4. Python 'Blah' "Blah" . ,
Python . -
, .
5. Python '4' 4 . (
), . -
.
6. : 2Teacher. Python .
7. "10" , .


1. :
>>> temperature = 25
>>> print temperature
25

2. :
>>> temperature = 40
>>> print temperature
40

:
>>> temperature = temperature + 15
>>> print temperature
40

3. :
>>> firstName = "Fred"
>>> print firstName
Fred

4. , , :
>>> DaysPerWeek = 7
>>> HoursPerDay = 24
>>> MinutesPerHour = 60
>>> print DaysPerWeek * HoursPerDay * MinutesPerHour
10080

5. , 26- , :
>>> HoursPerDay = 26
>>> print DaysPerWeek * HoursPerDay * MinutesPerHour
10920
25


3
1. Python * ().
2. Python : 8 / 3 = 2. 8 3 , Python2
. (, Python3 -
2.66666666667, Python2 .)
3. %. 8 % 3.
4. 8 / 3 ,
: 8.0 / 3 8 / 3.0. (, Python3
.)
5. Python 6 * 6 * 6 * 6 : 6 ** 4.
6. 17000000 : 1.7e7.
7. 4.56e-5 0.0000456 -
.


1. , .
1) , :
>>> print 35.27 * 1.15 / 3
>>> 13.5201666667

, $13.52.
2) :
length = 16.7
width = 12.5
Perimeter = 2 * length + 2 * width
Area = length * width
print ' = ', length, ' = ', width
print " = ", Area
print " = ", Perimeter

:
= 16.7 = 12.5
= 208.75
= 58.4

2. :
fahrenheit = 75
celsius = 5.0/9 * (fahrenheit - 32)
print "Fahrenheit = ", fahrenheit, "Celsius =", celsius

3. :
distance = 200
speed = 80.0
time = distance / speed
print " =", time

(, , , -
.)
26


4
1. int() (
).
2. ?
cel = float(5 / 9 * (fahr - 32))
cel = 5 / 9 * float(fahr - 32)

, :
>>> fahr = 75
>>> cel = float(5 / 9 * (fahr - 32))
>>> print cel
0.0

? , .
:
75 - 32 = 43
:
5 / 9 = 0
, 5 / 9. 5 9
, Python .
1, 0. :
0 * 43 = 0
:
float(0) = 0.0
float() 0!
.
3. int(), , ,
, 0.5. ( ):
>>> a = 13.2
>>> roundoff = int(a + 0.5)
>>> roundoff
13
>>> b = 13.7
>>> roundoff = int(b + 0.5)
>>> b
14

13.5, int() 14 13.


13.5 , int() ,
14, 14.


1. float():
>>> a = float('12.34')
>>> print a
12.34
27

, , ? :
>>> type(a)
<type 'float'>

2. int() :
>>> print int(56.78)
56

.
3. int() :
>>> a = int('75')
>>> print a
75
>>> type(a)
<type 'int'>


5
1. :
answer = raw_input()
12 answer,
raw_input() .
:
print " : ",
answer = raw_input()
print type(answer)
>>> ============== RESTART ==============
>>>
: 12
<type 'str'>
>>>

, raw_input() .
, Python 3 raw_input() input().
2. raw_input() , -
, :
answer = raw_input(" : ")
3. raw_input() ,
int() raw_input() .
:
something = raw_input()
answer = int()

:
answer = int(raw_input())
4. , int()
float().
28


1. :
>>> first = ''
>>> last = ''
>>> print first + last

! . :
>>> first = ' '
:
>>> print first + ' ' + last

:
>>> first = ''
>>> last = ''
>>> print first, last

2. :
first = raw_input(' : ')
last = raw_input(' : ')
print ',', first, last, ' ?'

3. :
length = float(raw_input (' : '))
width = float(raw_input (' : '))
area = length * width
print '', area, ' .'

4. #C:
length = float(raw_input (' : '))
width = float(raw_input (' : '))
cost_per_metre = float(raw_input (' : '))
area_cm = length * width
area_metre = area_cm / 10000.0
total_cost = area_metre * cost_per_metre
print ' ', area_cm, ' .'
print '', area_metre, ' .'
print ' ', total_cost

5. :
kop50 = int(raw_input(" 50 ? "))
kop10 = int(raw_input(" 10 ? "))
kop5 = int(raw_input(" 5 ? "))
kop1 = int(raw_input(" 1 ? "))
total = 0.50 * kop50 + 0.10 * kop10 + 0.05 * kop5 + 0.01 * kop1
print " : ", total


6 1. EasyGui msgbox(), :
easygui.msgbox(" !")
29

2. EasyGui enterbox.
3. enterbox ( )
. integerbox.
4. enterbox, -
float().
5. , , . -
, , . ,
, , ,
, . .


1. , EasyGui:
# tempgui1.py
# EasyGui-
#
import easygui

easygui.msgbox(' ')
temperature = easygui.enterbox(' :')
Fahr = float(temperature)
Cel = (Fahr - 32) * 5.0 / 9
easygui.msgbox(' ' + str(Cel) + ' .')

2. , , -
. .
\n. 21, :
# address.py
#
import easygui

name = easygui.enterbox(" ?")


addr = easygui.enterbox(" ?")
house = easygui.enterbox(" ?")
flat = easygui.enterbox(" ?")
city = easygui.enterbox(" ?")
country = easygui.enterbox(" ?")
code = easygui.enterbox(" ?")

whole_addr = code + ", " + country + ", " + city + "\n"


+ addr + ", " + house + ", " + flat + "\n" + name

easygui.msgbox(whole_addr, " :")


7
1. , :
20
my_number 20, if true,
( ).
2. ,
20
30

my_number 20, if false,


if . else.
3. , 30, 40, :
if number > 30 and number <= 40:
print ' 30 40'
:
if 30 < number <= 40:
print " 30 40"

4. Q :
if answer == 'Q' or answer == 'q':
print " 'Q' "
, ,
, Q. :
, .


1. :
#
# 10% $10, 20% $10
item_price = float(raw_input (' : '))
if item_price <= 10.0:
discount = item_price * 0.10
else:
discount = item_price * 0.20
final_price = item_price - discount
print ' ', discount, ' ', final_price
( )
.
2. :
#
# 10 12
gender = raw_input(" ? ('m' or 'f') ")
if gender == 'f':
age = int(raw_input(' ? '))
if age >= 10 and age <= 12:
print ' '
else:
print ' .'
else:
print ' .'

3. :
# , .
# 200
tank_size = int(raw_input(' ( )? '))
full = int(raw_input (' ?'))
mileage = int(raw_input (' ( )? '))
range = tank_size * (full / 100.0) * mileage
print ' ', range, '.'
print ' 200 .'
31

if range <= 200:


print ' !'
else:
print ' .'

5 , :
range = tank_size * (full / 100.0) * mileage
:
range = (tank_size - 5) * (full / 100.0) * mileage
4.
password = "bigsecret"
guess = raw_input(" : ")
if guess == password:
print " . !"
#
else:
print " . !"


8
1. .
2. : i = 1, i = 3, i = 5.
3. range(1, 8) [1, 2, 3, 4, 5, 6, 7].
4. range(8) [0, 1, 2, 3, 4, 5, 6, 7].
5. range(2, 9, 2) [2, 4, 6, 8].
6. range (10, 0, -2) [10, 8, 6, 4, 2].
7.
continue.
8. while , false.


1. , for
:
# 10
number = int(raw_input(' ? '))
print ' :'
for i in range(1, 11):
print number, 'x', i, '=', number * i

2. while:
# ( while)
number = int(raw_input(' ? '))
print ' :'
i = 1
while i <= 10:
print number, '', i, '=', number * i
i = i + 1

3. :
#
#
32

number = int(raw_input(' ? '))


limit = int(raw_input(' ? '))
print ' :'
for i in range(1, limit + 1):
print number, '', i, '=', number * i
, for range() , -
. 11.


9
, :
# tempconv1.py
# ,
Fahr = 75
Cel = (Fahr - 32) * 5.0 / 9 # ,
print "Fahrenheit = ", Fahr, "Celsius = ", Cel


10
, .


11
1. Python range():
for i in range(numberOfLoops)
:
for i in range(1, someNumber)
2. , :
for i in range(5):
for j in range(8):
print "",
print

( ),
( ).
3. 15 .
4. :
* * *
* * *
* * *
* * *
* * *

5. 2**4, 2*2*2*2, .
16 .


1. , , -
:
# ,
import time
33

start = int(raw_input(" : ? ", ))


for i in range (start, 0, -1):
print i
time.sleep(1)
print "!"

2. :
# ,
#
import time
start = int(raw_input(" : ? ", ))
for i in range (start, 0, -1):
print i,
for star in range(i):
print '*',
print
time.sleep(1)
print "!"


12
1. append(), insert() extend().
2. remove() pop() del.
3. :
new_list = my_list[:]
: new_list.sort();
sorted(): new_list = sorted(my_list).
4. in.
5. index().
6. .
7. :
:
>>> my_list = [[1, 2, 3], ['a', 'b', 'c'], ['red', 'green', 'blue']]
append():
>>> my_list = []
>>> my_list.append([1, 2, 3])
>>> my_list.append(['a', 'b', 'c'])
>>> my_list.append(['red', 'green', 'blue'])
>>> print my_list
[[1, 2, 3], ['a', 'b', 'c'], ['red', 'green', 'blue']]

:
>>> list1 = [1, 2, 3]
>>> list2 = ['a', 'b', 'c']
>>> list3 = ['red', 'green', 'blue']
>>> my_list = [list1, list2, list3]
>>> print my_list
[[1, 2, 3], ['a', 'b', 'c'], ['red', 'green', 'blue']]

8. :
my_list = [[1, 2, 3], ['a', 'b', 'c'], ['red', 'green', 'blue']]
my_color = my_list[2][1]
34

'green'.
9. .
10.
:
phone_numbers['John'] = '555-1234'
11.
:
print phone_numbers['John']


1. , , :
nameList = []
print " 5 ( Enter):"
for i in range(5):
name = raw_input()
nameList.append(name)

print " :", nameList

2. , :
nameList = []
print " 5 ( Enter):"
for i in range(5):
name = raw_input()
nameList.append(name)

print " :", nameList


print " :", sorted(nameList)

3. , :
nameList = []
print " 5 ( Enter):"
for i in range(5):
name = raw_input()
nameList.append(name)

print " :", nameList[2]

4. , :
nameList = []
print " 5 ( Enter):"
for i in range(5):
name = raw_input()
nameList.append(name)

print " :", nameList


print " ? (1-5):",
replace = int(raw_input())
new = raw_input(" : ")
nameList[replace - 1] = new
print " :", nameList

5. , :
35

user_dictionary = {}
while 1:
command = raw_input("'a' ,
'l' ,
'q' ")

if command == "a":
word = raw_input(" : ")
definition = raw_input(" : ")
user_dictionary[word] = definition
print " !"

elif command == "l":


word = raw_input(" : ")
if word in user_dictionary.keys():
print user_dictionary[word]
else:
print " ."

elif command == 'q':


break


13
1. def.
2. , .
3. .
4. .
5. return.
6. .


1. print:
def printMyNameBig():
print " CCCC A RRRRR TTTTTTT EEEEEE RRRRR "
print " C C A A R R T E R R "
print "C A A R R T EEEE R R "
print "C AAAAAAA RRRRR T E RRRRR "
print " C C A A R R T E R R "
print " CCCC A A R R T EEEEEE R R"

:
for i in range(5):
printMyNameBig()

2. , :
#
def printAddr(name, num, street, city, prov, pcode, country):
print name
print num,
print street
print city,
if prov !="":
print ", "+prov
36

else:
print ""
print pcode
print country
print

#
printAddr("Sam", "45", "Main St.", "Ottawa", "ON", "K2M 2E9", "Canada")
printAddr("Jian", "64", "2nd Ave.", "Hong Kong", "", "235643", "China")

3. , .
4. :
def addUpChange(kop50, kop10, kop5, kop1):
total = 0.50 * kop50 + 0.10 * kop10 + 0.05 * kop5 + 0.01 * kop1
return total

:
kop50 = int(raw_input(" 50 : "))
kop10 = int(raw_input(" 10 : "))
kop5 = int(raw_input(" 5 : "))
kop1 = int(raw_input(" 1 : "))

total = addUpChange(kop50, kop10, kop5, kop1)

print " : ", total


14
1. class.
2. .
.
3. , .
.
4. , , . , -
.
5. self .
6. ,
. ,
.
7. -
. ( , ) -
,
.

1. :
class BankAccount:
def __init__(self, acct_number, acct_name):
self.acct_number = acct_number
self.acct_name = acct_name
self.balance = 0.0

def displayBalance(self):
print " :", self.balance
37

def deposit(self, amount):


self.balance = self.balance + amount
print " ", amount
print " :", self.balance

def withdraw(self, amount):


if self.balance >= amount:
self.balance = self.balance - amount
print " ", amount
print " :", self.balance
else:
print " ", amount
print " :", self.balance
print " . ."
, , :
myAccount = BankAccount(234567, "Warren Sande")
print " :", myAccount.acct_name
print " :", myAccount.acct_number
myAccount.displayBalance()

myAccount.deposit(34.52)
myAccount.withdraw(12.25)
myAccount.withdraw(30.18)
2. BankAccount
:
add interest:
class InterestAccount(BankAccount):
def __init__(self, acct_number, acct_name, rate):
BankAccount.__init__(self, acct_number, acct_name)
self.rate = rate

def addInterest (self):


interest = self.balance * self.rate
print " ,", self.rate * 100, ""
self.deposit (interest)

:
myAccount = InterestAccount(234567, "Warren Sande", 0.11)
print " :", myAccount.acct_name
print " :", myAccount.acct_number
myAccount.displayBalance()
myAccount.deposit(34.52)
myAccount.addInterest()


15
1. , :
;
, ;
, , ;
(), .
2. Python .
3. import.
4. .
38

5. time :
import time
:
from time import *


1. , ,
, , bigname.py. :
import bigname
bigname.printMyNameBig()

:
from bigname import *
printMyNameBig()

2. c_to_f() :
from my_module import c_to_f
:
from my_module import *
3. 1 20:
import random
for i in range(5):
print random.randint(1, 20)

4. , 30 3 :
import random, time
for i in range(10):
print random.random()
time.sleep(3)


16
1. RGB- [255, 255, 255] .
2. RGB- [0, 255, 0] .
3. Pygame- pygame.draw.rect().
4. , , pygame.
draw.lines().
5. (pixel) picture element
( ).
6. Pygame- [0, 0] .
7. [50, 200] B.
8. [300, 50] D.
9. blit() Pygame- .
10.
:
;
.
39


1. , , TIO_CH16_1.py
\answers :
import pygame, sys
pygame.init()
screen=pygame.display.set_mode((640, 480))
screen.fill((250, 120, 0))
pygame.draw.arc(screen, (255, 255, 0), pygame.rect.Rect(43, 368, 277,
235), -6.25, 0, 15)
pygame.draw.rect(screen, (255, 0, 0), pygame.rect.Rect(334, 191, 190,
290))
pygame.draw.rect(screen, (128, 64, 0), pygame.rect.Rect(391, 349, 76,
132))
pygame.draw.line(screen, (0, 255, 0), (268, 259), (438, 84), 25)
pygame.draw.line(screen, (0, 255, 0), (578, 259), (438, 84), 25)
pygame.draw.circle(screen, (0, 0, 0), (452, 409), 11, 2)
pygame.draw.polygon(screen, (0, 0, 255), [(39, 39), (44, 136), (59,
136), (60, 102), (92, 102), (94, 131), (107, 141), (111, 50),
(97, 50), (93, 86), (60, 82), (58, 38)], 5)
pygame.draw.rect(screen, (0, 0, 255), pygame.rect.Rect(143, 90, 23, 63),
5)
pygame.draw.circle(screen, (0, 0, 255), (153, 60), 15, 5)
clock = pygame.time.Clock()
pygame.display.flip()

running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
pygame.quit()

2. ,
:
my_ball = pygame.image.load('beach_ball.png')
3. 16.16 :
x_speed = 10
y_speed = 10

:
x_speed = 20
y_speed = 8

4. , 16.16 :
if x > screen.get_width() - 90 or x < 0:
:
if x > screen.get_width() - 250 or x < 0:
, . -
, y.
40

5. 16.6 display.flip while -


:
import pygame, sys, random
pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill([255, 255, 255])
for i in range (100):
width = random.randint(0, 250)
height = random.randint(0, 100)
top = random.randint(0, 400)
left = random.randint(0, 500)
pygame.draw.rect(screen, [0,0,0], [left, top, width, height], 1)
pygame.display.flip()
pygame.time.delay(30)
, -
.
, .


17
1.
, .
2.
. -
. ,
.
3. Python-,
Pygame-.
4. ( )
, pygame.time.Clock, .
, ( ) .
5. ,
. .
6. pygame.time.Clock.
get_fps().


18
1. .
2. , , .
3. Pygame KEYDOWN.
4. pos .
5. pygame.
USEREVENT.
6. pygame.time.set_timer().
7. Pygame- font.
8. Pygame-:
font;
, ;
( ) .
41


1. ?
, y-
( , ).
. ( )
, , .. -
, (
y-). ,
, ! ,
, . .
, , ,
.
2. TIO_CH18_2.py
.

19
1. : Wave (.wav), MP3 (.mp3), Ogg Vorbis (.ogg) Windows
Media Audio (.wma).
2. pygame.mixer.
3. Pygame-
set_volume().
4. pygame.mixer.music.set_
volume().
5. pygame.mixer.music.fadeout(). -
( ), . ,
pygame.mixer.music.fadeout(2000) 2 .


TIO_CH19_1.py .

20
1. GUI- , .
2. , ( Alt) , -
.
3. Qt- .ui.
4. , GUI PyQt, , ,
, , , , , ,
, . Widget Box Qt-.
5. , .
6. & () Qt- .
7. Qt- .

1. , Qt-,
TIO_CH20_1.py TIO_CH20_1.ui.
2. Qt-
minimum maximum. minimum 1000,
maximum - , 1000000.
42

21
1. print , :
print " ",
print " ?"

2. , print:
print "Hello"
print
print
print
print "World"

\n:
print "Hello\n\n\nWorld"
3. \t.
4. %e
%E:
>>> number = 12.3456
>>> print '%e' % number
1.234560e+001


1. :
name = raw_input(" ? ")
age = int(raw_input(" ? "))
color = raw_input(" ? ")

print " ", name,


print "", age, ",",
print " ", color

2. :
for looper in range(1, 11):
print looper, "\ttimes 8 =\t", looper * 8

\t times =.
3. , 8:
for i in range(1, 9):
fraction = i / 8.0
print str(i) + '/8 = %.3f' % fraction

, print str(i) + '/8 =, . , %.3f' %fraction,


.

22
1. Python , , .
2. Python open().
3. ( ).
Python.
.
43

4. .
5. , , , .
6. , , , .
7. , ,
seek() 0:
myFile.seek(0)
8. Python- pickle pickle.
dump(), :
pickle.dump(myObject, "my_pickle_file.pkl")
9. pickle.load(),
:
myObject = pickle.load("my_pickle_file.pkl")


1. , :
import random

noun_file = open("nouns.txt", 'r')


nouns = noun_file.readline()
noun_list = nouns.split(',')
noun_file.close()

adj_file = open("adjectives.txt", 'r')


adjectives = adj_file.readline()
adj_list = adjectives.split(',')
adj_file.close()

verb_file = open("verbs.txt", 'r')


verbs = verb_file.readline()
verb_list = verbs.split(',')
verb_file.close()

adverb_file = open("adverbs.txt", 'r')


adverbs = adverb_file.readline()
adverb_list = adverbs.split(',')
adverb_file.close()

noun = random.choice(noun_list)
adj = random.choice(adj_list)
verb = random.choice(verb_list)
adverb = random.choice(adverb_list)

print "The", adj, noun, verb, adverb + '.'

, .
2. , :
name = raw_input(" : ")
age = raw_input(" : ")
color = raw_input(" : ")
food = raw_input(" : ")
44

my_data = open("my_data_file.txt", 'w')


my_data.write(name + "\n")
my_data.write(age + "\n")
my_data.write(color + "\n")
my_data.write(food)

my_data.close()

3. , pickle:
import pickle
name = raw_input(" : ")
age = raw_input(" : ")
color = raw_input(" : ")
food = raw_input(" : ")

my_list = [name, age, color, food]

pickle_file = open("my_pickle_file.pkl", 'w')


pickle.dump(my_list, pickle_file)

pickle_file.close()


23
1. , . -
( , )
( ).
2. ,
2 12 .
( )
.
3. :
import random
sides = [1, 2, 3, 4, 5, 6]
die_1 = random.choice(sides)

:
import random
die_1 = random.randint(1, 6)

4. .
5. .
( ).
6. remove(), : deck.remove()
hand.remove().


, .


24
1. :
( );
( );
45

( , -
);
( ,
), , ;
( , ),
, .
2. , . , -
,
.
3.
timedelta.

www.manning.com/books/hello-world-second-edition:
1. TIO_CH24_1.py Lunar Lander .
2. TIO_CH24_2.py Lunar Lander .
3. TIO_CH24_3.py GUI- Virtual Pet Pause.


26
, CircleAI:
class AI:
def __init__(self):
self.isFirstTurn = True
def turn(self):
if self.isFirstTurn:
self.robot.turnLeft()
self.isFirstTurn = False
elif self.robot.lookInFront() == "bot":
self.robot.attack()
else:
self.robot.doNothing()

, CircleAI , , .
CircleAI,
. , , ,
, .