Открыть Электронные книги
Категории
Открыть Аудиокниги
Категории
Открыть Журналы
Категории
Открыть Документы
Категории
2-018
004.42
18
., .
Hello World! . .: , 2016. 400 .:
. ( ).
ISBN 978-5-496-01273-7
! ? -
? , ,
, ! -
! , .
, , , ...
. ? ,
. ,
. , -
, , ,
Python (). , -
. .
Python . -
. , ,
, , .
, . e-mail,
, mp3, .
!
ISBN 978-1617290923 . .
ISBN 978-5-496-01273-7 .
.
Manning Publications, 2014
.
, 2016
.
,
, 2016 . , .
, 2016 .
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
-
!
. -
, 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 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
, !
Python . -
>>> :
Enter ( Return). -
Enter .
20 1
Enter :
Hello World!
>>>
, IDLE.
Python (print
) . ( ,
- , -
.)
Python . , !
!
! >>> d`, cnqondhm...
, : , ,
Hello World!, , !
. .
!
21
IDLE
! IDLE - ?
.
. ( , -
-
, Python.) ,
, .
- :
, , Python
. print (pront), Python
, . , -
, , .
. , print
Python, pront .
pront
,
print.
,
Python (
).
Python
Python . (-
), Python .
22 1
, -
, .
.
>>> :
8
>>>
, Python ! ,
.
:
*
. , .
5 3 5 3,
Python *. (
, 8.)
5 3
.
Python,
!
, ?
,
! . -
.
-, Python:
-
. 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 ( ).
.
RESTART , . ( ,
.)
. ,
, , .
.
26 1
-
, ? -
, . ,
, .
IDLE . - -
, , , .
, ,
-, Python.
:
, Python ( IDLE)
. ,
.
:
, .
, :
27
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
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 " !"
, ,
while, , if
elif. . -
, , .
RunRun Module,
. , . -
:
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-.
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 , . :
, -
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
PrinterF
he
f#
print
ello i
>>>He
#
ade
llo if
e+ 1
print
pag
r an
>>>H
f#
ello i
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
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
, , print.
( .)
print. -
First Second ,
Third. Third First Second.
. -
:
.
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 ,
. :
.
Python ,
. , :
>>> first = 5
>>> second = 3
>>> first + second
8
>>> first = '5'
>>> second = '3'
>>> first + second
'53'
5 3 , .
"5" "3" ,
"53".
, 1:
,
. .
: 39
,
.
.
(,
), .
. :
long_string = """ , :
, .
, .
,
."""
.
, ,
:
long_string = ''' , :
, .
, .
,
.'''
, ,
.
. , !
. Python
, ().
MyTeacher . MyTeacher
"Mrs. Goodyear" "Mrs. Tysick".
MyTeacher .
40 2
. Teacher?
IDLE, . :
>>> Teacher
'Mr. Morton'
"Mr. Smith"
Teacher. -
.
"Mr. Morton"?
( ). -
"Mr. Morton" - -
, . ,
, Python
.
. -
, .
, "Mr. Morton"
"Mr. Smith". ( )
. Python ( ), -
. ( ),
.
Python . 12,
.
>>> Score = 7
>>> Score = Score
: 41
, . .
: . -
:
? 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
-
. .
,
.
. , -
. , 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
(),
(/):
, , :
? .
, :
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. .
:
, 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-,
,
. , ^
,
, .
.
**.
, .
, ** . :
.
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 .
:
.
, - -
.
, . ,
,
!
: 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
-. :
, .
.
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'>
int() float() - , .
:
, , Python
, "fred" . ?
,
. , -
, 5 5.0 9 9.0?
float():
:
(, ,
) : str(), int() float();
61
, print;
type();
.
1. -
int()?
2. , ?
cel = float(5 / 9 * (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
, ,
:
raw_input() :
someName = raw_input()
, -
, print . :
, .
:
, 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 :
, 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, -
.
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
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():
. -
. (
, 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
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 )
,
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 :
Python
EasyGui. , ,
. (www.manning.
com/books/hello-world-second-edition) .
OK:
msgbox() EasyGui . -
EasyGui
( message box).
msgbox() -
:
OK -
.
GUI-
GUI-
. ?
OK -
. ,
:
>>> import easygui
>>> easygui.msgbox("Hello there!")
'OK'
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))
. 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
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,
, .
:
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
.
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 <>
. , !=.
, -
:
, age 8 12, -
. age
9, 10 11 ( 8.1, 11.6, ..).
8 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
,
:
( ).
, , .
, ? , -
,
. . :
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
,
. :
and. , -
.
if
age>=8 and grade>=3
( )
and :
, if
. .
or
or .
:
if
(
)
not
not. :
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.)
:
, . 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 . :
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 . :
, .
:
( 10
20) ,
( ).
!
range()
-
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.) :
, -
- ! ?
, range (1, 5) [1, 2, 3, 4]. -
:
96 8
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
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):
: [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
range() 2.
2. :
5. ?
,
?
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 ' ?'
i = 2 , ?
i = 3 ,
i = 4 , ?
i = 5 , ?
, ( i == 3)
(i == 4). -
continue. while.
break
, ,
? break.
104 8
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 ', '
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 ' '
, :
. , -
#, , .
. :
#. , , -
.
.
#. :
# ***************
# , Python
#
#
# ***************
. . -
,
, ,
.
108 9
, Python -
. -
. 2 ,
. , :
""" ,
.
,
.
"""
,
. -
, , , Python .
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
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
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
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
obstacles.update()
score_text = font.render("Score: " +str(points), 1, (0, 0, 0))
animate()
pygame.quit()
\examples\skier.
, . -
, .
, -
. , , -
.
, , 10.1
. , -
, . !
11
, ( )
, .
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:
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
, .
, -
, .
.
, -
. .
, , -
. ,
. ,
.
, .
, .
,
, :
, , -
, . , -
! , ! ,
118 11
for range.
, , 1:
, , .
( 8.) ,
. :
.
, 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
, , .
:
,
.
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
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
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
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * * *
11.4
. ,
,
.
.
,
, 11.5.
11.5.
numBlocks = int(raw_input(' ? '))
for block in range(1, numBlocks + 1):
121
= 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. -
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
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 .
:
,
, . ,
.
- (11.7).
11.7. -
dog_cal = 140
bun_cal = 120
ket_cal = 80 -
mus_cal = 20
onion_cal = 40
126 11
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. :
# 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 :
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. -
, , .
. ,
, , . :
, -
, , .
:
. -
0, , letters[0],
:
,
(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
, :
(type) ,
, (str), (list).
, ,
. ,
.
. ,
, , ,
. ,
, , -
. ,
.
,
. :
. -
(
). :
, , -
.
, .
:
, , ? ,
letters[:] . ,
- , .
.
, 0 4.
:
letters[5] = 'f'
. ( , .)
, . -
, :
, 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() :
, extend() .
, extend ,
.
, extend(),
.
insert()
insert() .
:
z 2.
( ). c,
, .
.
append() extend()
append() extend() , -
. .
extend():
137
append():
? , append()
. , ? .
, , .
. ,
, .
.
insert() append() ,
, append()
.
, ? :
remove(), del pop().
remove()
remove() :
, . ,
. -
:
>>> 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 . :
( 3), d.
pop()
pop() .
:
pop() :
( 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.
, letters a, s.
in remove() ,
, :
if 'a' in letters:
letters.remove('a')
, .
140 12
index():
, d 3,
. remove(), index(),
, ,
in:
if 'd' in letters:
print letters.index('d')
, -
. range()
. , .
,
. ,
. :
letter. (
looper, i, j k.)
,
letter .
. ,
().
,
141
sort() , -
.
, sort() .
, .
:
. :
>>> letters.sort()
>>> print letters
.
, .
, :
reverse(),
.
142 12
sort() ,
( ):
, reverse, , , -
.
,
.
. ,
, .
:
, ,
,
, , . ,
-, -
new_list = original_list[:]
( 2),
, name1 = name2 -
,
. ?
new_list = original_list
?
143
, .
new_list original_list
. ( )
. . :
new.sort() original
1,2,3,4,5
new
new,
original, new original .
, new :
new 6,7,8,9,10
2.
, , new
= original. ,
: new = original[:].
. :
. new. -
.
sorted()
-
. Python
sorted(). :
sorted() .
, 2 ,
.
( , ). -
Python. ,
, , .
. Python
, .
, . Python
? ! , (tuple), -
. :
, , .
, ,
- . .
:
, ,
.
145
myTeacher ( ) ( ):
( ) ,
:
(
, , ):
Joe 55 63 77 81
Tom 65 61 67 72
Beth 97 95 92 88
? ,
. :
, ?
,
:
(data structure) -
, -
. ,
, -
. -
.
, .
. classMarks
.
, classMarks
joeMarks, tomMarks bethMarks. :
. classMarks
, . -
in:
classMarks. -
studentMarks.
. .
( .)
, .
, .
( ) ?
, (joeMarks) ,
classMarks. :
147
classMarks[0] Joe.
. ? -
.
Joe ( ) 2. ,
, :
!
.
!
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
,
, .
:
, :
, .
, , (
).
:
.
append(), . -
:
, , , .
- :
, , , -
, .
150 12
. ,
.
.
, (
), , ,
.
, -
.
.
. ,
, . .
. ,
, , -
.
,
:
, Python ,
. , , ,
.
keys() :
>>> phoneNumbers.keys()
['', '', '', '']
, values() :
>>> phoneNumbers.values()
['444-4321', '555-1234', '555-6789', '867-5309']
, Python-, .
(
). -.
151
, , ,
( , , ),
(, ) ().
, , ,
, . ,
, .
. ,
(, , , ).
,
.
, , , . ,
. , ,
, .
. ,
, , ,
sorted() , :
sorted(),
. , ,
.
, , , -
? ,
. .
, . -
. , :
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()
.
1. . .
2. .
3. .
4.
.
157
. ,
, .
, .
- , . 13.1
, . :
-
:
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
,
. , ...
,
. ,
!
.
.
-
,
. , ,
.
, : -
, - !
, ,
?
. -
. .
, ,
. ,
. 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 , :
, -
. :
160 13
printMyAddress("Carter Sande")
printMyAddress("Warren Sande")
printMyAddress("Kyra Sande")
printMyAddress("Patricia Sande")
.
, :
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
( ) , ,
.
?
, ,
. , --
, .
. -
(), ,
.
- -
163
,
, , - .
- .
, (),
. ,
, .
- -
- -
return. ,
, :
taxTotal ,
. ? -
. :
calculateTax 8.4694, -
totalPrice.
, -
. ( ),
, :
164 13
, :
,
.
. 13.4 -
calculateTax().
, .
. ,
, (=) .
, calculateTax().
13.4. ,
def calculateTax(price, tax_rate):
total = price + (price * tax_rate)
return total
, 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
: 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
? ! ?
, , , 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 :
, my_price -
. -, calculateTax(),
10000. -, , -
, 7.99.
, -
Python -
. ,
.
, -
. ?
Python global, -
. :
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. , , -
:
, .
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 = ""
14.2:
176 14
, 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
14.3
__init__().
,
__str__()
, . -
,
. ,
print myBall
__str__() .
Python
, ,
__xxxx__() Python!
. ,
! ,
Python . , -
Python, .
__init__(),
. .
, ,
.
__str__() Python,
print .
:
( __main__
);
(Ball);
, (0x00BB83A0).
178 14
- , ,
__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:
self
self,
. :
def bounce(self):
179
? , ,
? , -
:
warrensBall.bounce(),
, .
cartersBall warrensBall ? self
, .
(instance reference).
! warrensBall.bounce() -
, self. ,
? , Python
.
, .
:
Ball.bo