Вы находитесь на странице: 1из 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.bo