You are on page 1of 416

Michael Dawson

Python
Programming
for the Absolute Beginner
rd

,"
t

Edition

COURSE TECHNOLOGY
CENGAGE Learning

Australia Brazil Japan Korea Mexico Slngapore Spaln United

lngdom

United States

r.

~n
Mocua -
-- 6
~.

2014

Python. -

.: ,

2014. -

416

.: .

r Pytho. ,

,
.

Python ,

r m.
n ,
, r . m 1)'

Python,

, .
r

Python !

: Couse

Technology .
r
.

, , , :

. , ,
! 1
, .

ISBN 978-1435455009

Couse Technology, part of Cengage Learning


,
,
, 2014

2010

2014

.............................................. 2s

.................................................. 26

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

............................................. 29

1.

2.

, -.

Game Over. . . . . . . . . . . . . . .

...................

30

43

n . , while .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

4.

for, .
................................ 104

s.

6.

. -

7.

. r

8.

r.

................. 134

.................. 165
............. 194

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

9.

r- .
-:

................................

245

10.

.
.............. .211

11. .

12. ,

................308

, .

..........................343
. -

..............................387

livewires .................... 388

...................................... 400

..............................................

25

.................................................. 26

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

............................................. 29

1.

Game Over ............... 30

Game Over . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Python ................................ 31
Python ........................ 31
Python - ............................... 32
Python - - . . . . . . . . . . . . . . . . 32
Python - . . . . . . . . . . . . . . . . . . . . . . . . 32
Python . . . . . . . . . . . . . . . . . . . . . . 33
Python . . . . . . . . . . . . . . . . . . . 33
Python - . . . . . 33
Python Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Python . . . . . . . . . . . . . . 34
IDLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
. . . . . . . . . . . . . . . . 35
. . . . . . . . . . . . . . . . . . 38
Game Over . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
. . . . . . . . . . . . . . . . . . . . . . . 41
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
.................................. 42
........................ 42
.... " ............................................. 42

2.

, -.

.................... 43

................... 43
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Game Over 2.0 .................... 44
.............................. 45
...................... 46
.................. 47
....................... 47
s- . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
...... 48
. . . . . . . . . . . . . . . . . . . . . . . . . 49
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
............................... 51
................ 51
..................................... 52
............................. 52
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
........................................... 53
............... 53
................................. 55
. . . . . . . . . . . . . . . . . . . 55
.............................................. 56
....................... 56
.................................. 56
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
............................ 58
............ 59
input() ............................. 59
................................ 61
........... 61
. . . . . . . . . . 62
.................................... 63

( )

........ 64
65
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
( ) ....... 66
...................... 67
. . . . . . . . . . . . . . . . . . . . . . . 68
. . . . . . . . . . . . . . . . . . . . . 68
................................ 69
. . . . . . . . . . . . . . . . . . . . . . . 69
m . . . . . . . . . . . 69
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
moon_weight sun_weight ............. 70
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
.................................................. 71
...............

. ,

while

.............................. 72

............................... 72
. . . . . . . . . . . . . . . . . . . . . . . . 73
random ................................. 74
randint() . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
randrange() . . . . . . . . . . . . . . . . . . . . . . . . . 75
if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
....................... 75
, if ................... 77
..................................... 77
.................................. 77
. . . . . . . . . . . . . . . . . . 78
................ 79
if else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
/ . . . . . . . . . . . . . . . 79
else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
elif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

......................................... 80
elif . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

10

while. . . . . . . . . . . . . . . . . . . . . . . . . 84
. . . . 84
while ......................... 85
.................. 85
. . . . . . . . . . . . . . . 86
. . . . . . . . . . . . . . 86
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
. . . . . . . . . . 87
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
, . . . . . . . . . . . . . . . 88
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
. . . . . . . . . . . . . . . . . . . . 90
............................ 91
....................... 91
. . . . . . . . . 92
break . . . . . . . . . . . . . . . . . 93
continue .................. 93
break continue . . . . . . . . . . . . . . . 93
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
. . . . . . . . . . . . . . 94
not . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
and . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
..................................... 98
.............................. 98
.......................... 99
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
. . . . . . . . . . . . . . . . . . . . . . . . . 101
random . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
.................................. 101
. . . . . . . . . . . . . . . . . . . . . . . . . . 101
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

11

4.

for, .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

.............................
for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
for .........................
for. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
....................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
, . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

104
105
105
106
107
107
107
108
109
109

. .. . . . . . . .. . . . . . .. . . . . . .. . .. .. . .
..............
len() . . . . . . . . . . . . . . . . . . . . . . . . . . .
in .............................
........................................
..............
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
.............................
..............................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . .
..................................
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
None ..................................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
...................................
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.

109
110
110
111
111
111
112
113
114
115
116
116
117
118
119
119
121
121
122
122
123
123
124
125

12

..........................

......................
. . . . . . . . . . . . . . . . . . . . . . . . .
.................................
2.0 ..............
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
len() . . . . . . . . . . . . . . . . . . .
in . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
.................................
...............................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.........................
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.......................
jume. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.................................................

5.

125
125
126
126
126
127
127
128
128
128
129
129
1

l
11

131
11

132
132
132
132
132
13

133
13

. ................. 134

..............................
.....................................
3.0 . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
len() . . . . . . . . . . . . . . . . . . . .
in . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.....................................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

134
135
136
137
137
137
138
138
138
138

13

...............................
. . . .. . . .. ... . ..
.............................
................................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.....................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
..................................
.................................
..........................
. . . . . . . . . . . . . . . . . . . . . . . . .
..............................
, - . . . . . . . . . . . . . . . . . .
..............................
2.0 ..................
. . . . . . . . . . . . . . . . . .
.........................
.........................
...............................
, ....
............
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
..........................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- . . . . . . . . . . . . . . . . . . . .
- ........................
- .....................
.

139
139
140
140
140
140
141
141
142
142
142
143
143
144
144
144
145
145
146
147
147
148
148
149
149
149
149
152
152
152
153
155
156
156
157
157

14

. . . . .. . . . . . . . . . . . . .. . .
...............................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
...................................
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.....................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.................................................

6.

. -

158
158
159
159
159
162
162
163
163
163
164

. . . . . . . . . . . . . . . . . . 165

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

165
165
167
168
168
169
169
169
170
170
171
172
172
173
174
174
175
175
176
177
177
179
180
180

.........
.....
- . . . . . . . . . . . . . . . . . . . . . .
- ......................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
display_instruct() ..............................
ask_yes_no() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ask_numer() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
pieces(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
new_oard() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
display_oard() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
legal_moves() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
winer() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
human_move() . . . . . . . . . . . . . . . . . . . . . . . . . . . .
computer_move() ..............................
next_turn() ..................................
congrat_winner() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
mai() ................................
..................................
...............................................
.

15
181
181
182
182
184
185
185
185
186
186
186
186
187
188
188
191
191
192
192
192

7. . ............ 194

..............................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
..................
..........................
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3 .....................
..............................
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
3 . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .

194
194
195
197
198
199
200
200
200
201
201
202
203
203
204

16

.................

205
. . . . . . . . . . . . . 206

................................

.....................................
..................
try/except . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
..................
.................................
else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
open_file() ..................................
next_line() ...................................
next_lock() .................................
welcome() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.....................................
.....................................
....................................
.....................................
.........................
..................................
main() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.................................................

8.

207
208
208
208
209
211
212
212
212
213
214
215
215
216
216
216
216
217
217
217
217
217

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

...................... 219
221
, . . . . . . . . . . . . . . . . . . . . . . . . . 221
. . . . . . . . . . . . . . 221
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
. . . . . . . 224

- .....................

17

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
. . . . . . . . . . . . . . . . . . . . . . . . 225
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
. . . . . . . . . . 226
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
............................... 228
. . . . . . . . . . . . . . 229
. . . . . . . 229
............................. 231
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
. . . . . . . . . . . . . . . . . . . . . . . . . . 232
. . . . . . . . . . . . . . . . . . . . . . 232
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
. . . . . . . . . . . . . . . . . . . . . 233
............. 233
. . . . . . . . . . . . . . . . . . . . . . . . . . 234
. . . . . . . . . . . . . . . . . . . . . . . . . . . 234
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
. . . . . . . . . 237
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
. . . . . . . . . 237
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
. . . . . . . . . . . . . . . . . . . . . . . . 240
Critter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
................................................. 244
.

9.

- .
- ................................. 245

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

18

...... 247
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
. . . . . . . . . . . . . . . . . . . . . . . . . . . 249
.................................... 249
. . . . . . . . . . . . . . . . . . 249
card . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Hand ................... 250
- ..................... 251
- Hand . . . . . . . . . . . . . . . . 251
. . . . . . . . . . 252
. . . . . . . . . . . . . . . . 253
2.0 . . . . . . . . . . . . . . . . . . 253
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
. . . . . . . . . . . . . . . . . . 255
. . . . . . . . . . . . . . . . . . . . . . . 255
. . . . . . . . . . . . . . . . . . . . . . . 256
. . . . . . . . . . . . . . . . . . . . . . 258
3.0 . . . . . . . . . . . . . . . . 258
. . . . . . . . . . . . . . . . . . . . . . . . . . . 258
............ 259
. . . . . . . . . . . . . . . . . . . . . . . . . 260
. . . . . . . . . . . . . . . . . . 261
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
. . . . . . . . . . . . . . . . . . 263
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
. . . . . . . . . . . 265
- .............................. 266
cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
............................ 267
. . . . . . . . . . . . . . 268
cards games . . . . . . . . . . . . . . . . . . . . . . . . . . 269
BJ_card. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
J_Deck. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
BJ_Hand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
BJ_Player. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272

19

J_Dealer

.....................................
.....................................
main() ..................................
............................................
J_Game

272
273
275
276

10. .

.............. 211

277
279
280
281
281
282
283
283
283
284
284
284
284
285
285
285
286
286
286
287
287
288
288
288
288
289
289
290
290
290
291

. .. . . .. . . . ..
GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
GUI ....................
tkinter .................................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
, . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
...........
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- 2. . . . . . . . .
tkiter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Application . . . . . . . . . . . . . . . . . . . . . . . . . .
- .....................
, . . . . . . .
Applicatio . . . . . . . . . . . . . . . . . .
. . . . . . . .
...............
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . .

20

..........................

..................................
. Grid ............
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

291
291
291
292
293

Grid . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
: ........
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.....................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
-2 ....................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
............................
. . . . . . . . . . . . . . . . . . . . .
................................
. . . . . . . . . . . . . . . . .
tkinter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- Application . . . . . . . . . . . . . . . . . . . .
create_widgets() Application . . . . . . . . . . . . . . . .
tell_story() Application. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
..............................................

11. .

293
294
295
295
296
296
297
297
297
298
299
300
300
300
301
301
303
303
303
303
304
304
305
306
307

................ 308

.......................
pygame livewires . . . . . . . . . . . . . . . . . . . . . . .
.................................
. . . . . . . .
games .................................

308
308
310
310
311

21

............. 312
......................... 312
............................... 313
.............. 313
........................... 313
.................................. 315
......................... 315
.................................... 315
- ................. 317
....................... 318
................................ 318
........................... 319
...................................... 320
! .......... 320
color .................................. 321
Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
Text . . . . . . . . . . . . . . . . . . . . . . 322
..................................... 323
...................... 323
color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
Message . . . . . . . . . . . . . . . . . . . . . . . . 324
. . . . . . . . . . . . . . . 325
Message . . . . . . . . . . . . . . . . . . . . 325
....................................... 325
. . . . . . . . . . . . . . . 326
. . . . . . . . . . . . . . . . . . . . 327
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
. . . . . . . . . . . . . . . . . . . . . 327
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
update() . . . . . . . . . . . . . . . . . . . . . . . 329
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
........................ 330
........... 330
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
............................ 331
. . . . . . . . . . . . . . . . . . . . . . . . 332

22

... ........ ..
.. . . .. . . . . . .. . . . . . . . . .. .. . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
......................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Pizza . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
main(). . . . . . . . . . . . . . . . . . . . . . . . . . . . .
..........................................

332
332
333
333
333
335
335
335
336
336
336
338
340
341
342

12. ,

, .
. . . . . . . . . . . . . . . . . . . . . . . . . 343

.......................
.......................................
. . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
..........................
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.............
angle ........... , . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.................. , . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
.............................
..........................
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

343
345
345
346
346
347
347
347
349
349
349
350
350
351
352
352
352
353
355
357

23

..........................

357
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
. . . . . . . . . . . . . . . . . . . . . . . . . 358
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
- 1 . . . . . . . . . . . . . . . . . . . . . 359
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Asteroid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
main() ...................................... 361
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
- 2 . . . . . . . . . . . . . . . . . . . . 361
Ship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Ship . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
- 3 . . . . . . . . . . . . . . . . . . . 363
math .................................. 364
Ship . . . . . . . . . . 364
upclate() Ship. . . . . . . . . . . . . . 364
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
- 4 . . . . . . . . . . . . . . . . . . 366
upclate() Ship. . . . . . . . . . . . . . . . . . . 366
Missile ....................................... 367
. . . . . . . . . . . . . . . . . . . . . . . . . 369
- 5 . . . . . . . . . . . . . . . . . . . . . 369
Ship . . . . . . . . . . . . . . . . . . . . . . 370
- Ship . . . . . . . . . . . . . . 370
update() Ship. . . . . . . . . . . . . . . . . . . 370
................................... 371
- 6 .................... 371
upclate() Missile ................. 371
die() Missile . . . . . . . . . . . . . . . . . . 371
update() Ship. . . . . . . . . . . . . . . . . . . 372
die() Ship. . . . . . . . . . . . . . . . . . 373
Asteroid. . . . . . . . . . . . . . . . . . 373
die() Asteroid . . . . . . . . . . . . . . . . . 373
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
- 7 . . . . . . . . . . . . . . . . . . 374
Wrapper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374

..
. . . . . . .
. . . . . . .
. . . . . . . .

.
.
.
.

24

Collider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Asteroid . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Ship . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Missile. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Explosion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
, , . . . . . . . . . . . . . . . . . . . . . . .
- 8 . . . . . . . . . . . . . . . . . . . . .
color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Asteroid. . . . . . . . .
- Asteroid ............
die() Asteroid. . . . . . . . . . . . . . . . . . .
Ship . . . . . . . . . . . . . . . . . . . . . .
- Ship . . . . . . . . . . . . .
update() Ship. . . . . . . . . . . . . . . . . . .
die() Ship. . . . . . . . . . . . . . . . . . . .
main() ......................................
.................................................

. -

.............................. 387

livewires.................... 388

livewires . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
games ......................................
Screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Animation . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . .
Mouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Music. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
games . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
games. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.

375
376
376
377
377
378
378
378
379
383
383
383
384
384
384
385
385
385

388
388
389
390
391
392
393
393
394
394
395
396
399

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400

,
, - .

, r

, .

. ,
.

Uenny Davidson) ,
: .
.

Xoyry (Robert Hoag)


, ,
.

(Pete Shinners) ( Pygame)


LiveWires. ,
Python, r

, .
,

(Mic\1ael Dawson)

, .

, .
-.

U CLA . ,
, : <k ++

(Beginning ++ through Game Programming), <k


Python (Guide to Programming with Python) <kC++:
(++ Projects: Programming lR1ith Text-Based Games).
(www.programgames.com)


: - .
.
, , -

, . ,

, :
?~

, , . ,
,

~.
, ,

. ... ,
.

. ,
, ,
, ,
.

Python

, . ,
,

,
.

,
, . ,
,

, .
. ,

Python -

. ,

Python

.
, .

Python

- . Python,
. ,
,
~.

Python

28

, .

Windo\vs.

Python

, ,

. .
, , ,

: , , ,
- ,

GUI .

. ,
, .

,
. ,
, .

, ,
- www.courseptr.com/downloads.

(),

. ,
, .

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

. .

-------------------------~
,
.

,.

'

. ,

','

'1

." ; . '

1 ".

'

,
, .


, j:i

vinitski@minsk.piter.com

( ~>, ).

!
http://www.piter.com
.

.
Game

Over

, , - .

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

Python.

Python

Python ;
;

Python ,

, .

Game Over,

Game Over

, ,

Game Over.

1.1

, .

1.1 -

. ,

(GUI), ,

Over

< ; ,

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

, .

31

Python

1.1. ,

Game Over -

Hello World,

Hello
World (n, ). Hello World- ,
. , Hello World - ,
.
--

-- - - - - -- - - -- - ----- -- - -- - - - --

- - - - - -- ---- - - - - - - - - - - - - - - - - --- - -

- ---- -- -

. - - - - --

--- - --- - --- - - --- -

- - ---- ---- ------ -- - - - ---- - - --- -

____ j

Python

,
(Guido van Rossum).
1991 . Python ,
,

Python -

, .

Python 42, .

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

,
).

.
Python? .

Python

. , , ,

32

1.

Game Over

- Visual Basic, C#,j ava . - . t .


, , .
. Python
. Python
, .

, Python -
:

Python

, .

Python -

Python ,
. ,

GUI

Python .
: Google, I, Industrial Light + Magic,
Microsoft, NASA, Red Hat, Verizon, Xerox Yahoo!.
Python. Electronic Arts, 2 Games Disney Interactive
Media Group - Python.

Python -

r-

- ()

.
, ,

. , ,
, , , .

C#,java Python - - . Python


. # java -

. ;
- ,
.

Python

: -

. - ,
, .

? .
? .

Python

Python -

Python , , ++ jv.
Python ,

,
(, /++), -

Python.

Python

Python

33

Windows

thn- : Palm
Cray. ,
Python Windows, Macintosh,

Linux -

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

r r

Python

.
Python Python Tutor,
.
:

http://mail.python.org/mailman/listinfo/tutor.
Tutor (~), : ,

Python. , ,

. ,
.

Python -


Python . ,
. , Python,

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

Python

Windows

Python,
. :
Python Windows
.

34

1.

Game Over

1.

Python Windows .
Python Windows - (www.co Python Software

urseptr.com/downloads).

python-3. 1 . ms i.

2. python-3 . 1.msi - Python Windows.


.

3.

1.2.

Python 3.1

~~~~~~~~~~~~~~~~~~~~~~~~

-, n
. , , ,
, .

www.courseptr.com/downloads . .

Python 3.1.1 Setup

Select Destlnatlon Directory

Please select dlrectory for the Pyttn 3.1.1 flles.

CJ Pythonl

python
for
windows

l:\Python31\

1 < Back

1.2. Python

Python

![

Next >

Cancel

Python .
, Windows,
Python http://www.python.org
. Python
.

1.3.

35

IDLE

1' python m

Ac!vancedSearch

Python Programming Language - Official Website

80U

NEWS

proerammlng languag that lets you wort mor


ctulokty and tntegrate u systems more et'fectlvety. You can
leam to use ~on 1nd almoat immedlate taJns ln
productlvltf and lower malntenance costs.

Python runs on wtndows, IJnux/UnD:, OS . and has been


ported tC! trn! Java and .N virtuat machines.

Pyd'lon 11

OOCUMEN N
OOWNLOD

l'lt
COMMUNJV
FOUNDJON

CORE OEYELOPMENT
Help

~Re'"'"'

open source ltcense

lnde

Qulcltllnks~.7.2)

New ro P'ython or choosing etwEen Python 2 and Python

Read

DocumvntaHon
Wlnd~ /rstaller

~on

Soun:1D1'itribution

The F\tf1on So~re Foundatlon holds the intellectual property rights


behlnd Pyttion, underwrites the Pyeon co[lference, and funds other

Q11lck llnb .2 .1)


Docurintation
WindDW1lr1t1ller

SOtJtttDlttrtulion

Python JG:s

2 or ptthon 3

Puhshed

" Pytbon 3,:;1:, 1rc2 released


release cand~ate for Python ~.. 2:1 has

Help Fund Pytt!on

Putshed.Sun,Ju

Python

been released for testrng.


2.1 flnal is scheduled for re\ease on ..k.Jly 10, 2011

1.3.

users uch

RtkSpte,

/ndustnal L!ght

nd

Wathlngton Pott:

Mon, 11 July 2011, 08:00 +0200

Pytfion2 0137
Htlp M1ln1-ln W1.tt1

jl:nlng

" Pytbon 3,g, 1 released


Pytilon ~ 2.1 ha'3 been released.

~~i~M!iiili

Magic, Astrazeneca, Honeywe11,


and many others.

Read more, -or- download Python now

Python Wlld

t-

proJects i1 ttie Python communlty.

Python lllerctiendlse

Pytflon lnsldar Blo!I

(ente PyPI package name}

'----Python 1s free to use, even for commercial products, because of its


osi.pproved

Pack11g1

1wlsh there was Python :iupport Jn I.

Persona/1y, 1hve dlfect


n uslng Python as
prtmary devetopment language
da11yatmyday)oOat

2011 16:00+0200

Python,

~~~~~~~~~~~~~~~~~~~~~~~~~~

Python. ,
Python .

, ,

IDLE

Python
IDLE. ,
. -

. ,
.

IDLE :

Python. Python ,
, , .


. ~

Python 3.1

IDLE (Python GUI).


1.4.

, ,

36

'
Python 3.1.1

(r311:7448,

J.ug 17 2009,

"copyright", "credit3" or

Game Over

l,ol@~

'

17:02:12)

"lice~e()"

1.

for

[JIISC v . 1500 32

nre

it

(Intel)]

on t1in32

information.

> 1

.1.4.

Python.

Python (Python Shell). (>)

pri nt( "Game Over") Enter.

Game Over
,

Python!

. , - ,
.

print

, :

pri nt( "Game Over" ).

, . (

), , .

Python.

-
.

pri nt ( ) , ,

, . ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~~

Python

. ,

. n

PRINT(Game Over)-

print( Game Over)

Print(Game Over)

37

IDLE


, , ,
. ,

, , .

pri nt () -

, , ,

. , pri nt ( "Game Over").


, .
, , .

pri nt () "Game Over". ,

Game Over.
~~~~~~~~~~~~~~~~~~~~~~~~

Python

r ,

. .

2.

"Game Over", print( ), .


, . ,
~ ~ ~
, ,

() . .

"Game Over" - : , .
, , .

- , Python , - .
.

, , ,

Python. ~.

-. ~
. , , :


.
, ,

. , ,

primt( "Game Over" ),

Traceback (most recent call last):


File "<pyshell#O>". line 1. in <module>
primt( "Game Over")
NameError: name 'primt' is not defined
: -?!

NameError: name pri mt' i s not defi ned

38

( :

'primt'

1.

Game Over

).

, pri mt. ,
, . . ,

, , :
.


, , , ( ,

, ) .
,
. , .
,

Python, -

pri nt -

. , , "Game Over"
.
. ,
:


.
, : . ,

, ,
. , IDLE
. , , .

,
, , , , .

w r
,

File () New Window ( ).


1.5.

, .

()

pri nt ( "Game Over")

Enter. ! ,

, .
, .

r
File Save As (
). game_over. ,

, .
~~~~~~~~~~~~~~~~~~~~~~~~

..

IDLE,

Python.

7~

39

IDLE

1<;ol@l;...n...1

Untltied

J;.dl:

Furmat

"'-"'

Qptfon

'!'l)ndows

IJ.elp

~~
.

1.5.

. Pytho

Game Over , Run ~

Run Module (

~ ).
. , .

Pyt.hcn

.1.1

(r11:74'l,

"copyriqht",

.lug 17 2009, 17:02:12)

"cre:dit~"

or

"licee()"

[JISC v.1500

bit (Intel)] on

1n2

for more informe.tion.

>>> print. ( nGame Over")


~

OVer

>>> .,." RE3TART """",,.".,,."." ..... " " "" "."


>
Game OVer

> 1

11
. 1 .6.

Game Over,

IDLE

1.6.

40

1.

Game Over

, 1> . , ,

pri nt ( "Game Over" ),


, - Game Over.
(RESTART), -
: Game Over. :

IDLE,

- , .
- , . , ,
, .
,

. ,

, .

Game Over

Game Over IDLE.


IDLE - .

, ,
,
.

Game Over

, , .
, , , . -

, .
, Game Over

. , , ,
Gamc Over -
. ,
. Game Over, :

Enter.

..

Enter,

.
.
(www.courseptr.com/clownloads ), game_over.

Chapter

1, 1

~~~~~~~~~~~~~~~~~~~~~~~~~~

Windows,

Python

IDLE,
Edit with IDLE (

IDLE).

,
.
. - u.4t. . .

Python,

\Vindows+ R

cmd,

41

Game Over

# Game Over
#

print

, .

, .


. , -
, .
, ,
.

#. (

# ) .
. ,

IDLE

, .
.

, -
.

: ~ ?

, , , - ?~>
,
, , ,
. ,
,
.


r, .

. ,
.
, - ;

, - .
.

, :
, . , ,

.
. ,

pri nt.

42

1.

Game Over

print("Game Over")

pri nt.

, Game Over.


:
input("\n\nHae

Enter.

.")

Enter.

Enter.

. ,

Enter

,
.

, ,
. ,
, , ,

i nput ) .

. ,

Python .
- .
Python ,
, ,

. , ,
. ,

Python .

'

' i

'

A/J,AUU
"'Jfl

'

"

' "l,.

. ,,, !
-.,'r

: .
n ,
.

, ,

Enter . , .
, . ,
.

,
-.

<< >> 1

,
. .
,
, (, , ) .'\f.

.

, :
s-, -

Python;

;
,
;

r r
&
,

1>,
.

2.1.

, ) . Python 2.,
Python 3.1 ,
# coding: 1251 # coding: utf-8. - . .

44

2. , -.

2.1.

, 28-

,
.

,
: , .
, , , , >.>

. .
, ,

"Game Over".

. , ,

.
.


Game Over 2.0 -

Game Over 2.0

Game Over:

, ,
. , .

2.2.

. - (www.courseptr.com/

downloads) Chapter 2;

game_over2. .

45

# Game Over - 2
#

2.2. .. .

pri nt( " 'Game Over' 2. ")


print( " " . "". "")
print( "".
"-".
"")
print("Bo".

end=" " )

pri nt ( " ...")


print(

_I

1 1
1 1

1
11 1 1 _I
1 11
11 1 1 I_
1 / 1_1 1 1 1 _I
11
1 1 1 I_

/ / 1 1
_

/ _

1 l_I 1 / / 1 1
'
/ / 1
l_I / /
/ _ \ l l //
111111 / /
1 1 1 1 1 1/ /
1 l_I 1 1 1/ /
, _ _1 1_1
input("\n\nHae

l_I 1__ 1

1 _11 - \
1 I_ 1 l_I 1
1 _I 1 _ /
1I_1 1 ' '
1_11_1 \_\

Enter.

. ")


:
, ( ' ' ),

2. , -.

46
("") Over".

'Game Over' -

"Game

rint("

'Game Over' 2.0")

. .

2.2.

, , ,

, G. . -
: ,
. , ,

.
: ,
.

. ,
. , , "

'. '

"

. , "

"

". "

, , ,

" ''.

. ,

, , , .

pri nt ( ).

, .
:
printC"Toe".

"".

"")

: " ", "" "".


. ,

. pri nt )
.
, , ,
( ) -.
,
- .
:

pri nt "".
"-".

"")

, .

47

pri nt )

. ,

pri nt ()

. , -, ,

. , ,

pri nt ()

print( ).

. :

end=" ")

print("Bo".

pri nt (" ... ")


... , , . ,

pri nt ( ) .
( ) .

pri nt ()

... ,

?. , ,
end pri nt ( ) : end=" ". pri nt (),


: ,

end, , .

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

6,


, , ,

Game Over

. :

/ _J
/ 1
11
/ /11
11
!_
1 l_J 1 / / 1 1
J

'

1 1 1

11-11 _I

1 11
11 1 1 I_
1 1 1_1 1 1 1 _J
11

J_I 1 1

1 1 1 I_

l_I l __ I

\ 1 1
/ / 1 _11
\
1 1 1 1 1 1 / / 1 I_ 1 J_I 1
1 1 1 1 1 1 / / 1 _I 1
1
1 l_I 1 1 1/ /
1J_1 1 \ \
1_11_1 ,_,
\ _ _ ! I_/
/

. ,
. , ,

48

2. , - .

; ,
.
,
, .

, Game Over 2.0,


ASCll-rpaa . , , , ,
.

ASCll America Stadard Code for lformatio lterchage (

). 128 .

, -

. :

1898 .

L-- -------- - ----- -- --------- --- ------- ----------------- -- ----- - - ---------- ___ _ ____ _ ___ ________ ____________ _________ __J

s-
s- ( )
.

.
s- : (\)
. ,
s-, ,
.

, , ,

~;.

, .

~;.

, s

. .

2.3.

...

2.3.

49

s-nn

. -

Chapter 2;

#
#

(courseptr.com/downloads)

fancy_credits.py.


s-

printC"\t\t\tBoopaaee ")

printC"\t\t\t \\ \\ \\ \\ \\ \\ \\")
print("\t\t\tpapaoa ")
print("\t\t\tMaa ")

print("\t\t\t \\ \\ \\ \\ \\ \\ \\")
rint"\n :")
printC"oey \'\'.
\"\".")

printC"\a")
inputC"\n\nHae

Enter.

.")


~~ ,
.
, s-

\ t.

pri nt( "\ t\ t\ t

\t

")

s-
, , , ,

.
, ,
.


, , , ,

,
s-. :

( ,
\ \ ), :

printC"\t\t\t \\ \\ \\ \\ \\ \\ \\")
printC"\t\t\t \\ \\ \\ \\ \\ \\ \\")


s-

\ n.

50

2. , -.

, , . \n ,
, .
:
print("\nOreoe :")

\ n,

:.


, ( ,

) .
s- \', \".

.
, :
rit(" \'\'.
\"\".")

, .

1. \ '\ ' ''.

2. \' .
3.

\"\" "".

4. \" .


:
!

pri nt ("\")

. s- \
.

-
pri nt()

. ~ , ,
.

\.

s-
, ,

IDLE.

, , . , ,

print( "\").

IDLE,

, .

Windows, ,

, .

, s-, , :

. .
s-.

2.1

51

2.1. s-

\\

. : \

\'
\"

, . :

'

. : "

\t


, , .
,

- .

r r
~ .
.

2.4. ,

.
-

Chapter 2.

#
#

2.4.

(www.courseptr.com/downloads)

si l ly _stri gs. .

rit("

"

'+' . ")

2. , -.

52

print("\na

+
+
+

+ " . " \
- \n" + " -" \
"" + "" + ". " \
" " + " \n" + " . " \
" +

" .

"

" +

""

" +
+ "

""

+" ."+" "+" ? "+" .\n"

"

" +

"

" +

""

!")

print("\nEc . .

,")

rit(" ? . ")
print("pa .

")

rint(":")
rint(""

input("\n\nHae

10)
Enter.

.")


, ,

- ,
-

pri nt:

print("e

" +

"

'+'. ")

+ " " "

'+' . , .

: ,
, .

~ - -
. , , , ""

"", "", " ".


;
.

, :
print("\na

" + " " + "" + " . " \


" + "" + - \n" + " -" \
+"" +"" + " . " \
+ " " + " \n" + " . " \
+

" .

+" ."+" "+" ?" +" .\n"

+" "+" "+""+" !")

,
,

22 .


.
. .

\ (
), .

53

, ( ,
);
.

, ,

. , -
,
.

r
, ,
:

rint(""

* 10)

:
"
"

".

*,

, .

, ;

.
,

* .

, , .

. , -

, -
. , Python
; ,
.

r r r

. -, ,

, .

, . - ,

~

( )

. .
.

2.5,

54

2. , -.

2.5. Python ,

, ,

(www.courseptr.com/

downloads) Chapter 2. word_problems. .


#
#
print("Ec

20

print("o

800

40

.")

?")

Enter.")
20 =". 800 - 40 + 20)

inut(" .

print("800 - 40

print("\nEc .

rint("

")

?")
inut(" .

print("

* 3 =". 6 * 3)

print("\nEc

Enter .")

19

).")

print(" . ?")
inut(" .

Enter . ")

print( "19 / 4 =". 19 / 4)


print("\nEc .

107

. ")

print("pea . ?")
inut(" .

Enter ." )

print("l07 // 4 =" . 107 // 4)


print("\nEc
.")

print("o ?")
inut( " .

print( "107% 4 =" . 107% 4)


input("\n\nHae Enter.

Enter. ")

. ")

107

55


, .

, , , .

Python

, ,

. (int)

( fl oat) . .

1, 27, -100

2,376,

-99,11,0



. , ,

. ,

800 - 40 + 20 40
800 20, 780. ,
800 - 40 + 20 , 780.

, ;

, .

19 /

4 19 4

6*

6 3 18; ,
4. 75.

, , .
:

107 / / 4.

//

, , . // ( )
, ,

( ).
1, ;
.

107 / / 4 26.
107 % 4, , ,

. %
.

107 % 4 3.
2.2 .
6n

2.2.

1
11

()

7+3
7-3
7*3
7/3
7 // 3
7%31

10
4
21
2.3 33333 33333 33335
2
1

( )

-------------------------

8 n. 2.2 , . , 7
3 2.3333333333333335. n, . n
, ,
- .

decimal.

Python.

2. , -.

56

Python

2.6,

<.:.

2.6.

2.6,

. ,
. -

(www.courseptr.com/downloads)

Chapter 2.

greeter. .

#
name = ""
print(name)
rint(".".

name)
Enter.

input("\n\nHae

. ")


-
. ,
- ,
. -

57

. , ,

, , , ,
:

name =

""

name,

- "".

, .
,

name

, ,

1
~~~~~~~~~~~~~~~~~~~~~~~~~~

, ( ) -

, , -
.

Python

. ,
, ,

, , ,

:~>

5.


- .
, .
, , :

printCname)
"", print("Bac").
, :

pri nt (".". name)


". ", , "". name
"".


,
. - name,

person, guy alpha7345690876:


.
; Python
, . , :
.

. ( ) scope

, .

. . .

58

2. , -.

, ;
.

,
. ,
, 4 4

( :

alpha7345690876 -

, , ). , .

. ,

, , , .
, ,

score ,

s.

, . ,
, , , .)
. ,

, .
, ,

hi gh _score hi ghScore?

. , ,

,
.

. -
. , ~, ,

Python, .
,
( Python
).
.

, . ,
, , : persona 1_checki ng_account _

1ance'? , . ,
, , . , ,

15 .
~~~~~~~~~~~~~~~~~~~~~~~~~

, ,


4, , ,

. ,
, 4. ,

, ,

59

, .
, - .

: .
, ,

, . .

2.7.

2.7.

. , ,

.
- ( www.courseptr.com/

downloads) Chapter 2.

persona l _greeter. .

#
#

name = inut(".
print(name)
rint(".". name)
input("\n\nHae Enter.

")

.")

input()

name

i nput (" .

")

, :

name .

60

2. , -.

i nput ( ) .

i nput () , .
, .

input() ". ? ". .

2.7

, i nput ( ) .

, - .

Enter

input() , .

, , name.
, , ,

i nput ( )

, .

, ,
,
.

, : i nput ( )

. i nput ( ) - .
, ; ,

. -
, . ,

i nput ),

". ?

".

, .
i nput ( ) ,
.

,
. ,

name . :

print(name)

rint(".".

name,

name)

".", name.
, ,
.

input("\n\nHae

Enter.

Enter:

.")

i nput () .
, ( )

Enter, ,

. -

, . -

, . ,

Enter,

i nput ( ) ,

. .

61

Python .
- .

. :
.



, , ~.
, ,
- ~ .
: ,

~.

1943 IBM (Thomas Watson).

~
-. (
,

. .)

2.8.

2.8.

downloads)

Chapter 2.

(www.courseptr.com/

quotati on_manipul at i on. .

#
#


# .

quote

1943

IBM

=". ."

rint(" : ")

2. , -.

62

print(quote)
print("\nOa :")

print(quote.upper())
print("\nB :")
print(quote.lower())
print("\nKa :")

pr;nt(quote.title())
print("\nC --

:")

print(quote.replace("y ".

print("\nA
print(quote)

" "))

:")

input("\n\nHae

Enter.

.")

r r

, -
. , , :

print(quote.upper())
, ,

quote,

upper( ). - 4
, . , quote upper ()
, .

, , , :
print("YMAIO. .")

, ,

, .
, , , .
. , .
, , , i nput ( ) ,
,
. , , :

pri nt (upper())
, ", , ,
, , , ,

. . ,
. ,

upper( )

replace( ).

pri nt(quote. l ower())


l ower( ) quote

. .

63

print(quote.title())
quote, ,

, ,

- .

, titl ( ).
:
print(quote.replace("y ".

" ''))

quote

" " " ".

rep 1() 1-: ,


, . .

, .

.
:

print("\nA
print(quote)

:")

. 2.8 , quote . :

. .
, ,

2.3.

2.3.

u()

lower()
swapcase()

,
, :

capitalize(}

, ,

title(}

, ,

strip(}

, (, ,
)

l(old,
new [,max])

, old new.
max


: ,

.
, . ,
.

64

2. , -.


( )
,
.

,
- . , ,

, ,
. ,
, .
.

2.9.

2.9.

, ! ?

, . ,
. ,
, , .
, , ,
, .
(www.courseptr.com/downloads)
trust_fund_bad . py.
# ( )
#
pri nt (

Chapter 2.

. .
.

.
.

. .

65

ent =

inut("

i nput( "

'':

")

jet - input("Apea : ")


gifts = i nput (": ")
food = input("Oe : ")
staff = inut(" (. . .
guu = i nput( " : ")
games = inut(" : ")
total = + ent + jet + gifts + food + staff + guu + games
int("\n :", total)

):

")

input("\n\nHae Ente. .")

, .
: .

2.9.

, .

, . ? ,
.


.
,
, , , , .
.


, ,

, .
,

. , ,
. ?
,

i nput ( )

, ,

. : ,
.

total =

+ ent +

jet + gifts + food + staff +

guu +

games

, !

, , ? , -
,
. ? , ,
!
I:
+ , .
, .
, , , .

nnoxo, ()

? , . .

66

2. , -.


, ~.
,

i nput ( ), .

,
.


( w)
~ ,
.
.

2.1 .

. 2.1.61

300

.
-

Chapter 2 t rus t _fund _good. .

( )
# type conversion

print(

. .
.

. .
.

. .

= inut(" '' :

")

67

= i nt ()
= i nt ( i nput (" '1 : "))
jet = int(input("Apea : "))
gifts = i nt ( i nput (": "))
food = int(input("Oe : "))
staff = int(input("aoae <. . . ): "))
guu = int(input("aa : "))
games = int(input( " : ))
total = + ent + jet + gifts + food + staff + guu + games
int("\n :". total)
ent

input("\n\nHae Ente. .")



. ,
:

car

= inut("

= int(car)

'~:

")

()

.
: i nt () , r,

.
car.

:
ent = i nt( i nput (" : "))
jet = int(input("Apea : "))
gifts = int(input("oap: "))
food = int(input("Oe : "))
staff = int(input("aoae (. . . ): "))
guru = int(input("aa : "))
games = i nt ( i nput (" : ))

, . ,
input() int() -

, , . ,
, ~ , r

~ . i nput () ,

i nt ( ) .
, rent, i nput ()
, .
- ;

i nput ()

int() .
,

i nt () .

ent.
.

2. , -.

68

.
n

2.4.

2.4. ,

float(x)
int(x)

float("lO.O")
int("lO"}

str(x)

str(lO)

10.

10
'10'

. , , ,
.

food, :

food = food * 52

food, 52 ,
food. , :

food *= 52

food

*=

52

food,

.
, ,

- .

2.5.

2.5.

*=

x=x*S

/=
%=

/= 5

+=
-=

*= 5

%=

= / 5
= % 5

x=x+S

+= 5
5

-=

=-5



, ,
~

, .

downloads) Chapter 2.

usel ess_trivia ..

(www.courseptr.com/

69

01


,
. , ,
:

/
# / . . .

-------------------------

8 ,

. . (:1-j

i nput ()

name = input( ". ? ")


age = inut(" ? ")
age = int(age)
weight = int(input("Xopoo. .
,

?"))

i nput () . age wei ght

, .
age :
, i nput ( ),
.

weight

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

name

name -

print("\nEc . :

name. l ower ())


print("A

"

". name.upper())

- , , -,
. ,

, , .
, , , ,
4~ .

2. , -.

70

called

name * 5

print{"\nEc ".)
print("o :")

print(called)
11 ed
name. called.

seconds = age * 365 * 24 * 60 * 60


- ", seconds.

print{"\nTo

365 , 24 ,

".")

60 , 60

age 365 * 24 * 60 * 60.

seconds,

moon_weight sun_weight

1 :

moon_weight = weight / 6
moon_weight.

print("\naee . ".

sun weight

weight * 27.1

"?")

print( " . ", sun_weight. ". (. .


".)")

, ,
.

moon_wei ght , 1/6


weight. 27,1
, sun_weight , weight * 27 .1.

Enter,

i nput( "\n\n Enter.

.")

, ,

, , ,
.

. .

71

, ,
. s

. , .

: ,
. , ,
.
, .
, , , ,
.

: . ,
.

11

, .

r ,
. : 15

20 % .

,
. : , ,
, .
, .
.

,
while
.

<< >>

. ,
, , .
,

- . :

if

ra nd i nt ) ra nd ra nge );

l se ;

l i f,
;

whi l

:;

. ,

, :

1 100,

. ,

: ,
. ,
. .

3.1.


. -

:

73

, , , . .

, ( ) ,

Python

3.1.

~~~~~~~~~~~~~~~~~~~~~~~~~~

Python

, , , . (
) . , , http://

www.fourmilab.ch/hotblts/.

. ,

, , .

: , , .
, .
.

3.2.

downloads)

Chapter

(www.courseptr.com/

craps_rol 1er . .

#
#
import random
# 1 - 6
diel = random.randint(l. 6)
die2 = random.randrange() + 1
total = diel + die2
print("p " . diel. "". die2.
input("\n\nHae Enter. . ")

".

".

total)

74

. ,

3.2. !

while

7 :

random

import. ,
random:

import random

, ,

. ,
. ,

random ,

,
, . ,

random.

randint()

random randi nt( ),


randint() :

random.randint(l. 6)
,

random.

randi nt()

: _. _ .
. ,
. : ,

75

if

, . random.
,

randi nt )

randi nt )
random.

.1
.

randi nt()

, . , ,

1 6,
.

random

1, 2, 3, 4, 5 6.

randrange()

randrange( ),

. randrange( ),

. :
() ( ).

drange() , 1, 2,

3, 4

5.

6? ,

random. n -

randrange()

, .

, di 2 ,

1
die2

random. randrange() + 1

die2

1, 2, 3, 4, 5

6.

~~~~~~~~~~~~~~~~~~~~~~~~~

: randlt() randrange(),
.
, .

if

. i f
,
, , .

r
~ i f ,
.
, .

3.3 3.4.

Chapter

password. .

(www.courseptr.com/downloads)

76

3.

3.3. -,

while

3.4. ,

secret? ..

if

print('opo " ". ')

print('-- -
password = inut(" : ")
i f password == "secret":

\n')

print( " ocy ")

input(" \ n \ nHae

Enter .

. ")

---.------~

: :

.1

---

. , , secret.
. , . , ,
. -

. .

77

if

if

>.> :

if

password == "secret":
print("ocyn ")

. , ,

password "secret ",

.
, ,

"secret",

i f,

n
i

f , ,

. , , ,

: ,
. , : >.>,

, , .

Python -: True - ,
F l se, , - .
. , >.> ,

password == "secret ". ,


"secret ". password "secret ",
- True, - Fa l se.

password -

i f, -


,
t .

>.>: >.>, ==.


~~~~~~~~~~~~~~~~~~~~~~~~~~

. ,

,
. password
secret - ,
password secret. password
secret - ,

True

False.

==

-.

>.>, .
.

3.1.

3.1.

--

!=

5 == 5
8 != 5

True
True
,

78

. ,

3.1

while

()

>
<
>=
<=

3 > 10
5<8
5 >= 10
5 <= 5

False
True
False
True

~~~~~~~~~~~~~~~~~~~~~~~~~

,
, . , ;
fr -~ . , ,

True,

<

( ).

Pytho . ,
, r <,<=,> >=.
, . 10 > .
, ,

l.!J- .


, i

pri nt ("

")

f,

,.

. ,
. ,

i f.

( ), ,

. ~:~.

pri nt( "

").

,
,

. :

if password == "secret":
print("ocy ")

print("opo !

. . .")

,
! . . "

,
.
~~~~~~~~~~~~~~~~~~~~~~~~

Python , .JI
( , ). ,
. . -, :
, . -,
. , n

if

79

else

r r
.
,
.

f,

, , , .
, .
, ,
.

if else

, , :
- ,

- .

1se i

f.

r /
, , ,

, .

el se.

, , ( . . 3.4 ).
.

3.5.

3.5.


n>

granted_or_denied. .

Chapter ;

80

3.

while

# /
#

else
pri nt (' "
print('-- - \n')
password = input( " : ")
if password == "secret":
pri nt ( " ")
else:

".

')

print("ocy ")
input("\n\nHae

Enter.

.")

else

: i

l se:

if password == "secret":
pri nt ( " " )
else:
print("ocy ")

password

"secret",

, . (
else) .
i f l se

:
,

,
1se.

l se i f : l se,
. l se ,

if

if

l se

. .

elif

,
f. ,

l i

1970-

-, ! -

(Mood Ring).

. .

, .
.

3.6 ,

, .

3.6. ,

81

elif

, . ,

,
.
,

i f

l i f , r . (

, .
,
. )
-

Chapter ;

(www.courseptr.com/downloads)

mood_computer . .


# elif

import random
print(" . .")
print("a.

mood = random.randint(l. 3)
if mood == 1:
#
pri nt( \
1
1

<

1
1
1.
1

'

... '
""")

...")

82

. ,

while

elif mood == 2:
#
print( \

<

11 "tl)

elif mood == 3:

print( \

1
1

<

1
1
1
1

'

11 11)

else:
print("He ! (
pri nt (" ... . ")
input("\n\nPress the enter key to exit.")

. .)")

elif

, 1i

f,

, .
:

if mood ==

elif mood == 1:
elif mood == 2:

1i f (

i f,
else if). 1i f

, :
mood . ,

mood

. . ,

, ,

mood

83

elif

. , , ,

, , ,

mood .

.
~~~~~~~~~~~~~~~~~~~~~~~~~

if elif

,
. , ,
. , mood
, .
,
.
.

mood ,
l se :
! ( . .).

mood

1, 2 3,

. : ls-
.
~~~~~~~~~~~~~~~~~~~~~~~~~

else

: ,

. , - ,

else

, ,
.

3.2.
.&

3.2.

if <>:

. <> ,
<> , -

<>

if <>:
< 1>

<

else. <>
1>, - < 2>

else:
< 2>
if < 1>:
< 1>
elif < 2>:
< 2>

".

elif < N>:


< N>
else:
< N+l>

elif else . m
, . n
True, m

etse

84

3.

while

while

.
: ,
. , :

- , - , ,
, .

, , -:
, .

, .

whi l .

r

,
. , ,
, , ,
,

. ,
. whi l

. , .

3.7.

3. 7.

- ,

, : ?

- (courseptr.com/downloads) Chapter

three_year-old.py.

3.

85

01 while


# while

print("\topo ' '\n")


rint(" .")
rint(" .\n")

response = ""
while response !=" .":
response = input("oey?\n")
print("A. .")
input("\n\nHae Enter. .")

while

while response
response =

!=" .":
input("oey?\n")

whi l , .
- i f.
,

if

whi l ,

. ( ,

-
) , , whi l
, ,

. .

: response =
i nput ("?\ n" ). ,
" .", - .

response ! =

" ." ,

print( ".

.").

whi l

, :

. ,
, .

- response. ,
" ,

, " .

.
. ,
. :

response = ""
~~~~~~~~~~~~~~~~~~~~~~~~~~

,
, .

86

. ,

while


- . , response "".
response , "",
, .


, whi l .
. , ,
, :

response = " ."


while response != " .":
response = input("oey?\n")

response

" ."

, .

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

, -
..

counter =
while counter <= 10
print(counter)
, ,
1. , , .

counter . :
( ) .
.



, . .

, - : .
, ?

87


!>

. , ~.:
, . .
. ?
-

Chapter ;

losing_battle-bad.py.

print("Baeo .")
rint(" .")

rint(" .
.\n")

health = 10
trolls =
damage = 3
while health != :
trolls += 1
health -= damage
rint(" .

"\

damage. " . \n")


" . trol l s. ".")

" ".

print( "
print("Ho ! . ")
input("\n\nHae Enter . . ")

, .

3.8. ,

3.8. ,
Qrl+C.

88

. ,

while

r
, . ,
.
, , :
.

, ,
, .

, .

health

trol 1s

damage

health !=

whi 1

health
10

trolls

damage
3

health !=
True

(True),

. , ,
:

health
10

trolls

damage
3

health
10

trolls

7
4
1
-2
-5
-7

1
2
3
4

5
6

damage
3
3
3
3
3
3
3

hea lth ! =
True
True
-

health ! =
True
True
True
True
True
True
True

, . ,

hea 1th

), - . , ,

health ,

,
. .

,
, , whi l
, , .
. ,

89

~ ~ .
:

while health >

- Chapter 3;

l os i ng_batt l e-good. . , hea l th

, .

, :

health
10
7
4
l
-2

trolls

damage
3
3
3
3

1
2
3
4

health
True
True
True
True
False

>

.
.

3.9.

3.9.

, . ,

, ,

35 + 2,
37. , 37 ? Python

. ,

.
,

""

2749, 8. 6, "",
(True) (Fa l se ).

, :

True Fa l se

. ,

90

3.

while


,
. ~.>
, .

. - ,
. .

3.1 .

3.10 3.11 .

3.11. !

, , , : -
. ,

. -

91

(
-

#
#

Chapter ;

- ).
(www.courseptr.com/downloads)

ma i t re_d. .

print("opo --!")

print("Kaec. .\n")

money = int(input("Coo
if money:
pri nt (" .
.

?
.

"))

.")

el se:
rint(". .
input("\n\nHae

Enter.

.")

.")

i f money:
, money :
money . ,

- . ,

if

money !=

, .
. 4

, - ,

. : ,

. , ,

"" ,

- . ,
/ - . ,

.
, , ,

. :
, , ,


4
, .
, ?

92

. ,

while

. ~.> ,
,

- , ,
. , >.> .
.

r

~.>

1 1

~.> . ,

. ,

3.12.

3.12. 5

cotinue,

break

fi ni cky _counter . .

break

continue

count =
while True:
count += 1
# .
if count > 10 :

count

break
#

5
count == 5:
continue
pri nt (count)

if

input("\n \ nHae

Enter.

.")

10

Chapter ;

93

break

while True:
, ,
- .
:

# . count 10
if count > 10:

break

count

11. -

1,

break ( "

) .

continue

count

# 5
if count == 5:
continue

cont i nue ,

, , ,
. , count

5, , pri nt ( count),

. .

break continue

break continue

. . ,
, ,

break

continue;

. break conti nue, -, :


, , .

Python

. ,

, ~>
.


.1 ,
. ~~ .

94

. ,

while

,
. ~m61-l .

,
.


.
~

.
( , ?).
,
() .
,

~.

, .

, ,

. , ,
.
.

3.13-3.15.

3.13.

3.14.

95

3.15.

Chapter

us i ve_network . .

#
#

rint("\t ")
print("\too !\n")

securi ty =
username = ""
while not username :
username = inut(" : ")
password = ""
while not password :
password = input("apo: ")
if username == "M .Dawson" and password == "secret" :
rint(". . ")

security = 5
elif username == "S.Meier" and password == "civilization":
rint(". .")

security = 3
elif username == "S.Miyamoto" and password == "mariobros" :
print("oporo . .")

security = 3
elif username == "W.Wright" and password == "thesims":
print("Ka . ?")

security = 3
l if username == "guest" or password == "guest":
print("opo .")

security = 1
else:
pri nt( "
. \n")
input("\n\nHae

Enter.

.")

96

3.

while


n , n r .
n n -n (). -

n , .
, nn n

n.

not

, -
,

Enter ( )

. ,
, - :

username = ""
while not username:
username = i nput (": ")
, whi 1,

not

not.

(~).

not,
. Python not -
,
. ,
,

not username
username , not username , username

. :

username
True
False

not username
False
True

username

~.

not username

. username
.

username

Enter,

Enter,

, , .

not
username . ,
.

- ,

username

, not username, ,

- .

, .

password.

and

, ,
. , , , S. Mei er
ci vi 1i zat i on . , . -

97

, apS.Meier mariobros,M. Dawson civi 1ization civi 1ization

S. Mei er.

ci vi 1i zat i on

S. Mei er

, :

elif username -- "S.Meier" and password -- "civilization":


.
- , , username -- "S .Mei er" password =- "ci vi l i zation".
, ; ,

and.

usrnm

== "S.Meier" and password == "civilization",

and , ,

, . :
,

password

==

"civilization".

username -= "S. Mei er"

username == "S.Meier" password == "civilization" username == "S.Meier" and password


"ci vi 1i zat i on"
True
True
True
True
False
False
False
True
False
Fal se
False
False

-=

-----------------------

and ,
, r , r r.

S.Meier, - civi 1ization,

.
.
.

i f-e 1if-e1 se

- ~. ,
,
.

, ,
, .

or

, .
,

guest

. , :

elif username == "guest" or password == "guest":


print("opo .")

security = 1

98

3.

while

lifusrnm == "guest" or password ==


"guest" ,

. ,

or.

or

, .

or

or

~>; , .

username == "guest", password == "guest",


username == "guest" or password == "guest"

. .
:

username == "guest" password


"guest"
True
True
False
True
False
True
False
False

"guest"

username == "guest" or password ==

True
True
True
False


.
~> - ,
. , ,
, ( )

.
- , !
, 12
. ,
.

. ,
;
, .
. .

.

r
1 ,

, - .

, ,
.

99

. ,

. , , ~

, , , .

~. :

10000

$100

:
, .

,
.

( ) . ,

, .
Python: i f 1se,
.


, , ,
. ~,
. ,

, .
- .
,
.
, ,
~ .

~ ~:

. .?

,
. :

, .

. , while . r

100

- , .
, ,
.


40 ~ ,

. , ,

Python,

, /
.


, :

. -, ,
: . -,
, ,

.
------------------------

n r

r.

, r ,
.

100

101

r n

. ,

,
-

Chapter

Python.

guess_my_number.py.


, :

#
#
#

100

# . .

# /.
#

. .

random

random:
import random


,
:

print( "\t

' '!")

print("\n

100.")

rint(" .\n")

the_number = random.randint(l. 100)


guess = int(input("Bae : "))
tries = 1

the_number , .

random. randi nt( ).

1." 100,

i nput()
, i nt ( )
. gL.ess. ,
tri es, .

1.

102

. , while . ~


. ,
, . ( guess)

(the_number).

, ,

while guess != the_number:


if guess > the_number:
pri nt( "".")
else:
print( "."")
guess = i nt ( i nput ("
tries += 1

"))

guess != the_number,

guess the_number,

, ,

. :
print("Ba ! ".
print("B

the_number)
", tries. " !\n")

,
.


,
inut("\\n

Enter.

Enter:

.")

, . ,
,

if ( if-el se if-el if-el se),


.

whi 1 -

, , ,
. ,

,
.

103

- ,

- . - -:

, .

, 100 ,
,

,
. n ( ),
.

. , 1 100
, . , ,
. ,
Pytho.

for,

.
<<>>

, , .

,
, .

.
,

,
.
, :

for

range() ;

;
;

;
.


~, .

4.1,

, .

, (
, , ).
,
.
.

4.1.

105

for

. ,

for

whi l . ,
- . for
, . for . , ,
, , .
for
, .
.

. for,

. , .



. .

4.2.

loopy_string.py.

#
#
word =

(courseptr.com/downloads)

inut(" :

for

")

print("\nBo :")

for letter in word :


pri nt ( l etter)
input("\n\nHae

Enter.

. ")

for.

Chapter 4.

106

4.

f, .

4.2. for

, ,

for

for,

for letter in word:


pri nt ( l etter)
,

for,

. .
.

, .
"" .

"",

"" . .

for

"" .

for

,
.

1etter;

"" .
.
.

, ,
, .

, , . , ,
1etter ,

" ".

pri nt

L .

1etter -

"". ,

, "".

107

for.

, , . -
. .
, Pytho for ,
.

for

for, ,
for, ,
, i n,
.

, , , . .

for

for

range( )


~>.> .
range()

, ,

for ,
. , . 4.3.

4.3.

rage()

for

108

4. for,

downloads)

Chapter 4.

(courseptr.com/

counter. .

#
#

range(J

pri nt( ":")


for i in rangeOOJ:
pri t ( i . end=" " )
rint("\n\n :")

for i in range(O. 50. 5):


print(i. end=" ")
print("\n\nocae :")

for i in range(lO. . -1):


print(i. end=" ")
input("\n\nHae Enter.

.\n")

- r t

i, j, k.

, . ,
, , , i, j k-

for i 'n rangeOO):


pr'nt(i. end=" ")
for , 4'
. , ,
. , ,

range( ). , range()
range()

, (
). , ,

range( 10) [0. 1.

2. 3. 4. 5. 6. 7. 8.

9].,.

, ;

1, , . . ,
i 9, .
~~~~~~~~~~~~~--~-~--~-~-~--

range() ,

r . ,
, , . ,
.
range(), http://www.python.org.

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

. , ,

5.

n: n

109

,
, :

for i in range(O. 50. 5):


print(i. end=" ")

range()

, .

,
. , [.

20. 25. 30. 35. 40. 45].

5. 10. 15.

45, 50 - ( ).
50-,
, , :

range(O. 51. 5).

for i in range(lO, . -1):


print(i. end=" ")

range() , -1.

, , -1,
, 1. ,
rng(),[l.

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

1].

~~~~~~~~~~~~~~~~~~~~~~~~~

for

, n, n - ,

for,

n-. n,

!. , :

for _ in rangeClOJ:
rint("! ")


nr:
r
,

.
, ,

Python

. ,
, , , ,

110

4.

for,

. ,

<;>.

.
.

4.4.

4.4. len() in -

downloads)

Chapter 4.

( courseptr.com/

message_ana lyzer. .

len() in
message = inut(" : ")
pri nt ( "\n :". l en(message))
pri nt( "\n . ' . ")
if "" in message:
rint(" .")

else :
print("e .")
input("\n\nHae

Enter.

.")

len()

,
. :
print("\na :" .

l en ( ) -

len(message))

. .

111

. !, , (

), 1.

in

,
:

if

""

in rnessage:

rint(" .")

el se:
print("e .")

if : "" in message. ,
mes sage, " ", , -

. . ! , , Ti.>.
,

" i n message

"... ". , ,
!, ,
... ".

. i n , ,
- .
, ,

i n - ,

, , .

for

. , ,
, ,
, , ,

. ,
, ?
.
.
( ), .
.

r
~.>
, .

112

4.

for,

- "",
, .
.
.

4.5.

4.5.

downloads)

#
#

Chapter 4.

(courseptr.com/

random_access. .

import random
word = ""
pri nt (" word : " word . "\n")
high = len(word)
low = - len(word)
for i i n range(lO):
position = random.randrange(low . high)
pri nt ( "word[". posi ti on. "J\ t". word[posit i on])
input("\n\nHae Enter. .")

word

""

. ,
( , ),

>.> -

( -

113

).

~"

1;

~"

2 . .

. ,

word , word[ ].
: .
:

> word = ""


>>> print(word[OJ)

>>> print(word[lJ)

>>> print(word[2])

>>>

print(word[J)

>>> print(word[4])

>>> print(word[5J)

~~~~~~~~~~~~~~~~~~~~~~~~~-

, , n

- . . ,
. 5,
. :

> word = ""


>>> print(word[])
Traceback (most recent cal l last):
File "<pyshell#l>". line 1. in <module>
print word[J
IndexError: string index out of range
, . :

1.


, ,

.
:
.

. , , ,

, ,
. , ,
"":

> word = ""


>>> print(word[-1])

114
>>>

4.

for,

. r

print(word[-2])

>>>

print(word[-3])

>

pri nt (word[ -4])

>>>

print(word[-5])

>>>

print(word[-6])

word[-1] -

~.>,

-2 -

-3 -

-1

ci.>.

. .

.
.

4.6 ,

"".

-6
.

-5

4.6.

-4

-3

-2

-1

r
~.>. ""
- , .

random:

import random
,
, .

:
( ,

random. randrange()

-6 5
word). ,

. ,
:

high = len(word)
low = -len(word)

high 6, ~~.>
l ow ~~.>, -6.

, .

115

-6 5.

random. randrange() . ,
( )
( ). , , :

posi ti on = random. randrange( 1ow. hi gh)


position -6, -5, -4, -3, -2, -1,

1, 2, 3, 4 5.

, ,
"".
, , .
,
:

for i i n range(lO):
position = random.randrange(low. high)
print("word[". position. "J\t". word[position])


, :
. ,

- ,

. , ,

"Game Over ! " ,


. .
, , , . ,
- :
name = ""
print(name)

>
>

na'fle = ""
print(name)

>>>
>

. ,
"", "".

, , ,
. ""

name.

, ,

name. -

"",

, , , . ,
, .

4.7.


r. ,
, , ,
.

116

4.

oame

)(

for,

4.7. name ,
- .

, .
. , ,

, . , ,
:

> word="rpa"
> word[l]=""
Traceback (most recent call last):
File "<pyshell#l>". line l. in <module>
word[l]=""

TypeError: 'str' object does not support item assignment


, , "" "" (

, ).
~ ~. ""

- word[l].

. ,
(

). ,
, .


+, .
, .

, , , ,
.

.
, . 4.8.

117

. 4.8.

for ,
- ,

. ,
, , - .
-

Chapter 4.

(courseptr.com/downloads)

no_vowe l s. .

#.

for

message = i nput (" : ")


new_message = '"'
VOWELS = "iu"
print()
for letter in message:
if letter.lower() not in VOWELS :
new_message += letter
pri nt (" : ". new_message)
print("\nBo :".
input("\n\nHae

Enter.

new_message)

.")

VOWELS

new_message , :

"iu"

VOWELS .

, ,

,
, .
, .

118

4.

for,

, (
).
. -,

. , ,
, "aei u", VOWELS.
, , ,

, , , -
. -,

- , .
,
, .
,
.

~~~~~~~~~~~~~~~-----------------------

, , .
( r )

, Python, , .
. , ,
, .


. r.

'

Python, ,

.
---- - - .. - .. --- -- ----- - - - -- ----- -- - -- ----- ---------------- - - --------------- - - - -

--- ------ -. - ------- ..]


.
, .

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

. , ~~ :

for letter in message:


if letter.lower() not in VOWELS:
new_message += letter
r'nt(" :",

new_message)

, ,
.
-, Python .
, ""

, " ".

VOWELS

, , -

119

, i n
.

letter. lowerC ).

~~~~~~~~~~~~~~~~~~~~~~~~~~

, , ,

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

. , :

winner, ,

; .

name.lower()

==

winner.lower()

name wi nner

, . ,
"" "" . "" "",
"" "".

-, , , ,

+= - . ,
. :

new_message

letter

+=

, :

new_message

new_message + letter

r
, ,
.
.

. , ,
, - .
- .


~ "" .

. ,

, .
.

4.9.

120

4 .9.

4.

for,

, ,
, .

downloads)

#
#
word = ""
print(

Chapter 4.

(courseptr.com/

pizza_sl icer . .

+---+-- - +---+---+ - --+


1 1 1 1 1 1
+---+---+- - -+ -- - + - --+

-5

-4

-3

-2

-1

rint("

''.

.")

print("

start = None
while start !=

Enter.

. ")

121

start = (inut("\n : "))


if start:
start = int(start)
finish = int(input("Koea : "))
print("Cpe word[". start. ":". finish. "]
print(word[start:finish])
input("\n\nHae Enter. .")

".

end=" ")

None

,
, , :

start

None

sta rt None.

Python , .
None (False).

. start
whi l .


,
- , :
. ,

. .

4.10

"". ,
, .

-5
.

-4

-3

-2

4.6.

-1

4.10. .
/

,
. , ,
:

>>>
>>>

word = ""
printCword[0:5J)

>>> print(word[l:J)

122

4.

f, .

> print(word[-4:-2])

>>> print(word[-4:3])

word[O: 5) ,
.

word[ 1: 3)

" ", .

, . ,

word[-4: -2)

"",

word[l :3),


. .

, , .
,

word[-4:3)

"".

~~~~~~~~~~~~~~~~~~~~~~~~~

, ,
, - word[2:1], Python ,
. ,
. , , , , .


4 ~
, ,
:

printC"Cpe

word[". start. ":". finish.

"] ",

end=" ")

:" ,

sta rt

fi ni sh:

printCword[start:finishJ)


- .
, . ,

;
. , , word "",

word[ :4]

word[0:4J.

, .
word [2: ]

, word[2: 5].

, ,
.

word [ : J -

word [: 5].

> word = ""


>>>print(word[0:4J)

123
>>>printcword[:4J)
nuu

>>>printcword[2:5J)

>>>print(word[2:J)

>>>print(word[0:5J)

>>> print(word[:J)

------------------------
,

[:] -

. , ,

.
.


, , .
, ,

. 1 1, , 11
.

.
, ,
. , .

- ,
:r ( , ).

, , ,
.

<<

RPG. ,

. , ,

( , ?). ,
, .

, .

, - .
.

4.11.

- ( courseptr.com/dow

loads)

Chapter 4.

#
#
#

hero's_inventory. .

124

i nventory
#

4.

for,

()

i f not i nventory:
pri nt ( " . " )
input("\nHae Enter. .")
#
i nventory = ("" .
"".
"" .

" ")

pri nt ( "\ n : ")


pri nt (i nventory)
#
print("\na.

:")

for item in inventory:


pri nt ( i tem)
input( "\ n\nHae Enter .

. ")

4.11.

, ,

r
,
, .

, .

, ,
:

i nventory

= ()

:
.

i nventory

125


, , ,

Python

. .
~ :

if not inventory:

pri nt ( "

")

i nventory

(F l se }, ,

(True).

Fal se;

not i nventory . ,
" . ".

enycroro
.
-,

. i

i nventory

= (""

nventory:

"".

"".
" ")

. ,

"", - "", - "", , ,


"u ".

, , .
, ( );

Python

.
~~~~~~~~~~~~~~~~~~~~~~~~~~~

, , .
, , : .

, - ,

.
. ,
,

- .

n
,

, -
, . :

126

4.

for,

printC"\nCoepoe :")

pri nt i nventory)
, .

for, , i nventory,

print("\na.

:")

for item in inventory:


print(item)
i

nventory .

; ,

.
,
(),
. , , ,

.
~~~~~~~~~~~~~~~~~~~~~~~~~

, .

. ,
. , ,
. , , ,
,

Python.

. ,

, .
,

, i

for,

n, -

. , , .

2.0

.
;

. ,

.
. .

4.12.

,
, .
- (courseptr.com/downloads) Chapter 4.

hero's_inventory2.py.

127

4.12.

, , ,

r
,
~. ,
:

# 2.0
#
#

i nventory

= (""

for

"" .
"".

" ")
print("\na .

: ")

for item in inventory:


pri nt ( i tem)
i nput("\nHae Enter.

.")

len()

1en ( ) , :

, .
. , ,
.

1en ()

print("Ceac " .
i nput( "\ nHae

Enter.

len(inventory) .

.")

"/-.")

128

4.

for,

r .

("", "", "" "


"),

/-.

~~~~~~~~~~~~~~~~~~~~~~~~~~

, r

inventory

, .

in

( ),

i . , . ,
, :

#
if


" "

pri ntC "

in

in inventory:

.")

" "

in inventory , "
i nventory. ,

"


.
- , .

(),
:

index = int(input("\nBee
print( " ". index.

" ".

4.13.

""

""

-4

-3

"))
inventory[index])

4.13.

"" " "

-1

-2


.
. , ,
.

129

~ , ,


. :

start = int(input{"\nBee : "))


finish = int(input("Bee : "))
print("Cpe inventory[", start. ":". finish. "] - ". end=" ")
print(inventory[start:finishJ)
input("\nHae Enter. .")
.

4.14 ,

"" ""

-4

-3

"" " "

-2

-1

. 4.14. , ,

r
, .
:

> inventory =(".


>>> print(inventory)
(''.

''.

"".

''.

"".

" ")

' ')

> inventory[OJ = " "


Traceback Cmost recent call last):
File "<pyshell#>". line 1. in <module>
inventory[OJ = " "
TypeError: object doesn't support item assignment
, .


, .

chest =

("".

" ")

print("B .

print(chest)

:")

+:

130

pri nt "
inventory += chest

4.

for,

.")

printC"Teep :")

pri nt i nventory)
input("\n\nHae

Enter.

.")

, ,

chest,
chest ,
. +=
i nventory chest, - inventory. ,
inventory, , , ,

: "" " ".

. ,

inventory

chest

i nventory.

r r
, ,

~~. ,
. - ( oourseptr.oom/downloads)

Chapter 4. word_jumb 1. .

# r CWord
#
#
#

random:

Jumle)

-
r -

import random
, . ,
WORDS :
.

# .

WORDS

=("".

"".

"".

"",

"",

"")

, WORDS ,

random.choice( ):

word = random.choiceCWORDS)
, .
- .
, word.
, . ,

word

correct. , ,
:

131

# .
correct = word

r
-
, .

, .
,
(, ,

). ,
:

. , ,
, . , .

-r~1,
, (
) .

r r
:

~ .

jume

='"'

umb l .

,
.

wh i l .

, ,

while word:
,
,

word .

word.

word

132

4.

for,

n
,
:

position

random.randrange(len(word))

word[pos i t i on] , ~
~

word

umb 1.

jume
jume.

Jume +=

word[position].

word[position]

word

word

word[:position]

word[(position

l):J

word,
position. word
. - word [ : pos i t i on] - word [ pos i t i ],
. cpe-word[Cposition + 1): J - oword[position],

, .

word,

word[pos iti onJ.



,

, ,

#
pri nt

''!
. .
(

Enter.

printC"Bo :".

.)

jumle)


.
,

Enter:

133

guess = inut("\n : ")


while guess != correct and guess != "":
print("K . .")
guess = inut(" : ")
n

, . :

i f guess == correct:
print("a. !

!\n")


:
print("Cnaco .")
input("\n\nHae

Enter.

.")

. ,

range( ),

. ,

,
.

for,

- .
. , ,
, ,

. ,

, ~~.

'

r, .
, .

r,
.

, r .
, .
, r, , , .

, - , .
, , t t, t - ,
t

Her. .

.
<<>>

. - , ,

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

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

;
,
;

;
;

, ~..

- ,
, . ,
, .
,

. .

5.1-5.3 .
. ,
, .
, ,
.

135

5.1. . .. .

5.2.


, ,

. .

.
, , - . ,
, , ,
.

136

5.3.

5.

3.0

2.0:,

4.
, . 3.0 ,

. ;
, . .

5.4


. .

5.4.

5.5.

2.0,

137

5.5.

, ,

i nventory;

2.0

, , , .
-

Chapter 5.

(courseptr.com/downloads)

# 3.0
#
#

inventory

= ["".

print("\na.

hero' s _i nventory. .

"".

"".

for

" "]

:")

for item in inventory:


pri nt ( item)
i nput ( "\n Enter.

.")

len()


l en() , .

#
pri nt (" ". l en( i nventory).
i nput ( "\n Enter. .")

in

"/ -.

2.0.

")

. i n
.

138
#
if


" "

5.

in

i n i nventory:

print("B .")

2.0. ,

, ,
.

#
index = int(input("\nBee : "))
pri nt (" ". i ndex. " ". i nventory[indexJ)


, ,
?

#
start = int(input("\nBee : "))
finish = int(inputC"Bee : "))
print("Cpe inventory['', start. ":". finish. "] - ", end=" ")
print(inventory[start:finishJ)
input("\nHae Enter. .")

chest , .

, ,
.

#
chest = ["". "

"]

printC"B . :")

printCchest)
printC"B .")

inventory += chest
pri nt " : ")
pri nt ( i nventory)
input("\n\nHae Enter. .")


, ,
, , . ,

139

. , :. :
. ,
, .


,
:

print("B .")

inventory[OJ =

""

print("Teep :")

pri nt ( i nventory)
input("\nHae

Enter.

.")

i nventory, ,

1 "":

inventory[OJ

= ""

("").
,

pri nt,

i nventory.

~~~~~~~~~~~~~~~~~~~~~~~~~

, ,

n . - ,
r, .


,
. i
"

nventory [4: 6J [ " -

J:

print("a V: .
.")

inventory[4:6] =

[" "]

print("Teep :")

pri nt ( i nventory)
input("\nHae

Enter.

.")

- inventory[4]

inventory[5] -

" ".
,
.

i nventory

140

5.

n.

de l,

print("B
del inventory[2J

v.")

print("Bo :")

print(inventory)
input("\nHae

Enter.

.")

"'',

inventory.

2,

: ,
r, . , m

2 - : 3.

printC"Bop .")

del i nventory[: 2]
printC"B
print(inventory)
inut("\\

:")

Enter.

.")

inventory[ :2], ["".


i nventory :
del jnventory[:2J

""],

, .

,
- .


, .

. ,
, .

r
.."d

-
.

. -

141

: ,
, .
.

5.6.

5.6.


. ,

, . - scores -
, . -
. choi , .

#
#

None. -
Chapter 5. high_scores. .

(courseptr.com/downloads)

scores = []
choice = None

whi 1.

.
:

142

while choice '=


print(

5.

"":

1 -

2 -

3 -

4-

choice =
pri nt ()

input("Ba :

")


, . ,
: .

if choice == :
pri nt .)
, whi l
. ,
.

1,

#
1i f choi == 1 :

el i f,

print("Peop")

for score in scores:


print(score)

2,

score.
append( ),

score

elif choice == "2":


score = int(input("Bne
scores.append(score)

"))

scores.

143

3,

. ,
, , . ,
.

elif choice == "3":


score = i nt ( i nput( " ?: "))
if score in scores:
scores.remove(score)
else:
rint("". score. "
,

scores. ,

.")

score
remove( ).

, ,
( score). ,
score, .

, . ,

score. remove()

, .

remove()

del.

remove()

, .
~~~~~~~~~~~~~~~~~~~~~~~~~~

remove().

, , .

if score in scores:
scores.remove(score)


,
.

4:

elif choice == "4":


scores.sort(reverse=True)

sort()

. ,

. , ,
. , sort ()
.

reverse True. . ,
.

144

5.

~~~~~~~~~~~~~~~~~~~~~~~~~

, ,

. , , umers,
:

numbers.sort()

, , ,
el se. ,
.

#
else:

rint(".

".

choice)


, , ,
, , ,
:

input("\n\nHae

Enter.

.")

, .

.
n

5.1.

5.1.

nd()

sort()

. reverse
. True,

reverse()

unt()

id()

isert(i, )

pop([i])

i .

i
i

, -

01
rmv()

, : ?*>
, , ,

145

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

,
. , ,

.
, Python
.
, , , .

, 4' ~.
,

, , , .
, .

n
, .
, /,
/.

. ,
.

.
.
,
. , ,

. ,
.
:
.

2.0

4:~
. , ,

. ,
: ,

.
.

5.7.

146

5.7.

5.


:
, ,

. ,

. :

> nested =["" , ("" . "") , ["". "". ""]]


>>>

print(nested)

[''.

' ' ,

''),

[''.

,

"".

' ' .

nested

']]

" " , - " ". ""), - [ " ".


""].

.
. :
[ "" . 1000). "". 1500). "". 3000) J
printCscores)
[('. 1000). (''. 1500). (''. 3000)]

> scores =
>>>

scores .

, , : .

( !).

147

, 1 ,

- 1500,

3000.
~~~~~~~~~~~~~~~~~~~~~~~~~

nr , .
, n , :

nested

=("",

("".

("".

" ")))

. r
. n
r,

scores.

1
, ,
:

scores =[("". 1000).


printCscores[OJ)
(''. 1000)
>>> print(scores[l])
(''. 1500)
>>> printCscores[2J)
(''. 3000)

>

("".

1500).

("".

3000)]

>>>

. ,

. ,

? ,
, , :

a_score = scores[2J
printCa score)
(''. 3000)
>>> printCa_score[OJ)

>>>
>>>

""

scores :

print(scores[2][0])

>>>

scores

scores[2J[OJ

( (" "

. 3000) ),

, ( "").

,
.


, ,

, :

148
>
>

5. . 8

name. score
print(name)

=(" ",

175)

>>>

print(score)

175

. ,
, .


4~,

whi 1. ,
. -

downloads)

#
#

Chapter 5.

(courseptr.com/

high_scores2.py.

2.0

scores = []
choice = None
whi le choice '=
pri nt(

1 2 -

2.

choice =
print()

"":

input("Ba :

")

if choice =="":
pri nt( " .")

1,

scores

elif choice == "1":


print("Peop\n")

pri nt ("\ t ")


for entry in scores:

score name,

149

score. name = entry


pri nt(name. "\ t". score)

2,

entry.

( score ),
, ( name ).

,
, .

scores , 1, .
# add score
el if choice == "2":
name = inut(" : ")
score = int(input("Bne : "))
entry = (score. name)
scores.append(entry)
scores.sort(reverse=True)
scores = scores[:5J # 5

w
, ,

1 2,

l se. ,
.

else:
rint(". ".

choice)


, , , :
input("\n\nHae

Enter.

.")

2 , .

, , ,
,

. ,

"Python"

l anguage = "Python"

- ,

language, .
.

5.8, .

150

5.

. ~

language

111.

5.8. language

,
,

Python

"Python" , -
, , .

Python .

: ,

. ,
~ . ,
; , .

? ,
(, , ), , .

, , .
,

. , .
,

, .
. ,
. ( .

-~

9.

?) -,

. -
,
, , ,
- (
- ?), -
<'/:~. ,
.
. , ,
:

= [" ".
>>> mr_dawso = mike

> mike
>
>

h =

" ".

""]

mike

prit(mike)

[ .

' '.

''

>>> prit(mr_dawso)
[' '.

' '.

'']

' '.

''

>>> prit(hoey)
[ '

- mi ke, mr_dawso

. .

5.9.

151

mike------.
mr dawson

-+

ho~ey _____.
.

" "

5.9. mike, mr_dawson

" "

honey

""

, , ,
, . ,
(!)

, . ( !)
, , .

> honey[2J
>>>

" "

printChoney)

[' '.

' '.

' '

, .

honey,

2 ,

1<0

"", " ".

.
,

, . Python .

honey,

, , .
:

> printCmike)
[' ' , ' '
>>> printCmr_dawson)

' '

[' '

' '

' '

2 , mi ke mr_dawson,

" ". ,
.

: ,
. ,

, .
, () , :

> mike

= [" ".

honey = mike[:J
> honey[2J = "
>>> printChoney)

" ".

""]

>>>

[ '.

"

' '.

' '

' '.

'']

> print(mike)
[' '

honey -

mi ke.

honey

, , ,

honey, mi ke.

152

5.

n.

, - . ,
: ,

, r ! :

, .
,

. , ,


, , ,
. , , ,

. .
,
. ,
: . - ,
;

Python,

4 - .

. .
, , ,
.

, -

, , .

( )
.

, ,
, . .

5.10.

. ,

- . ~

- ( courseptr.com/downloads) u

Chapter 5.

#
#

geek_translator.py.

geek = {"404":

" . .

'.".

"Googling":

"'.

n -.".

404

'

153

"Keyboard Pl aque" : ". .".


"L ink Rot" : " - . " .
"Percussive Maintenance" : " . - .".

"Uninstalled" :

" -.

1990-2000- . "}

5.1 .


, , :

geek. .
"Keyboard Plaque" : ".

".

. ,

Plaque" -

. ,

"Keyboard
-

, ". "

. ~>.'> ()
. , "Keyboard Plaque" ".
" .

. ,
, .

>.'> ,

. ,

, ,


, ,

. ;

.

154

5.

r
,
.

. ,

geek

> geek["404"]
" . .

404

' '."

> geek["Link Rot"J


' -.

'

, .
,

. .
,

. ,

, , , .
,

Python . :
, .

~~~~~~~~~~~~~~~~~~~~~~~~~~

n , r , ,

> geek["Danc;ng Baloney"J


Traceback (most recent call last):
File "<pyshell#l>", line 1. in <module>
geek["Dancing Baloney"J
KeyError: 'Dancing Baloney'
"Dancing 8aloney", (r, -
, ,

-, ).

in

,

. , , ,
.

i n:

> if "Dancing Baloney" in geek:


print(" .

Dancing Baloney. ")

else:
Dancing Baloney.")
Dancing Baloney.

print(" .

"Danc~ng

geek

Baloney",

"Dancing Baloney" in

155

, .

, ,

i n . . ,

, .

,
. (, ) ,
.

get()

-
get ). , 110
. ,
, . :

> printCgeek.getC"Dancing Baloney".

" ."))

getC) . - 1

. ,
. ,
" ".

get ) ,

; .
, , ,
, ,

) None. :

> print(geek.getC"Dancing Baloney"))

None

~ r . ,

geek ,

. , ,
.

choice = None
while choice !=
print(

"":

1
2
3
4

choi

i nput "

")

156

pri nt ()
#
if choice

5.

== "":

print("o .")

1,

, . ,
. , (),

(), . ,
.

#
1if choi == "1" :
term = input("Kao
i f term in geek:
definition = geek[term]
print("\n". term. "". definition)
else:
print("\nY.

:",

")

term)

; ,

2,

#
elif choice == "2":
term = input("Kao ? ")
if term not in geek:
definition = inut("\n : ")
geek[termJ = definition
print("\nTep". term. " .")
else:
print("\nTao ! .")

.
,

. :

geek[termJ

definition
geek , term =

, defi ni ti on

.
: , ,
,

( =) ,

, .

. , ,
.
,

3.

157

~~~~~~~~~~~~~~~~~~~~~~~~~~

. ,
- , ,

. ,
.
, - .
.

3,
:

elif choice == "":


term = input("Kao ? ")
if term in geek:
definition = inut(" : ")
geek[termJ = definition
print("\nTep". term. ".")
else:
print("\nTaoo !

.")

,
:

geek[termJ = definition
~~~~~~~~~~~~~~~~~~~~~~~~~

Pytho ( )

. , , ,

. ,
.

4, l i f:

elif choice == "4":


term = input("Kao
if term i n geek:
del geek[termJ

print("\nTep".

term.

")

".")

else:
print("\nHe .

".

term.

" .")

,
. i

. , :

del geek[termJ

158

5.

( term ) geek.
.

de 1,

, ,
.

, 1se
.
~~~~~~~~~~~~~~~~~~~~~~~~~

, , .
, r .


1se ,
:

#
else:

rint".
inputC"\n\nHae

".

Enter.

choice)

.")

n
, .
.

, .
,
.

. ,
- , .
, .
. , ,
.

- . ,
, , , -,

. .

5.2

,
.
n

5.2.

gt(, [])

. ,
. , ,
,

keys()

None

159

values()
items()

~~~~~~~~~~~~~~~~~~~~~~~~~~

, - (views) ,
items(), - - <.
for. rr . ,

keys(), values()

, ,

. .

Python (www.python.org).

r
.1 , ' ,
~~.

. , , ,
: - , .
-
, .

r
. , ,
. radom,
.
-

downloads)

Chapter 5.

( courseptr.com/

hagma. .

#
#
# "". .

# .
. .

#
# ~
import random

. ,

, - :
,

12 .

160

5.

. , .

HANGMAN

, ).

HANGMAN

-+-

/-+-

161

-+- /

-+-/

/-+-/

/-+-/

1
1
1
1

1
1

1 1
1 1

"'"')

, :
AX_WRONG = len(HANGAN)

- 1

162

5.

, HANGMAN.
,
, .

HANGMAN

, .

,
.

; .

WORDS = "OVERUSED". "CLAM". "GUAM". "TAFFETA". "PYTHON")

random. choi ( )

WORDS word.

#
word = random.choiceCWORDS)

- so_fa r -

. - ,
. , (
), , .

so_far = "-" * lenCword)

# . -

wrong .
, , :

wrong =

, , ,

used.

used = []

1 .


, ,

:
print("opo

''.

!")

while wrong < MAX_WRONG and so_far != word:


printCHANGMAN[wrong])
printC"\nB :\n".

used)

rint"\n :\n".

so_far)

, . ,
,

so_far.

163


, ,
,
( , , ).
, .

, .
, ,
. ,

used.
")

guess = inputC "\n\n


guess = guess.upper()
while guess in used:

printC"B ".

guess = input("\n\nBee
guess = guess.upper()
used.appendCguess)

guess)
")


, , .
,
so_far, ,
.

if guess in word:
print("\na! '',

new

so_far

guess.

" !")

"1'

for i in rangeClen(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so far = new
,

wrong .
else:
printC"\nK .
wrong += 1

".

guess.

" .")


, .

, , .
<J .

164

5. .

, .

, .

if wrong == MAX_WRONG:
print(HANGMAN[wrong])
print("\nBac !")
else:
print("\nB !")

print("\no ".
input("\n\nHae

Enter.

word)

.")

, ,
. , , ,
, ( )
. ,

.

,
, . , ,

, ~

-.

, .
.

30 ,

: , ,

. , ,
, .

?, ,

. ,

, .
,

? , , , , .
-
.

. ,

.
<<->>

, , ,
. ,

. ,

,
-

;
- ;
, ;

;
-.

-
, , , ,

(),
. -
-.

( ) ,
; .
.

6.1-6.3.


, , , ,
len() range( ). Python

, , .
, :
- , .
, ,

166

6.1.

6.2.

6.

. -

... ...

. ,

6.3.

167

. ,
, ,
, , , ,

, , ,
.


-, ,

,
. ,
. ,
, , :

. ,

.
.

6.4.

6.4.

downloads)

Chapter

6. instructions. .

#
#.

def instructions():
'""' ."""

(courseptr.com/

168

. . -

pri nt (
.
"-".

8.

. .
.

\n

print("o

'-':")

i nst ruct i ons ()


printC"o :")

instructions()
print("Haec.

.")

input("\n\nHae

Enter.

.")

def

instructiosC):

, -
. ,
i nst ruct i ons ) ,
. def , , -
. , ,
. , ,
.
, .
, .
def, , , ,
, .
, . ,
, , .

instructions().


, .

.
:

""" ."""

i nstruct i s ()

169

, ,

. .
, , ,

, .

, . :

, . ,

IDLE,

,
.

r
, :

.
:

i nstructions()
, ,
. .

r
, .
m , .

, , ,

instructions()

, .


. :

, 3. ,
, , ,

, ,
, ,
, , .

, ,

,
, .

No 3.


, ,
, . ,

len()

.
,
.

170

6.

. -

,
, . .

6.5

6.5.

Chapter 6.

# -
#
def display(message) :
print(message)
def give_me_five() :
five = 5
return five
def ask_yes_no(question) :

(courseptr.com/downloads)

recei ve_and_return. .

"'"'

''

' '

. """

response = None
while response not in ("", "n") :
response = input(question) .lower()
return response
#

display("Ba .

number

\n")

give me five()

print("Bo give_me_five() :" . number)


answer = sk_s_n("\n. 'n': ")
print( ". ". answer)
input("\n\nHae Enter. .")


, ,

di sp l () .

. -

171

..

, , ,

, :

def display(message):
, ,
, . ,
display() mssg " .

display()

\n",

\n")

display("Ba .

message , .
, message
. :

print(message)
" ".

message,
, di sp l () .
di sp l () , , ,
. ,
.


-, ,

- give_me_fiveC) -

. , :

return five
,

fi ve , , .
return .
, ,
- .
, :

number = give_me_five()
printC"Bo

give_me_five():". number)

, , ,

number. number
5 - give_me_five( ). ,

, .

return

~~~~~~~~~~~~~~~~~~~~~~~~~

, , , .

, ,
.

172

. . -


, ,
. , fi ve
? ,

fi ve

give_me_fiveC ).
, ( ),
. .
;
() .

,
. , , ,

. ,
.

, , ,
.

. ,
.
, ~

~.

, ,

. , .

, .
, .
~ ~ ,

. ,
.
~~~~~~~~~~~~~~~~~~~~~~~~

, ~ .
, .

8 9,

- ask _yes _no() -

: ""

"n".

question:

def ask_yes_noCquestion)

ques t i on , .
- "\nn. '' 'n': ".

173

response = None
while response not in ("", "n"):
response = input(question).lower()
wh i 1 ,
, , n N.
.
,
, :

return response
.
answer
:

answer

= sk_s_n("\n.

print("Cnaco. ".

''

'n': ")

answer)


:
. , , 4'/-

ask_yes_no()

, ,

. . ,
:

, !

, '! . , t n r. r
, r r r
r . n .

n . ,
n, .

. - ,

r, .

. , ,
, .

no. - , ,

, .

-
. :
,

Python.
9.

174

. . -



.

. Python,
: .


~. .

6.6,

- .,
. .

n11

'.

1!16 "", ..

;.

1&!l -

N _ "

1 !

Bar1

Bar1

11?

11?

f)"

Bar1

11t1

11

_"

Bar1

lie

.rt

"

Bat1

nt1

11

n~?

.N

"

J<

t1t-1

"

11.11

"

Bar1

n1111

11

"

BaN

- 11 _ n

n11

12

12

12 '

J1?

11?

~)t(f1 Ente1~" - ._

6.6.

downloads)

#
#
#

Chapter 6.

(courseptr.com/

rthday_wi shes . .

def

irthdayl(name.

pri nt( "

age):

. ".

name . "!". "

".

age. "

age . "

? \ n")

def birthday2(name = " ". age = 1):


pri nt( " ." . name. "'". "
? \ n")

birthdayl("oap " .
i

rthdayl .

1)

" ")

" .

175

rthdayl( name ; "


rthdayl(age ; 1. name ;
i rthday2()

age ; 1)

".

" ")

irthday2(name; "")

12)
rthday2( name ; "". age ; 12)
i rthday2( "". 12)
input("\n\nHae Enter. .")
irthday2(age;

, , ,
:

def birthdayl(name. age):


, ,
:

irthdayl("oap ".

1)

,
, .
, ,

",

age -

1.

name

. .

"

: .

1 .

?.

, .
, :
i

rthdayl(l.

" ")

name 1, age -

" ".

: .

?.

.
.

, .


, . .

, ,

. i rthdayl () :
irthdayl(name =" ".

age; 1).

176

. . -

name

" ",

: .

age - 1
!

1 .

?. ,

,
. ,
; ,

. :

birthdayl(age

1. name

" ")

1 .

?, .

, , .
~~~~~~~~~~~~~~~~~~~~~~~~~~

r,
. - r
, r .

, ,
.


, , .
,
. bi rthday2( ),

def

bi rthdayl()

irthday2(name = " ".

age

1):

name ,
age,

" ",

. :
i

rthday2()

. ,
: .

1 .

?.

~~~~~~~~~~~~~~~~~~~~~~~~~~

<,
. :

def monkey_around(bananas

100. barrel of = "yes". uncle = "monkey's"):

def monkey_around(bananas = 100. barrel_of. uncle):


, .

177

, ?

-
. :

bi rthday2(name

"")

name, " ".


age - 1. : .

?.

1 .

birthday2(age = 12)

name -

: .

age,

12,

" ".

12 .

?.

:
irthday2(name

"".

age = 12)

12.

name

" ", age

: . !

12 .

?.

, :
i

rthday2( "". 12)

.
" "
.

12,

12 .

?.

~~~~~~~~~~~~~~~~~~~~~~~~~~~

,
. ,

, , ,
.



, , <1
, .

. .

: .

. , ,

178

. . -

.
. , , (.

6.7).

def funcl () :
varialel

def func2():
variale2
varialeO

def fuc 1():


variale1

fuc2():
variae2

def

variaeO
.

6.7.

6.7

funcl( ),

func2( ),

, .

, ;

. ,

, , ,
,

( ).

va ri l 1 funcl (),

funcl( ), .

, func2() ,

va ri l 1,

. .

. ,

. ,
, . ,

1 . >.'> , , ,
, , . , ,
, , ,
.

. . .

179

, , <~,

, .
,

. ,
variae2 funcl( ),
,

variable2

func2( ).


. , ,


~ ,

.
.

6.8.

6.8.

( courseptr.com/

downloads) Chapter 6. global_reach. .

#
#

def read_global():
print( " read_global () value ".
value)
def shadow_global():
value = -10
print("B shadow_global() value ",
value)
def change_global():
global value
value = -10
print("B change_global() value ". value)

180
# value

. . r-

value = 10
print("B value ".
value. "\n")
read_global ()
pri nt (" . va 1ue - ".
value. "\n")
shadow_global ()
print("Bepec . value - ".
value. "\n")
cha nge_g l l ()
print("Bepec . value ".
value)
input("\n\nHae Enter. .")

: ,
~1 . , , m
. ,

( ).
.

, .
read_global ().
va 1ue.
,
;
( , ). ,

read_gl 1() - :

value += 1
.

, ,
, ,

. ,
, ,
.

. ,

1 ,

181

. shadow_gl obal ().


:

value = -10

va l ue -10, va l ue . ,
va l ue -10.

, , ,

:
print("Bepec

value

".

value. "\n")
va l ue,

10.

~~~~~~~~~~~~~~~~~~~~~~~~~~

. :
, , .

.

gl l,

change_gl l ():

global value

va l ue

. :

value = -10
va l ue

va l ue

-10.

print("Bepec

value

".

value).

-10.



>.> >.>

, .

, , ,

. ,

, ,
. , .

182

. . -

, (,
) ,

. , , -

, - .
, , ,

. ,

. 28

( )? , ,

TAX_RATE

.28

. 28,

_R. : ,

-, , -, . ,
, ,
.

-
-~, ,

, .

, ,
. ,

.
,
.

-
, :
, .

,
. m .


, : .

,
.
.
, .
:

"-"

183

r
, ,
, . , ,

. , ,
, ?

,
: "" ""?

. ,
- .
- , .

,
. .

6.9.

6.9. ,

, ( ) .
, .

, .

q~ ( )
"" "", . , ,
, , "", .

. , ,
,

. .

6.1.

184

6.

. r-

6.1. -

display_istruct()

ask_yes_o(questio)

, .
, ''" ""

ask_umer(questio,

low,

high()

.
, (low) (high) .

pieces()

low

high

ew_oard()

display_oard(board)

legal_moves(oard)

. .

winer(board)

. .
: " None

huma_move(oard, huma)

, n .
.

computer_move(oard,
computer, human)

. ,
.

ext_tum(tur)

. .

cograt_wier(the_winer,
huma)

.
,

computer,


,
. .
, .
-

downloads)

#
#
#

Chapter 6.

( courseptr.com/

tic-tac-toe. .

-
-

""

= ""
=
= ""

NUM_SQUARES

(" "), - ("").

, . I
.

NUM_SQUARES -

~-.

185

r-

display_instruct()

. :

def di spl _; nstruct():


"'"' ."""

print(

"--

".

8.

. . -
.

\n

ask_yes_no()

, 4 4.
""

"n".

def ask_yes_no(question):
"""

''

''."""

response = None
while response not in ("". "n"):
response = input(question).lower()
return response

ask_number()

, .
, ,
.

def ask_number(question. low. high):


""" ."""

response = None
while response not in range(low. high):
response = int(inputCquestion))
return response

186

6.

. 111-

pieces()

, ,
, , .
.

def pieces():
""" ."""

go_first = ask_yes_no("Xoe ? (y/n): ")


if go first =="":
printC''\nHy . : .")
human =
computer =
else:
print("\nTo ." .")

computer =

human

return computer. human

no( ).

- ask_yes_

: .

new_board()

, :

def new_board():
""" .'""'

board = []
for square in range(NUM_SQUARESJ:
board.appendCEMPTY)
return board

display_board()

, "" "", print.


4-~.
.

def di spl ay_boardCboard):


""" > ."""

print("\n\t". board[OJ. "/". board[l]. "/". board[2J)


print("\t". "---------")
print("\t". board[J. "1". board[4]. "1 ". board[5])
print("\t". "---------")
print("\t". board[]. "/". board[7J. "/". board[8J. "\n")

legal_moves()

: human_move() - ,

187

, computer _

move() - .

. ,

, ,

4-

,
[.

2. 6. 8]

( , .

6.9). ,

, . ,
, .
.

def l ega l _moves (board):


.

moves = []
for square in range(NUM SQUARES):
if board[square] ==-:
moves.append(square)
return moves

winner()

.
: - ; , ; ,
None - .

WAYS_TO_WIN,

.
- ,
. :

(0. 1. 2).

, ,

- (3. 4. 5) -

1 2.

. .

def winner(board):
""" .

WAYS

WIN = ((0. 1. 2).


(3. 4. 5).
(6. 7. 8).

(0. 3.
4.
(2. 5.
(0. 4.
(2. 4.

(1,

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

for , ,
.

if

,
. , , ,

.
wi nner,
.

188

6.

. -

for row in WAYS WIN:


if board[row[OJJ == board[row[lJJ == board[row[2JJ != :
winner = board[row[OJJ
return wi nner
, .
, . , (

for ) .
i f not i n rd :
return

.
, , , ,

None.

return None

human_move()

-,

, .
.
, ,

, .
, .

def human_move(board. human):


""" . """
legal = legal_movesCboard)
move = None
while move not in legal:
move = ask_number("To
SQUARES)
if move not i n 1ega1 :

- 8):".

NUM

print("\nCeo ! . pyroe.\n")

ori nt( " ... ")


return move

computer_move()

computer_move()

, .
~~~~~~~~~~~~~~~~~~~~~~~~~~

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

189

,
. , computer_move()

, .

,
. (, .
.)

, ,
.

. , ,
, .
,

5.

( ), ,
, .

, ,
:

def computer_move(board. computer. human):


'""' ."""

# . u

board

board[: J

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

, .

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

. ,
.

1. , ,
.

2. ,
, .

3.

,
:

. ,

190

. . r-

#
BEST_MOVES = (4. . 2. 6. 8. 1. 3. 5. 7)
print(" ". end=" ")
. ,
, ( ,

) , . ,
; . ,

for move in legal_moves(board):


board[moveJ = computer
# .
if wi nner ( rd) == computer:
print(move)
return move
# 1 .
board[moveJ =

,
. , ,

. ,
( , )

, . ,
, ;
. ,
.

for move i n l ega l _moves rd):


board[moveJ = human
#
if winner(board) == human:
pri nt (move)
return move

1 .

board[moveJ =
,

BEST_MOVES, ,
:
, .

#
for move in BEST MOVES:
if move in legal_moves<board):
print(move)
return move

191

r-

- .
, ,
. , , .
, ,

IBM Deep Blue, '


Blue

, . Deep

200 . , , , , ,

1050. ,

Deep Blue

1 585 489 (

15 ).

next_turn()

, , .

turn,

, , 11

def next_turn(turn):
""" ."""

turn == :
return
return

if

else:
.

congrat_winner()

,
. ,

the_wi nner

, , .

def congrat_winner(the_winner. computer. human):


"""; ."'"'

if the winner != TIE:


print("Tp". the_winner.
else:

" !\n")

print("H!\n")

if

the_winner == computer:
print("Ka .

~.

\n" \

" .
.")

elif the_winner == human:


print("O .
? \n" \

! - .

": . .

!")

192

. . -

elif the_winner == TIE:


printC"Tee . : .
" !
.

\n" \

")

main()

,
.

. , , ,
, .

mai n( ), -

, .
, . ,
:

defmain():
display_instruct()
computer. human = pieces()
board = new_board()
turn =
display_board(board)
while not winner(board):
i f turn == human:
move = human_move(board. human)
board[moveJ = human
else:
move = computer_moveCboard. computer. human)
board[moveJ = computer
di spl ay _boardCboard)
turn = next_turn(turn)
the_winner = winner(board)
congrat_winner(the_winner. computer. human)

i

n (,

, ):

#
main()

inut"\n\

Enter.

.")

. ,

. ,
,

. , -

193

, ,

, . , -

-.

'

ask_numer() ,
( ).

1.

, ask_number().
( , ) ,

main().

computer_move(),

, .

<<>>

. ,
. ,
.

, ,
.

, :
;

;
;


- ,
. -,
. ,
-, .
(

).

, - ,
. .

, , Windows,

()
. .

7.1


Python

195

, , - 1

. :

.

7 .1.


~>.>

. , ,
. ,

. .

7.2.

, .
-

read_i t . txt.

( courseptr.com/downloads) Oiapter 7;

2 :

ASCII, . ,
- . .

, .

, ,
, .

. .

196

7.2.

7.

#
#

Chapter 7.

read _i t. :

pri nt( " .")


text file = open("read it.txt". "r". encoding='utf-8')
text=file.close()
print("\na .")

text file = open("read it.txt". "r")


print(text_file.read(l))
print(text file . read(5))
text_file .close()
print("\na .")

open( "read_ it . txt". "r". encodi ng= ut f-8 )


whole thing = text file.read()
print(whole_thing)text_file.close()
print("\na . ")

text_file = open("read_it .txt". "r". encoding='utf-8')


print(text_file . readline(l))
print(text_file . readline(5))
text_file .close()

( courseptr.com/downloads)

197

print("\na .")

text_file = open("read_it.txt". "r". encoding='utf-8')


print(text file.readline())
print(text=file.readline())
print(text file.readline())
text_file.close()
print("\na .")

text_fi l = open( "read_i t. txt". "r". encodi ng=' utf-8' )


lines = text_file.readlines()
print(lines)
print(len(lines))
for line in lines:
print(line)
text_file.close()
print("\nepepa .")

text file = open("read it. txt", "r". encoding='utf-8')


for line in text file:print(line)
text_file.close()
input("\n\nHae Enter. .")
.


( ),

ero

. ~:

> text_file = openC"read_it.txt". "r". encoding='utf-8')


open( ), ,

text _ fi l . :
, .

- "read_i t. txt" - .
, Python ,
. , r

, , .

"r". r Python ,

. , ,
.

. 7.1. 'ut f-8' r,


Unicode .
: Windows, Linux, OS r.
6111

7 .1.

rrrn

. ,

"w"

. , .
,

Python

198

116n

7.1

7.

()

"

r . r,
. ,

11+11

. ,

llw+"

. ,
. ,

"+"

r . ,

Python

. ,

text_file,

. ,
l ose ) ,
,

closeC ):

text_file.close()

>>>

, .


- , -
, .

read ()

readC)

. ,
:

>
>>>

text_file = open("read_it. txt". "r". encoding='utf-8')


print(text_file.read(l))

read.

:
>>>

print(text_file.read(5))

: , . Python ,
.
,

read()

. ,

read()

, .
:

>>>

>

text_file.close()
text_file = open("read_it.txt". "r")

199

,
.
, :

whole_thing = text_file.read()
print(whole_thing)

>>>
>>>

, em .
read()
. , :
, ,

>>>

text_file.close()

readl i ne( ). <1

, .
, .
,
. , , :

> text file = open("read it.txt". "r". encoding='utf-8')


>>>

print(text_file.readline(l))

:
>>>

print(text_file.readline(5))

>>>

text_file.close()
,

readl i neC)

readl i ne()

readl i ne()

read( ).
read()

. :

> text file = open("read it.txt". "r". encoding='utf-8')


>>>

printCtext_file.readline())

>>> printCtext_file.readline())

>>>

print(text_file.readline())

>>>

text_file.close()
,

. , s

"\n".

200

7.

read l i nes (), ,

. :

>
>>>

text_file = open("read_it.txt'". "r". encoding='utf-8')


lines = text_file.readlines()

1i nes

:
>>>

print(lines)
1\n . '

1i nes

2\n' .

'

3\n' J

:
>>>

print(len(lines))

for line in lines:


pri nt l i ne)
1
2

>>>

>>>

text_file.close()

for

text_file = open("read_it.txt". "r". encoding='utf-8')


for line in text file:
print(line)
1
2
3
>>> text_file.close()

>
>>>

, ( l i

ne)

. .


,
.

Python

, . .

201


~ ,

read _ i t. txt.

.
.

7.3.

downloads)

7.3.

Chapter 7.

( courseptr.com/

write_it. .


, ,
. :

#
#

write() . ")
text_file = open("write_it .txt". "w" . encoding='utf-8')
print("Coa

wri te _i t

.txt ,
. txt ,

. wri te _i t

, .
write(

),

text

file . write("Cpoa

l\n")
2\n")

text-file.write("o

text=file.write("o 3\n")

write()

, .

\n

202

7.

, . ,
, .
, ,

\n.

, "

2\n

3\n"

1\ n

wri te ( ) .

text_file.close()
, , ,
:

print("\na .")

text_file = open("write_it. txt". "r". encoding='utf-8')


print(text_file.read())
text_file.close()


wri te l i nes ()
. read l i nes ( ), wri te l i nes ( ) ,
: , .
:

pri nt ( "\n ; wri tel i nes (). ")


text_file = open("write_it.txt". "w". encoding='utf-8')

write_it. txt,

.
,

lines

=["

l\n".
2\n".

"

"

3\n"J

,
.

1i nes

wri te l i nes ( ):

text_file.writelines(lines)
:

text_file.close()
, ,
:
print("\na .")

text_file = open("write_it.txt". "r". encoding='utf-8')


print(text file.read())
text_file.close()
input("\n\nHae Enter. .")

203

, ,
. .

7.2.

7 .2.

dose()

. J)'
,

d([])


. , ,

readline([co])

r r. , ,

readlles()

write(crpoa)

writelles(
)

,
. :

.
, .

-
, . Python

. ,
, .

n .

Python. ,

1 (,

, , ).

.
: (
), .

. .

204

( courseptr.com/downloads)

7.4,

Chapter

7.4.

7.

7.

pi ck l _i t ..


, ,

#
#
import pickle. shelve

pickle

she l ve

: ,
, .
, :

, :
rint(" . ")

variety =[" . "". ""]


shape = ["" . "". ""]
brand = ["" . "". ""]
:

= open("picklesl.dat". "wb")
() ,

pi ck l es 1. dat
"wb".

205

, ,

7.3.

7 .3.

"rb"

. 01 , Pytho

tlw"

. , .
01 ,

""

. 01 ,
. 01 ,

"r+"

. ,

Python

"wb+"

. ,
. 01 ,

"+"

n . 01 ,
. ,

picklesl .dat

vari ety, shape brad -


pickle.dump().

: , .

pickle.dump(variety. f)
pickle.dump(shape. f)
pickle.dump(brand. f)
f.close()
, ,
, picklesl.dat

variety.

. ,

shape brand.

, :

pi ck 1.1 oad ().

: ,

.
rint("\n .")

f = open ( "pi ck 1es1. dat . "rb")


variety = pickle. load(f)

206
shape
brand

=
=

7.

pickle.load(f)
pickle.load(f)

,
, ["".

"".

vari ety.

""].

, ["".
"". "" J

shape.

()

[ "".

"".

" "J,

brad.

, , :

print(variety)
print(shape)
pri nt(brand)
f .close()
.

7 .4.

7.4.

pickle

dum(,

. n True, , False -
, .
in = False

, [,n])

ld()

shel ve ( .

, ,
.

.\1

s:

rint("\n .")

shelve.open("pickles2.dat")

she l ve. open () , open ),


shelve.open() ,

s;

.
------------------------

shelve.open()

Python

, .

207

she l ve. open () -

. ,

. (

), "".
.

7.5.

s["variety"]
s["shape"J =
s["brand"] =

["".

["".

"".

"".

["".

"".

""]

""]
""]

. 1

<J ["". "". ""],


["". "". ""],

"".

"variety"
"shape" -

"brand" - ["".

""]. ,

sync()

-:

#.

s.sync()

, ,

Python ,

. ,
,

sync ().

cl ose( ).

-----------------------

, shelve
. ,
, .


, , ,
. :

, :

rint("\n :")

s["brand"])
-". s["shape"J)
-". s["variety"])

rint(" -".
printC"op
rint"

s.close()
inputC"\n\nHae

Enter.

.")
611111

7.5.

""

r . ,

''n"

. ,

"r''
"w"

. ,
. ,

Python
Python

208

7.


- ,

'l, n n . n m
n

XMl. n

Pytho

n. http://www.pytho.org.


Python ,

. , ,
( exception ), ,

. , Python
.

Python:

> num = flt("!")


Traceback Cmost recent call last):
File "<pyshell#l>". line 1. in <module>
num = flt"!")
ValueError: could not convert string to float:

Python

"!" . ,

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


.t
,

. ,

.
.

downloads)

7.5.

try/except.

(courseptr.com/

Chapter 7. handl e_it. .

try / except

( .t)

try ,

except, ,

, ,
.

209

7.5.

! ,

~ .

try except.

#
#
# try/except

try:
num
except :

= float(input("Bee :

print("oxoe.

"))

!")

fl oat () -

, - ,

, "!",

: .

! . ,

num
except,

, ,
.


. , ,
float( ),

"!

Va 1ueError,

210

).

20; . 7.6

7.

6n8

7.6.

IOError

, r /
, ,

IndexError

eyError

NameError

, (,
}

SyntaxError

TypeError

, rr -


, r

ValueError

ZeroDivisionError

except ,

. ,

except.

, V 1ueError:

#
try:
num = float(input("\nBee : "))
except ValueError:
print("o !")

print , ValueError.

,
: !. ,
,

except

try

.
, , .
.
~~~~~~~~~~~~~~~~~~~~~~~~

? ,
.
, r, .
r,
.

211

~~~~~~~~~~~~~~~~~~~~~~~~~~

, , , . :
. , ,

, ,
:

> 1/0

Traceback (most recent call last):


File "<pyshell#O>". line 1. in <module>
1/0

ZeroDivisionError: int division or modulo

zero

, ZeroDivisionError.
, .

, .

except

, :

#
print()
for value in (None. "!"):
try:

rint(" :

value.

"-->"

end=" ")

print(float<value))
except (TypeError. ValueError):
print("oxoe. !")

.
fl oat (None)

, .

TypeError,
. flt("! ")

"-

ValueError,

"

, ( ).

except .
:

except. t ry
except:
print()
for value in (None. "!"):
try:
rint(" : value. "-->" end=" ")
print(float(value))
except TypeError:
print(" !")

except ValueError:
print(" . !")

None,

TypeError

212

7.

" !". "


!"

Va l ueError,

: "

. !".

.v

except
try.

, ,
.


, .
, Python.
, as.

try:
num = float(input("\nBee
except ValueError as :
print("o !

"))

:")

print(e)

else

except t ry
el se. , try
.

# try/except/else
try:
num = float(input( "\n
except ValueError:

"))

print("o !")

else:
print("B ".
input("\n\nHae

Enter.

num)

.")

try,

num

. , ,

num

~ ~. -

213

. ,

. ,
; -

. ,

tri vi . txt,

, , .

t ri vi . txt

r
, ,

tri vi . txt.

. () .
:
<

>

<>

<
<

1>
2>

< >
<

4>

< >

<>

:
.

/ .

1
- !
.

" "

. .

3
" "

tri vi . txt

15

Soul .

downloads),

Chapter 7.

(www.courseptr.com/

214

7.

, (.

, .

,
. , " "

) .

(, ,

".

. . . / .

/ '"1. ?"
.

"", "'', "", ""

, .
,
.

1,
- (""). ,

- ,
.

- " - !"
.

, (/).
. , Python
, .

, s- .

, .

open_file()

open_fi le( ),

( - ),
. try except
IOError, -,
.

, .
;

sys .exit( ).

, .
sys . exi t ( ) . ,

sys .exit()

sys.

# .

#
import sys
def open file(file name. mode):

"'"' .'"'"

try:
the_file = open(file_name. mode. encoding='utf-8')
except IOError as :
rint(" ". file_name. "
.\n". )
input("\n\nHae

Enter.

.")

215

sys .exit()
else:
return the file

next_line()

next_l i ne( ),

def next_line(the_file):
""" .

line = the_file.readline()
line = line.replace("/". "\n")
return l i ne
, - :

s- . , Pytho
, . ,

: , ,
. , ,

tri vi . txt

.
, .

next_ock()

next _b1ock ( ) ,

. (
, , , ), (

def

).
next_ock(the_file):
""" ."""

category = next line(the file)


question = next=line(the=file)
answers = []
for i in range(4):
answers.append(next line(the file))
correct = next_line(the_file)
i f correct:
correct = correct[OJ
explanation = next_line(the_file)
return category, question. answers. correct. explanation
,
. , tr~

via. txt,
category "". category
, main() .

216

7.

welcome()

we l come()

;
.

def welcome(title):
""" ."""
print("\t\topo

''

!\n")

print{"\t\t". title. "\n")

r
i n(),
. :
, ( ),
.

def main():
trivia file = open file("trivia.txt". "r")
title: next lineCtrivia file)
welcomeCtitle)
score =

, ,

whi le,
category .

,
.

: (),
.

category, question. answers. correct. explanation


whi l category:
#
printCcategory)
print(question)
for i in range(4}:
print("\t". i + 1. " " ar1swers[iJ)

= next_ock(trivia_file)

#
answer = input("Ba

")

217


. ,
;

, .
( , ) .

#
if answer == correct:
print("\na!". end=" ")
score += 1
else:
print("\nHe.". end=" ")
print(explanation)
printC"Ce:". score. "\n\n")
n
next_ockO, ,
. ,

category

#
category. question. answers. correct. explanation = next_ock(trivia_file)
w

tri vi . txt

trivia_file.close()
print("o !")

print("Ha

".

score)

main()

ma i n( ) :

main()
input("\n\nHae

Enter.

.")

.
, ,

.
( , , ).

, , ,

218

7.

. ,

, ,
, , .
,
: ~.>

, .
, ,

~,.. .

, -

' --

- _, - ;

. ,
.

, . n
-.
.

, , :
.

,
Python.

.
<< >>

- ()

. ,

;
.

, .

.
:

, ;
;
;
.

r
~

. ;
,

, . , ,

. ~
.

8.1-8.3.

,
. ,
. ,
. , ,
, .

220

8.2.

8.

8.1.

8.3.

221

, ,

, , . ,

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

(, ,
) , . - ,

. :
, .

,
. ,

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

, ,
. ,

100, - 1 .

-----------------------

, .
, . ,

. Pytho,
, .

,
, - .
- ($~ . ,
.

r r
($ ~

- , Python.

222

8.

(, ).
.

8.4.

. 8.4. talk()

Critter,

downloads)

Chapter 8.

simple_critter. .

(courseptr.com/

#
#
class Critter(object) :

""" """

def talk(self) :
rint(".

Critter.")

#
crit = Critter()
crit.talk()
input(" \ n \ nHae

Enter.

.")


- <1j>,

.
:

class Critter(object) :
1ass -

Cri tter.

, .

Python ,

223

object.

object

,
.

object.

, .
:
""" """


.
:

def talkCself):
rint(".

Critter.")

, ,
( ).

ta l k )
Cri tter ..

ta l k)

se l f,

. .1 rt.ll, ,
, ,

sel f. .
sel f: ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~~

n ,

. ,

self.


, ( -)
:

crit

Critter()

Cri tter

crit.

Critter

, . ,
, , ,
: .

224

8.

ta 1k ).

, , .

, :

cri t . ta 1k ()


ta 1k () Cri tter,
cri t. : .
Critter ..

ta 1k(),

, ,
. - .

,
. ,

, .



~> Cri tter,
-.

, .

8.5.

8.5.

225

- (courseptr.com/
downloads) Chapter 8. constructor_critter. .

#
#

class CritterCobject):
""" """

def

init

Cself):

rint(" !")

def talk(self):
print("\npe.

Critter.")

critl = Critter()
crit2 = Critter()
critl.talk()
cri t2. ta l k()
input("\n\nHae

Enter.

.")

r
, ,

( ):

def _init_Cself):
rint" !")

,
, .

_init_, Python

, -. ,

_init_C)

Critter. , ,
:n !.
-------------------------

8 Python

. -

_init_ -

ero .

critl = Critter()
crit2 = Critter()
. -
: !.

, r .

ta l k()

226

8.

critl. talk()
crit2.talk()
: "\n .

Cri tter. ", -



-.
.

r

name.
Critter -,
name. , ,
, . .

8.6. Critter name,


talk()

#
#

class Critter(object) :
""" """

def

i nit

8.6.

se lf. name) :

rint(" !")

227

self.name = name
def

~str~Cself):

rep = " Critter\n"


rep +=": "+ self.riame + "\n"
return rep
def talkCself):
rint". ". self.name. "\n")

critl = CritterC"o")
critl.talk()
crit2 = Critter( "")
cri t 2. ta 1k()
print("Bo critl
print(critl)

:")

rint("

critl.name:")

print(critl.name)
input("\n\nHae

Enter.

.")


, ~>, -

!, .
name,

name.

critl

= CritterC"o")

Critter, nm "".
cri t.
,
self. , self
,
. , sel f
, ( , ,
).
~~~~~~~~~~~~~~~~~~~~~~~~

self, - ,
r . Python, ,
, .

, -, ,
Critter sel f
, name "". :

self.name = name

name name,

"".

228

8.

crit.
,

cri t

name,

"". , !
:

crit2

= Critter("Myp")

name,

Critter
crit2.

"",

r
, .

ta l k() , name
Critter: , .
, talk( ):
critl.talk()

sel f

def talk(self):

pri nt . .
se l f. name name :
rint(". ". self.name. "\n")

crit2. talk()

ta l k() .
name cri t2 "".

,
, . ,

name critl:

print(critl.name)
.
, ,
: _. _.
~~~~~~~~~~~~~~~~~~~~~~~~

.
, ,
.



, :

<~main~.Critter

object at

90>

print(critl), Python

229

Cri tter.
. , :
_st r_ (),
. ,
, _st r _

( ).

name.
print(critl)

Critter

~~~~~~~~~~~~~~~~~~~~~~~~~~

_str_()
. , ,
.




m . , , ,

. ,
, . ,

Cri tter

tota l

tota l.

. .

, Python , ;
. - , .

1 .

Python , .

r r

,

. ,

-4, 4

t. . .

230

8.

, . ,

Critter,
, .
.

8.7.

8.7. !

downloads)

#
#

Chapter 8.

cl assy_critter. .

class Critter(object):
""" """

total =
@staticmethod
def status <) :
print("\nBcero
def init (self. name):

" .

Critter.total)

rint(" !")

self.name = name
Critter .total += 1
#

print("Haxoy

Critter .total :". end=" ")

print(Critter .total)
print("\nCoa . ")

critl = rittr(" 1")


crit2 = rittr(" 2")
crit = rittr(" 3")
Critter .status()
print("\nOpaac :" .

print(critl .total)
input("\n\nHae

Enter.

.")

end=" ")

(courseptr.com/

231

total =

total

Critter .

, (
) .

- Pytho11 .
, ,
, , ,
.


;
.

Critter

total

print Critter.total

status()

pri nt ( "\ nBcero

"

. Cri tter. tota l )

-
:

Critter.total

+=

, - tota l 1.
:
_._.

, ,
. :

print(critl.total)
tota l,
Critter, .
, : pri nt (cri t2. tota l) print(crit. total ), .
~~~~~~~~~~~~~~~~~~~~~~~~~-

,
. ,
.

232

8.

def status :
print("\nBcero

status( ):

".

Critter.total)

- . ,
se 1f. , status( ),

, , . ,

,
se 1f, . , ,
, .

status ( ) - ,
, , - (~~)
. :

@staticmethod
,
status( ),

Critter, total.
.

@stat i cmethod, , ,

, ,

self.

r
.
:

Critter.status()
, ,

. ,

, .
, , .

status ( );

, . , ,

, -
tota 1 1.


4
\'>

6. ,

233

( ).
,

. , , .
,
.

.
, . Checking_
Account ( ) 1ance. , ,
; 1ance
- . ,

1ance .
.
, , ,
, , .
wi thdraw(),
,

: , ,
, .


(pulic ):

(private ).


~ , ,

. .

8.8.

8.8.

234

8.

,
-

Chapte .

(www.courseptr.com/downloads)
pri vate_critter. .


,
. -
: :

#
#
class Critter(object):

""" """

def _init_(self. name. mood):


rint(" !")

self.name = name
self ._mood = mood #

# ~

, ,

i ,
.
~~~~~~~~~~~~~~~~~~~~~~~~



( , ~
).

ta l k( )

_ mood:

def talk(self):
print("\nMe ",

self.name)

print("Ceac ".

self._mood. "\n")

,
.


Critter, . ,

, :

> crit

Critter(name

="".

mood

="")

>>> print(crit.mood)
Traceback (most recent call last):
File "<pyshell#l>". line 1. in <module>
pri nt ( crit. mood)
AttributeError: 'Critter' object has no attribute 'mood'

235

AttributeError, Python

crit

mood.
, .
:

>>> print(crit. mood)


Traceback (most--ecent call last):
Fi 1 "<pyshel 1#2>". l i ne 1. i n <modul >
print(crit. mood)
AttributeError: 'Critter' object has no attribute ' mood'

Attri buteError:

, . ,
, ?

, . Python ; ,
, .
:

>>>

print(crit._Critter~mood)

mood,
"".

,
?

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

,
.


,
: .
, :

def

~private_method(self):
print("o .")

. ,

( )
.


,
),

. u ic_method(
:

236
def

8.

puic_method(self):
print("o .")

self.~private_method()

.
,
.

private_method:
>>> crit.private method
Traceback (most recent call last):
Fi l "<pyshe 11#0>". l i ne 1. i n <modul >
crit.private method
AttributeError: 'Critter' object has no attribute 'private_method'

,

crit

Attri buteError: Python

).
, :

>>> crit.~private_method()
Traceback (most recent call last):
File "<pyshell#l>". line 1. in <module>
crit.~private_method()

AttributeError: 'Critter' object has no attribute

~private_method'

) .
:

>>>

crit._Critter~private_method()

, ,

.
~~~~~~~~~~~~~~~~~~~~~~~~

:
.



. , :

crit = Critter(name
crit.talk()

="".

mood

="")

crit.pulic_method()
input("\n\nHae

Enter.

.")

237

_i ni t _

()

Cri tter,

, ,
. ta l k() cri t .
,

publ ic_method()

crit

. ,
.. .

n

. ,
?
, . ,
, ,
. Pytho
, ,
.
-----------------------
: , r
r ,
r , r .

n : r
r
.


, ,
. , , ,
, .

Python

- , .

, - Critter.
, , ,

. .

8.9.

,
-

Chapter 8.

(www.courseptr.com/downloads)
property_critter. .

238

8.

8.9.

Critter

,
- . -
Critter,

name,

_ name:

#
#
class Critter(object) :
""" "" "

def _init_(self. name):


rint(" !")

self . name = name


@propertydef name( se lf):
return self. name
, ,
(

_name ),
@property. ;
name. name Critter
_name - ,

.
(

name

).

, , ,
,

@property. .

239

, , ,

( ).
, ~
, .
.

name _name

@name.setter
def name(self. new name):
if new name ==print( "
else:
self. name = new name

.")

print(" .")

@name. setter. setter


name, , , ,
name 1

, : @,
, , ,

setter.
name,

. , , .
: - , .

new_name ,

. ,
_name ,
.
_name new_name , .
, - ,
.

name, ,

. :

def talk(sel f):


print("\npe. ".

self.name)

crit = Critter("o")
crit.talk()
se1f. name name ,
_name.

.

,~~. .

Python,

240

"". ,

8.

name

, , :

end=" ")

rit("\ ".

print(crit.name)

cri t. name

Critter, , ,
name Cri tter

, _ ( -
"").
:

pri t( "\
crit. = ""

".")

crit.ame

"" m

,
_ . "".
, , _m " ",

..

:
prit("Mo ". d="

")

print(crit.name)
" ".
:

rit"\ ".")
crit.ame = ""

, m
, _.
new_ame ,

: .,

cri t .
name :

pri nt "

".

end= " ")

print(crit.ame)

iut("\n\n Eter.

.")


,
. ,

. ,
-

Chapter

(www.courseptr.com/downloads)

8. critter_caretaker. .

241

Critter

Critter -

, m

. ,

-r
-

Critter: name, hunger boredom.

hunger boredom

, ,
.

#
# .
class Critter(object):

""" """

def _init_Cself. name. hunger


self.name = name
self.hunger = hunger
self.boredom = boredom

=.

boredom

0):


. ,

Critter.

__pass_time()

Meo

_pass_time() -

(hunger) (boredom) .
, , ; -
. , ,
, ,

- : , , .

def

pass timeCself):
self.hunger += 1
self.boredom += 1

mood
mood

: hunger
boredom Critter, , ,
"", "", " " "".

mood

, ,

.
.

@property
def moodCself):

mood -

Cri tter,

242

8.

unhappiness = self.hunger + self.boredom


if unhappiness < 5:
m = ""
elif 5 <= unhappiness <= 10:
m = ""
elif 11 <= unhappiness <= 15:
m = " "
else:
m = ""
return m talk()
ta 1k() mood Cri tter
. eo

_pass_time( ).

def talk(self):
self.naire.
self._pass_time()

print("Me ".

". ". self.rood.

"naw.\n")

eat()

eat () ,
food. , food

4.

. , ,

_pass_time( ).

def eat(self. food = 4):


pri nt ( "". ! ")
self.hunger -= food
if self.hunger < :
self. hunger =
self._pass_time()

play()

play() ,
fun. , fun

4.

. , ,

time( ).
def play(self. fun

_pass_

4):

print("Y!")

self.boredom -= fun
if self .boredom < :
self.boredom =
self._pass_time()
w
ma i

n( ).

Critter.

hunger boredom -

243

,
.

def mainO:
crit_name = input("Ka
crit = Critter<crit_name)

")


.
, .

1,

ta l k( ). 2, eat ( ).
3, l ( ). ,
.

choice = None
while choice !="":
print \
(

1t

11"

1 2 -

3-

11 11 11)

choice = input("Ba
pri nt ()
#
if choice == "":

")

print("o .")

el if choice == ':
cri t. ta 1k()
#
elif choice == "2":
crit.eat()
#

if choi == "3" :
crit. l ()

#
else:
print( ". ". choice)
nr1

main()

, , .

main()
input("\n\nHae

Enter.

.")

244

8.

,
. , oryr
( ) (),

- ~

. -,

. , ,

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

,'

, ,
(
).

, .
, . ,
.

. , , ,
, (

Critter 1

_str_()).

Critter,

.
, . , ,
: 1 , .

,
.

<<->>
.
, .

, ,
, , .

.

, :

;
;
;
;

;
.

n-
, ,
-- 1. :

- ,
21 , . ,

, ; ,

10 , -

1 11

( , ).

2 , .
,

.
- .

. .

. .

246

9.

- . -

, . ,
. , ,

, .

. ,

21 . ,

, . ,
.

, .

, <~-~,
,
,

17 .

, ,

, . ,

, . (
) .
.

9.1.

9.1.

- ,

. ,

; .

, -
.

.
. , , , ,

247


w
,
. : ,
(, ,

).
. .

9.2.

Alien.

9.2.

hero -

Pl ayer

ast()

i nvader di ()

hero

i nvader -

i nvader. ,

, ,
.
.

9.3.

hero.ast(invader)
.

9.3. hero Player invader Alien

248

- . -

9.


, , ,
.
. /-

- UML (

),

, -i __ _~_ ~_~-~- ________________________________________________________________________________________________________

downloads}

#
#

Chapter 9.

(courseptr.com/

al ien_blaster. :

class PlayerCobject):
""" -.

def

ast(self.

"""

enemy):

printC"po .\n")

enemy. di ()
class Alien(object):
""" -
def die(sel f):
print("Teo .
.

-.

',

"""
.

\n" \
" ... .

".

\n" \

". .

'")

print("\t\te \n")

hero = PlayerC)
invader = Alien()
hero.ast(invader)
input("\n\nHae

Enter.

.")


, ,
! :
Pl ayer, hero, l i en,

i nvader.

, .

hero.ast(i nvader) ast()

hero
i nvader. st ) , ,
enemy. l ast ()
enemy l i en. ,
last() enemy.die() die() Al ien. ,
, Pl ayer l i en ,
die( ).

249


i nvader hero :

di () ,


. ,
, , ,
, : , , . .
: , .
, , , .
. ,
Drag_Racer, ;
engine, Race_Engine
().

Zoo, ,
ani ma 1s - ( Ani ma 1).
, , .

r
,
-
( , ).

(Hand),
; , -.
.

9.4.

9.4.

Hand -

Card

250

9.

- . -

,
-

Chapter 9.

(www.courseptr.com/downloads)

1ayi ng_ rds . .

Card

Card,
.

#
class Card(object):
. """
RANKS = ["". "2". "". "4". "5". "6". "7".
SUIS = ["".

"".

"9". "10". "J". "Q".

""]

"d". "h". "s"J

def

init (self. rank. suit):


self.rank = rank
self.suit = suit
def _str_(self):
rep = self.rank + self.suit
return rep
Card

rank, -
RANKS : (""),
2 10, ("J"), ("") ("").
suit, .
SUS: "" (lus)-, "d" (diamonds)-y
, "h" (hcarts)- , , "s" (spades) - .
, rank, "", suit, "d",
.

. ,
, _str _(

).

Hand

, ,

-:

class HandCobject):
""" :
def _init_Cself):
self.cards = []
def str Cself):
if seif .cards:
rep = ""
for card in self.cards:
rep += strCcard) + " "
else:
rep = "<n>"
return rep

"""

Hand,

251

def clear(self):
self.cards = []
def add(self. card):
self.cards.append(card)
def give(self. card. other_hand):
self.cards.remove(card)
other_hand.add(card)
Hand rds,
. , - ,
.

_str_() .

Card
. Hand ,
<>.

1 r ( ) : rds
. add() cards. gi ve()
cards, ,
Hand ( add( )).
, Hand Hand :
cards Card.

Card:

cardl = Card(rank =

suit

="")

print("Boy -:")

pri nt(cardl)
card2 = Card(rank = 2. suit ="")
card = Card(rank = "". suit ="")
card4 = Card(rank = "4". suit = "")
card5 = CardCrank = "5". suit = "")
print("\nBoy :")

pri nt rd2)
pri nt ( card)
print(card4)
print(card5)
Card rank "",
su i t -

"" ( ). ;

Hand

Hand, my_hand
:

252
my_hand

9.

- . -

Hand()

print("\neaa .

:")

pri nt (my_hand)

cards

<>.

my_hand

Card

my_hand.add(cardl)
my hand.add(card2)

-hand.add(card)

my-hand.add(card4)
my-hand.add(card5)

print("\neaa . :")

pri nt (my_hand)
2 4 5.
Hand your_hand.

my_hand

give( ),

~ ~

~ :

your_hand = Hand()
my_hand.give(cardl. your_hand)
my_hand.give(card2. your_hand)
print("\nepe .")

pri nt (" :")


print(your_hand)
print("A :")
pri nt (my_ hand)
,

your _hand

my _hand - 4 5.
my_ha nd

2,

1 r ( )
:

my_hand.clear()
print("\nY
print(my_hand)

input("\n\nHae

Enter.

:")

.")

<>.

() .
, ,
!

253

~~~~~~~~~~~~~~~~~~~~~~~~~

Python

1<, nr ;

r .
- r, .


,
. ,

.

.
, , Drag_Racer -
stop() go( ). ,
(

400

/ ).

stop()

go()

Drag_Racer.

,
.

2.0

2.0 -

Deck

().

, ,

Deck
Hand. Deck
Hand. Deck , -, ,

, ,

. , <~: ,
. .
, . -,
, -,

2.0

9.5.

, , , ,
.

,
-

Chapter 9.

(www.courseptr.com/downloads)

playing_cards2.py.


, .

- Card Hand -

254

9.

- . -

l!ID~

. '.
3<\

IJur

KOJ10J1a.

<)

JJ

n11

Rc

.Jc

Qc
9d
6/1

l!d
5}1

2s
Qs

Qd
2d
Sh

. Js

5s

2s

r1

2d
Qd
911

&
d

Kd
1011

/1

4d

5s

6s

?s

Jh
8s

5d
2h
Q!1
9s

Jc
311

?d

?
2

3s

JJ1
9s

9d
211

&d
311
\1

HJt
?d
411
As

10s

Js

?11
4d
Rd
10s

!
d

1(,
d

911

511

Ss

l>

10h
4h

Jd

As

611

4s

J(h
5

Qc
Qs
Sd
?s

!d

Qc
Qs
5d
?s

4d
Ad
1fiJs
1fiJd

Jc

?d

9d

?h

""511

!:J:

Js

Ad
Jd
811

/{

Al1

Ql1

rn

911

neper1catia.

11<\

Qd

?11
4:;

Q/1
l{d
6<1
Ks

1d

Ks

}(._. . 110na

r.

2d
811

11

s
6

Ss

10

2"
4

Ah

Jd

J<o11ona .
Bor .

~r,r

._

Ente".

1011
411

J]1

3<1

9s

As

611

211
4s
\1

()

9.5. Deck

Hand

# 2.0
#
class Card(object):
.
RANKS = [ . 2. .. . 4.. "5.. "". 7 . . 9. 10. J..
SUIS = [ " " .

"d". "h". "s"J

def _init_(self. rank. suit):


sel f. rank = rank
self.suit = suit
def _str_(self) :
rep = self.rank + self.suit
return rep
class Hand(object):
'' :
def _init_(self) :
self.cards = [J
def str (self):
if self.cards :
rep =
for card in self .cards:
rep += str(card) + "\t"
else:
rep = "<>"

255

return rep
def clear(self):
self. cards = [ J
def add(self. card):
self.cards.appendCcard)
def give(self. card. other hand):
self.cards.remove(card)
other_hand.add(card)

Oeck.

Hand:

class Deck(Hand):

Hand

Deck -

Hand.
Deck Hand. ,
, Deck
- :

_init_O;
_str _();
cl ear( );
add();
give().

,
Deck.

Hand


, . .

Deck:

""" .
def populateCself):
self.cards = [ ]
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank. suit))
def shuffle(self):
import random
random.shuffleCself.cards)
def deal(self. hands. per hand = 1):
for rounds in range(per_hand):
for hand in hands:
if se lf. rds :
top_card = self.cards[OJ

256

9.

- . -

self.give(top_card. hand)
else:
print("He :

!")

, , ,
:

populateO;
shuffleO;

deal .
,

Hand,

Deck

Deck.

Deck ,
.

Deck:

deckl

Deck()

, , -
.

Oeck

Hand,

Deck

Deck. ,
rds ;

$>.

deck 1.

, , . :
print("Coaa .")

print("Bo :")

print(deckl)

Hand.

_ s t r _ ( ) Deck ,

<>.

. ,
.

popul ate()
52 :

deckl,

deckl.populate()
, :

popul ate() Deck. 52


( Card. SUIS Card. RANKS);
Card,
,

257

pri nt( "\nB

.")

print("Bo :")

print(deckl)

52 . ,
- . ,

deckl. shuffl ()
Deck shuffle(), random

random. shuffl ) cards .


random. shuffle() ,

, , . ,
,

pri nt( "\n

.")

print("Bo :")

print(deckl)
Hand,

hands:

my_hand = Hand()
your_nand = Hand()
hands = [my_hand. your_handJ
:

deckl.deal(hands. per_hand = 5)
dea l () - , Deck.
: , .

, : : !.
,
. ,

deckl

my_hand

your_hand.

, :
printC"\nMe

.")

pri nt( " :")


printCmy_hand)
pri ntC :")
printCyour_hand)
printC"Ocaoc :")

printCdeckl)
, ,
,

42.

258

9.

- . -

deckl.clear()
pri nt ( "\ n

.")

:
print("Bo :".

inputC"\n\nHae

Enter.

deckl)

.")


, ,
. , ,
, .
. , :
,
.

Drag_Racer.

, ,

stop() .
, ,

- , - Drag_Racer
Parachute_Racer stop( ).
stop( ), stop() Drag_Racer

(, , ),
.

r nti .

3.0 rd, ,

. ,

. ,

< >.
, .
.

, rd.
, .
. 9.6.
.1 ,
-

Chapter 9.

(www.courseptr.com/downloads)

playing_cards. .


, .
Card, ,
, :

259

9.6.

_str _(),

- -

# 3.0
#
class Card(object) 1 :
.

RANKS
SU IS

["" .

= [

"2". "3". "4". "5" . "6". "7". "8". "9". "10". "J". "Q".
"" . "d " . "h" . "s " J

""]

def

init <self. rank. suit):


self.rank = rank
self.suit = suit
def _str_(self):
rep = self .rank + self .suit
return rep

Card , (
) . :
class

Unprintae_Card(Card) :

Unpri ntab l _ rd

rd. ,

. :

"""

def _str_(self):
return "<

"""

>"

Python 3 object, 2- .
, object 2- .
object. - . . .

260

9.

- . -

Unpri nta _ rd _st r_ ( ) rd. Unpri ntab l _


( ) , (

rd _st r _

) . ,
, ,
, .

Unprintae_Card < >.

,
, -
. -.
,

rd



. ,
rd. ,
, , .

Card, ,
i s_face_up.

, -,

, , ,

ra nk su i t. rd :

, ,

rank

suit

,
.

Pos i t i ona _ rd:

cl ass Pos iti n _ rd(Card):


'"'" . n .
def init (self. rank. suit. face up = True):
super(Positionae Card. self).- init (rank. suit)
self.is_face_up = face_up

super()

r . super<Positionae_Card. sel f) ._init_(rank.


su i t) 1 _i ni t _ ( ) ~d, Pos i t i n _
rd .

- _ i nit_ ( rank. suit) -

-
,

rank suit.
Pos i t i ona _ rd (
) , Card:

def

str (self):
if self. is face up:
rep = ~uperIPositionae Card. self).

str

super() .

()
. . .

261

else:
rep = ""
return rep
_str_() is_face_

up.

True,

, .

_str_() Card,

Positionae_Card. , ,

, rd.
, , .

, :

def flip(self):
self.is_face_up = not self.is_face_up
,

i s _face _up

. True, fl i ()

Fa 1se, ,
True.

Fa 1se,

fl i ()


:
Unprintae_Card, ,

rd,

Positionae_Card:

cardl
card2

Card("A".

"")

= Unprintae_Card("A".

card = Positionae_Card("A".

"d")
"h")


rint("

Card:

Card:")

pri nt ( rdl)
, .

Unpri ntab l _ rd:

print("\nneaa Unprintae_Card:")

print(card2)
rank "", suit -
"d", : <
>, Unprintae_Card

_str_()

"< >".

Positionae_

Card:
pri nt( "\n
print(card)

Pos i t i n e_Card: ")

262

9.

- . -

(i s_face_up = True},
_str_) _str_) Card,
Ah.
fl i () Positiona e_Card:

Card. ")

rint" Positionae

rd. fl i ()

is_face_up
Pos i t i n

.
rd:

print("\neaa Positionae_Card:")

pri nt ( rd)
input("\n\nHae

Enter.

.")

,
.

, ,
,

. ,

Unpri nta _ rd rd, ,


Unpri nta _ rd, ,
_ st r_ ) rd.
_s tr _

()

, , ,
: Unprintae_Card

Card.
_str_(),

, ,
.


random
" " 3.
Python , ,
.
.

-, , ,

. , , rd,

Hand
Deck ,

,
.

263

-, ,
.

; , .
(

) .

, , .
, I-
.

-, , .

, , ,

, ,

Python.

r r
, , .
, ,

, ,

, . ;

, .

. .

9.7.

9.7.


~ ~.
, ,
, .

264

9.

- . -

Python.

,
(, ), ,
, .
games
, .
- (courseptr.com/downloads) Chapter

#
#

9.

games . .

class PlayerCobject):
""" . """
def _init_Cself. name. score = 0):
self .name = name
self.score = score
def
str Cself):
rep =self.name + ":\t" + strCself.score)
return rep
def ask_yes_no(question):
"""

''

'."""

response = None
while response not in ("". "n"):
response = input(question).lower()
return response
def ask_numerCquestion. low. high):
""" ."""

response = None
while response not in range(low. high):
response = intCinputCquestion))
return response
if name == " ma i n " :

printC"B . .")

input("\n\nHae

Enter. .")

games,
games . .

. ;

. Player
: name score, -. , ,

_str_), .
- ask _yes _no() ask _number() -

q "-"

6.

,
.

i f _name_ == "_mai n_"

, .

, . ,
games . ,
, .

265

games, <1

. ,
-

Chapter 9.

#
#
import games. random

(www.courseptr.com/downloads)

simple_game. .

import , ,

, . ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~~

, , , ,
, Pytho . . ,

, , ,
, .
, .
, , .


<1
.

, :
printC"opo - !\n")

again = None
while again != "n":
players = []
num = games .ask_number(question = "
high = 5)

(2 - 5): ". low = 2.

, ask_number()

games.

, ,

: _. _.

1 100

randrange()

random)

. ,

Pl ayer. games,
, .
- .
for i in range(num):
name = input(" : ")
score = random.randrangeC100) + 1
player = games.Player(name. score)
players.append(player)

266

- . -

9.

:
print("\nBo :")

for player in players:


pri nt Cpl ayer)

ask_yes_no()

games ,

again

games.ask yes

n("\n ?

input("\n\nHae ntr.- .")

(y/n): ")

&-
,

Python,

, ~- .

, , (,

).

cards

-~- ~
rds.

Hand Deck , 2.0i-,


Pos i t i onab1_ rd 3.0i-.

rd

- ( courseptr.com/downloads)

Chapter 9.

cards. .

# cards
#
class Card(object);
"'"' . """
RANKS
SU 1TS

def

"2". "3". "4". "5".


. "d" . "h" . "s" J

= ["".

= [ ""

"".

"7". "8". "9". "10". "J",

rank. suit. face_up = True):


self. rank = rank
self. suit = suit
self.is_face_up = face_up
def str (sel f):
if self.is face up:
rep = self.rank + self.suit
else:
rep = ""
return rep
def flip(self);
self.is face up = not self.is_face_up
class Hand(object): """ : .
def ~init~(self);
self.cards = []
~init~(self.

"".

""]

267

def

str (self):
if self.cards:

rep = ""
for card in self.cards:
rep += str(card) + "\t"
else:
rep = "<>"
return rep
def clear(self):
self.cards = [ ]
def add(self. card):
self.cards.append(card)
def give(self. card. other_hand):
self.cards.remove(card)
other hand.add(card)
class Deck(Hand):
'"'" .
def populate(self):
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank. suit))
def shuffle(self):
import random
random.shuffle(self.cards)
def deal(self. hands. per_hand = 1):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[OJ
self.give(top_card. hand)
else:
print("He :
if name
" main ":

!")

print"'o . .")
input("\n\nHae

Enter.

.")


,
, . , ,
.

- .
n

&

9.1.

9.1.

J_carc1

carcls.card

-.
value - ,
.-

268

9.

- . -

9.1

()

&
IUl8CC

J_Deck

cards.Deck

-.

BJ_Card
-. : name, , total,

J_Hand

cards.Hand

J_Player

J_Hand

J_Dealer

J_Hand

( -)

J_Game

object

-. : deck - J_Deck, dealer - J_Dealer players,


J_Player

, , ,

, ,
: ( ). r

,
.

,
, .
.

9.8.

cards.Card

cards.Hand

cards.Deck

BJ_Card

BJ_Hand

BJ_Deck

BJ_Player

9.8.

BJ_Dealer

, , . 9.8,
.

. ,
. :

269

f<

.


.

cards

games

, , .

-),) :

cards games.
,
- (www.courseptr.com/downloads) Chapter 9.
ackjack. .

#
#

-
1 7

import cards. games

games,

, ,

B_Card

BJ _Ca rd rds . rd.


BJ_Card value, :

cl ass

J_Card(cards. Card):

"""

-.

VALUE

"""

@property
def valueCself):
if self. is_face_up:
v = BJ_Card.RANKS.indexCself.rank)

270

9.

- . -

if v > 10:

v = 10
else:
v = None
return v

va l ue

1 1 -

. J _ rd. RANKS.

i ndex ( se1f. rank). rank -,


"6" ),
BJ _ rd . RANKS ( 5 ).

(,

, ( ,

"6" 6). ,
1; 1
. is_face_up False,
None.

n J_Deck

BJ_Deck

--.

rds. Deck.
,

BJ_Deck

cards. Deck' s popul ate( ),


BJ_Card:

class BJ_Deck(cards.Deck):
""" "-".

def populate(self):
for suit in BJ Card.SUITS:
for rank in BJ Card.RANKS:
self.cards~append(BJ Card(rank. suit))

n J_Hand
BJ _Hand, rds. Hand,

~.

-~.

name,

cards .Hand,

~:

class BJ Hand(cards.Hand):
""" 7 ':

"-" .

def _init_Cself. name):


superCBJ_Hand. sel f) ._init_()
self.name = name
_str _(),

def _str_Cself):
rep = self.name + ":\t" + superCBJ Hand. self)._str_()
if self.total:
rep += "(" + strCself.total) + ")"
return rep

271

name ,
cards. Hand _ str_ () . tota l
None, .
.

tota l,

. 4 , ,

None.

, , 4.

@property
def total(self):
#

value

None.

None

for card in self.cards:


if not card.value:
return None
1

# .

=
for card in self.cards:
t += card.value

#.

contains_ace = False
for card in self.cards:
if card.value == BJ_Card.ACE_VALUE:
contains = True

# 11. 11

if contains and t <= 11:


# 10.
t += 10
return t
,
va l ue, None ( , ).
,

None.

. ,
. , ( ),

def is_busted(self):
return self.total

>

BJ_Hand

1 11.

i s_busted( ).
True, total 21.
Fal se.

21

se l f. tota l

>

21

return

(, )
.

272

9.

- . -

, ,
True F l se. ,
( ,
).

is (

s_on () ).

BJ_Player

J _Pl ayer, J _Hand,


:

class BJ_Player(BJ_Hand):
"""

"-".

def is hitting(self):
response = games.ask yes no("\n" + self.name +"

(Y/N): ")

return response == ""


def bust(sel f):
print(self.name. ".")
self.lose()
def lose(self):
pri nt (self. name. ".")
def win(self):
printCself.name. ".")
def push(self):
printCself.name. "

- i s_hitt i ng() -

.")

True ,

, Fa l se - . bust () ,
, lose() . , lose()
, , wi nC) - . ,

push() . bust(), lose(), win() push()

, .
,
, , (

).

BJ_Dealer

BJ_Dealer, BJ_Hand,

class BJ_Dealer(BJ_Hand):
""" "-".

def is hitting(self):
return self.total < 17
def bust(self):
pri nt ( se lf. name. . )

273

def flip_first_card(self):
first_card = self.cards[OJ
first_card.flip()
- i

s_hi tt i ng ( ) -

. , 17 ,
, True, tota l
17, Fal se. bust() ,
. , fl i p_fi rst _ca rd()
.

BJ_Game
BJ_Game

(!-".

play()

. , ,
,

_ add i t i ona l _ rds ( ),

st i l l _p l ayi ng,

, .

_init_()

, .

class BJ_Game(object):
"""

-.

"""

def _init_(self. names):


self.players = []
for name in names:
player = BJ_PlayerCname)
self.players.append(player)
self.dealer = BJ_Dealer("Dealer")
self.deck = BJ_Deck()
self.deck.populate()
self.deck.shuffle()

still_playing
sti l l_pl ayi ng

( ):

@property
def stil l_playingCself):
sp = [J
for player in self.players:
if not player.is_busted():
sp.appendCplayer)
return sp

274

9.

- . -~

_additional_cards()

_additional_cards( )

player

BJ_Player

BJ_

i s_busted() Fal se,


i s_hitting() True, .

Deal er.

is_busted() True,
bust().
def additional cards(self. player):
while not player.is busted() and player.is hitting():
self.deck.deal(fplayer))
print(player)
if player.is_busted():
l ayer. bust ()
. -,

player. is_hitting() ,
player: J_Player J_Dealer. _additianal_cards() ,
. -, J _Pl ayer J _
Dea 1er bust (), l ayer. bust ()
.

play()

l ( )
:

def play(sel f):


# 2
self.deck.deal(self.players + [self.dealerJ. per hand = 2)
self. dea l er. fl i p_fi rst_card() # . .

for player in self.players:


print(player)
print(self.dealer)
#
for player in self.players:
self. additional cards(player)
self.dealer.flip first card() #
if nat self.still playing:
# . ""

print(self.dealer)
else:
#

print(self.dealer)
self. additional cards(self.dealer)
if self.dealer. is-busted():

# .-

for player in self.still_playing:


player.win()
else:

275

-
# . ;

for player in self.still playing:


if player.total > self.dealer.total:
pl ayer. wi n()
elif player.total < self.dealer.total:
pl ayer .1 ose()
else:
1ayer. push ()
#

for player in self.players:


pl ayer. cl ear()
self.dealer.clear()
. ,

, ,
. <11> .

,
. ,
<1~>.

. ,

17. ,

. ,

, ,

main()

ma i ( ) ,
BJ _Game, .
l ( ) ,
.

def main():
print("\t\topo -!\n")

= 8)

names = []
number = games.ask_number("Coo

for i in range(number):
name = iut(" : ")
names.append(name)
print()
game = BJ_Game(names)
again = None
while again != "n":
game. l ()
again = games.ask_yes_no("\nXoe
main()
iut("\n\ Enter. .")

(1 - 7): " low

")

1. high

276

9.

- . -

. ,

.
.

. ,

.
.
,
.
, .
'

'r

'~

n- . .

n. n , n n n .
, n n.

, : m
, , n .
- , . n
- , .

n - ,
, , .

10

<<
>>
, ,

.
.

(GUI) -
GUI

.
GUI. , :

GUI;

;
;
.

,.

'!>,
, .
,

. ,
. . 10.1-10.3. ,
~

GUI.

278

10.

11 1! 1~,n...,i

7~ 11
~ r 3

:
. .:

11>11>:

1
1
1

l4 (-):

n11

11!8011

pa<(J(o

nr !

-- - -

-- - -

-- -

10.1 . GUI
1 > .\ @) i._,,a.d

7~ l\
n !
8t<:~;
. . :

11:
nn (-):

!
l
!!
J;1' nl

/;1

r.

(' nG

pac(J(o I

'

_..

_____

--

--~

-- - -

10.2.

--

7'
n

. .:

~!__
n-__
_
_ _ __

11111111:

!!

11 (-):

'

j'; n1138811

(' nano

n1

11

ceoeti - n
, , , ~. ~<!
11 . 1 f180J ,

t'! . n~. , HI!


. nepewn11 ~ 1
. ? J .

10.3.

GUI

279

GUI

GUI,

. .

10.4

8J1 R 311

,..,

_
_ __

111 :
11.n . .:

r :

1l

r -~):

w n11~

r.

611W11 u r

!
t+< ! :
, I<, , ..
J1.1

"111t1. J n111J n1'13, 1'1

11

wy nyew ~-11. not1Ctc:OD 1 :11.


w
r n . f\f1-t

. d? , ~ )

GUI.

10.4.

GUI

Python,

Tkinter.

~~~~~~~~~~~~~~~~~~~~~~~~

Windows,

- ,

kinter , ,

. kinter

Python: http://www.python.org/

topics/tkinter.

GUI Tkinter.

10.1

10.4,
n

tki nter,

GUI,

tkinter.

10.1. GUI

Frame

Lael

, -

tkinter

n n

GUI

.,

280

10. .

llacc

Button

tkinter

10.1

()


n <r -

Entry
Text
Checkbutton

Radiobutton

~~~~~~~~~~~~~~~~~~~~~~~~

. ,
.

GUI, , -.

. - ()

, .

GUI (, ),

- .

, ~
. ,

Python,

, ,
input( ). ,
, . .

, . ,
,

GUI,

.
.

(, )
(, ).
. ~

( ), ,
( ).
, , .

, ,
. , U1',
.
,
.

281

GUI

. , ,
- .

, ,

GUI

GUI.

, . <:<

~ ,
.


GUI
GUI~ , ,

: . .

10.5.

' '"?-' npocreiiii GUI l 0 1@J lii4"'tJ '

10.S.

- .
- , ?

~~~~~~~~~~~~~~~~~~~~~~~~~~

Tkiter

IDLE, , IDLE .
Windows

, ;
.

~~~~~~~~~~~~~~~~~~~~~~~~~~

,
: , ,
.

Windows ,

,
. , ,

simple_gui.py,

simple_gui.py
pause
, .
, , (

WordPad).

Word

. . t (, simple_gui . t) .

, .t

.txt.

.
-

(www.courseptr.com/downloads)

Chapter 10.

282

10. .

, .

10.5,

GUI
-
. 10.6.

( )
,

10.6.

GUI,

. ( )

Tkinter ,
GUI

. ,

.
~~~~~~~~~~~~~~~~~~~~~~~~~~

GUI-, , ,

.
. .pyw.

Windows,

(www.courseptr.com/

downloads) Chapter 10. simple_gui . .


tkinter

GUI

#
#

tkinter:

GUI

from tkinter import *

tk i nter
. , -

283

GUI

, tki nter, .

, .

r
, Tk tk i nter:

root = TkO
, tkinter Tk
. , tk i nt.er .

,
, .
~~~~~~~~~~~~~~~~~~~~~~~~~-

l<inter .

, , .

r
,
:

rt.titl("

GUI")
root. geometry( "200100")

title() . ,

.
"

geomet ry

GUI ".
)

( ) ,

200 , - 100 .

r r
mainloop(),

root. mai nl ()
,
. ,

. ,
, .
; simple_gui. bat.

284

10. < .

. ,

GUI

/ ,

. ~~

- , .
, :

, . ,

. ,
.

Labe1,

. .

10.7.

74 , '"'

' ~!
.

10.7.

downloads)

Chapter 10.

GUI

(www.courseptr.com/

labeler. .

tki nter

.
# .

#
from tkinter import *
#
root = Tk()

root.title("o . ")

root .geomet ry ( 20050")


, .
, .
, :

= Frame(root)

285

,
, . -

Frame root. ,
.

grid()

app.grid()

grid()

. .

, .

,
.

Label:

= Label(app. text

=" !")

Label

.
."1,
. . ,

text

gridC)

",

!.

-:

.grid()

GUI.

GUI:

root.mainloop()

Button,

. , ,

286

10. .


~ , ,
, .

. ,
. .

10.8.

downloads)

Chapter 10.

10.8.

(www.courseptr.com/

l azy_buttons. .


, ,

#
#

tki nter, :

from tkinter import *


#
root = Tk()
rt . titl(" ")

root. geomet ry ( 20085 )


#

Frame(root)
app .grid()
=

Button.

bttnl = Button(app . text


bttnl .grid()

= !")

!.

; ,

, tk i nter . ,

GUI

287

, . ,
, , .
, .

#
bttn2 = ButtonCapp)

ttn2.grid()

, :

. ,
. . ,

configure( ):

ttn2.configureCtext =" !")

text "
configure()

! ",

.
.

ttn

= Button(app)

ttn.grid()

text

bttn["text"J =" !"

text

. " ! ",
!. (~),
, .

GUI

#
root. mai nl ()

GUI

,
.
. , ,
GUI-, .

288

10. .

- 2 -

- 2

. , ,
.

' 7~ 61113 ~ 2

10.9.

10.9.
[

=1

@J

1 d'

-. ,
,

downloads)

Chapter 10.

(www.courseptr.com/

lazy_buttons2. .

tkinter

- :

- 2
#

from tkinter import *



tkinter

Application
Appl ication, Frame:

class Application(Frame):
GUI-

Frame,

l i cat i on, .
, l i cat i on

-
l i cat i on :

def _init_(self . master) :


" . "
super(Application. self) ._init_(master)
self.grid()
self .create_widgets()
. l i -

cat i on ();

GUI

289

, . create _

widgets( ), .

, r

create_wi dgets ),

def create_widgets(self):
"""

self.ttnl = Button(self. text


self.bttnl.grid()

"""


= " !")

self.ttn2 =

Button(self)

self.ttn2.grid()

self.ttn2.configure(text =" !")

self.ttn

= Button(self)

self.bttn.grid()
self.ttn["text"J =" !"

,
4 .

bttnl, bttn2

ttn

1i cat i on.

se 1f,

, 4 1i cat i on.

Application

,
:

root

TkO

root.titleC"ecnoee

- 2")

root .geometry( "20085")


l i t

i on

root:
=

Application(root)

1i cat i on

root.

create_widgets( ), , ,

1i cat i on .

, , ,

GUI:
root.mainloop()

290

10. .

GUI-, , .
,

. ,

, ~> .
GUI- ,
.


:~- : ,
. ,

()

. .
7~ we1Nk0&

11111 : s

=1

@)

10.1.

\..,.--& .;,,J

10.10. ,

downloads)

Chapter 10.

(www.courseptr.com/

cl ick_counter. .


- :

#
#
from tkinter import *

l i cat i on:

class Application(Frame):
GUI-.
def _init_(self. master) :
""" . "'"'
super(Application, self) ._init_(master)
sel f .grid()
self.bttn_clicks = #
self .create_widget()

. ,

sel f . ttn_cl icks


.

= , ,

291

Grid

create_widget() :
def create widget(self):
""" . -

self .bttn = Button(self)


self.ttn["text"J= " : "

self.ttn["command"J

self.ttn.grid()

= self.update count
-

comand

update_count ( ).

, li .

, " ( ) (
upda te_count ( ) ). comma nd
, -.

update_count ( ), :
def update count(self):
""" . '""'
self.ttn clicks += 1
self.ttn["text"J = " : " + str(self.bttn_clicks)


,
. , - .

#
root = Tk ()
root.title("Koeco ")

root. geometry( "20050")


= Application(root)
root.mainloop()

root, .
root.
, GUI .

1i cati

.
Grid
GUI- ,

- .

292

10.

. r

. :
, ,

. ,
. ,
.

,
.

Grid,

Grid
GUI.

100 ,
secret.

, , ,
. .

l ::> 11;;] ~..,,

'7~ r:1G1<

10.11

10.12.

.,,j

! !I

. 1
,

10.11.

'74

i=l!;;JJ..13 ,,

/secret

. 1

100 ,

99,

10.12.

, ,

downloads) Chapter 10.

longevity. .

(www.courseptr.com/

293

Grid

r r
, :

#
#

Grid

from tkinter import *


class Application(Frame):

""" GUI - .

"""

def _init_Cself. master):


""" . """
super(Application. self). init (master)
self.grid()
self.create_widgets()
tkinter Appl ication.
- l i cat i . ,
,

create_widgets( ).

Grid

create_widgets()
:

def create_widgets(self):
""" .

"""

sel f. inst_l = Label (sel f. text =

" .

")

, ?

Grid

, :

self.inst_l.grid(row =.

column

=.

columnspan = 2.

s~icky

= WJ

grid() .
:

row

row, col umn, col umnspan

sticky.

1umn

.
,
.
~, . .

10.13

.
row 1umn
. .
( :

), ,
. 1umnspan

294

10. .

, .

:

2,

, ,

1 (

rowspan

).

Grid

= 11J l""'a,.J

row=O
column=

row=O
column= 1

rowO
column 2

row= 1
column=O

row=I
column= 1

row= 1
column 2

row=-2

row=2
column = 1

rowZ
column = 2

7~ ~: "~

column =
.

10.13.

row

column

( ),
,

(W).

(N),

sticky. ,

(S),

sticky -,

()

( ),

,
:

self.pw

self.pw-l

= Label(self. text = " : ")


.gridCrow = 1. column = . sticky

W)

#
self.pw_ent = Entry(self)

- Entry:

, .

,
:

self.pw_ent.gridCrow

1. column

1. sticky

W)

self.submit_bttn = Button(self. text


reveal)

" " .

command

self .

r r.

295

Grid

revea l (),

, .

self.submit_bttn.grid(row = 2. column = . sticky = W)

r o6nacr

- Text:

# .

self.secret_txt

Text(self. width = 35. height = 5. wrap = WORO)

wrap

wi dth hei ght,

- WORD, CHAR NONE.


WORD ,
, . CHAR

:
. ,

NONE

.
,

~ ~:

self .secret_txt.grid(row = 3. column = . columnspan = 2. sticky = W)


r : r

revea l (),

. ,
, , , .
, .

get() Entry:
def reveal(self):

contents = self.pw_ent.get()

~.

"""

get ( ) .
Text. , secret. ,
(, message)

Entry,

100 .

, .

if

contents == "secret":
message ="

100

99. " \

" ."

else:
message =

" .

" ."

"\

296

10. .

, , .

. ,
Text.

delete( ):

self.secret_txt.delete(0.0. END)
.
: . 4"

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

- -

.
tk i nter , ,

END,

. ,

delete()

Text, Entry.

, , :

self.secret_txt.insert(O.O. message)

i nsert ()

: .
, 4~ . , .

message,
i nsert () .

~~~~~~~~~~~~~~~~~~~~~~~~~~

insert() , .
, delete().


,
. l i cat i , .
, , .

#
root = Tk()
rt.titl("")

root. geometry( "300150")


= Application<root)
root. mai nl ()



, .

297

,
.


~
: , , .
,

, . .
.

7/J

10.14.
i= l @Jl... ."J


, :

" >t

'
.

s .

10.14.

downloads)

Chapter 10.

(www.courseptr.com/

movie_chooser. .

#
#

tki nter

i cat i on:

from tkinter import *


class Application(Frame) :
""" GUI-.
def _init_(self. master):
super(Application. self)._init_(master)
sel f.grid()
self.create_widgets()

"""

, :

def create_widgets(self) :
'"'" .

"""

298

10. .

LabelCself.
text = " ~ "
).grid(row =. colLmn =. sticky = W)
, , :

Label .
, ,

tkinter
Labe1, ,

, .

. ,
, .

. - ,

Labe 1 ,

LabelCself.
text = " . :"
).gridCrow = 1. column =. sticky = W)
,
.

, .
, ,
.
~ BooleaVar

tkinter.

BooleanVar

1i kes_comedy, :
# ""
self.likes_comedy = BooleanVar()
()

. n . n-r w11 ,

CheckbuttonCself.
text ="".
variae = self.likes_comedy.

299

= self.update_text
).grid(row = 2. column =. sticky

cornand

W)

, .

se l f. 1i kes _comedy
date_text( ),

va ri 1, ( <~:-.
l ikes_comedy. command self .up-

<~:)

( )

update_text ( ). .

, Checkbutton .
,

likes_comedy.
:

" "
self.likes_drama = BooleanVar()
Checkbutton(self.
text = "".
variale = self.likes_drama.
cornand = self.update_:ext
).grid(row = 3. column =. sticky = W)
# " "
self.likes_romance = BooleanVar()
Checkbutton(self.
text = " ".
variale = self.likes_romance.
command = self.update text
).grid(row = 4. column =. sticky = W)

,
,

Checkbutton

update_text( ).

- ,

1i kes_drama, -

1i kes_romance.

, , :

#
self.results_txt = Text(self. width = 40. height = 5, wrap = WORD)
self.results_txt.grid(row = 5. column =. columnspan = 3)
r

update_text( ),
,
:

def update_text(self):
""" .

"""
likes = .".
i f se l f. l i kes _comedy. get ( ) :

300

10. < . <

likes += " .\n"


self.likes_drama.get():
likes +=" .\n"'
if self.likes_romance.get():
likes +=" ."
self.results_txt.delete(O.O. END)
self.results_txt.insert(O.O. likes)
if

BooleanVar :
get ( ) . get ( )
1eanVa r, l i kes _comedy, ,
. True,
" . \n" ,

.
. ,


,
1i cat i , .

#
root = TkO
root.title("Koa")

= Application(root)
root. ma i nl ()


,
. , ,
.
.


-2
4'-2 .

, ,
, .
,
.

10.15.

downloads)

Chapter 10.

(www.courseptr.com/

movi e_chooser2. .

301

' 71.

t.-2

[!@ !!;~~~

rr

11 .

10.1 S.

#
#

tki nter:

-2

from tkinter import

Appl ication.

1i cat i :

class ApplicationCFrame):

""" GUI -.
def _init

"""

."."

Cself. master) :

"""

superCApplication. self) . init Cmaster)


self.grid()
self.create_widgets()
,
:

def create_widgets(self) :

."". .
# -

."".

Labe 1 se lf .
text = " "
).gridCrow =. column = . sticky = W)
# -
Labe 1 se lf .
text =" :"
).grid(row = 1. column =. sticky = W)

, ,
, , , .

StringVar

tkinter.

302

10. . <

. ,

, StringVar,
. favorite

set()

#
self.favorite = StringVar()
self.favorite.setCNone)

None:

# ""
Radiobutton(self.
text = "".
variale = self.favorite.
value ="..
command = self.update_text
).grid(row = 2. column =. sticky

W)

va ri 1 se l f. favori te,
val ue , ,
. va l ue

". ", , ,

StringVar,

self. favorite,

".".

# ""
RadiobuttonCself.
text = "".
variae = self.favorite.
value =".".
corrnnand = self.update_text
).grid(row = 3. column =. sticky = W)
# " "
Radiobutton(self.
text = " ".
variale = self.favorite.
value =" ..
command = self.update_text
).grid(row = 4. column =. sticky = W)
va ri l se l f. favori te, value- ".". ,
StringVar, self. favorite,

"."
.

#
self.results txt = Text(self. width = 40. height = 5. wrap
self.results-txt.grid(row = 5. column =. columnspan = 3)

WORO)

303

JJ


, get ( )
Stri ngVar:

def update_text(self):
"'"' .
message = "
message += self.favorite.get()

,
".",
,

se 1f. favori te. get ()

".". ,

sel f. favori te.get()

" '1.

".

, , , ,

self.results_txt.delete(O.O. ENO)
self.results_txt.insert(O.O. message)


, 1i cat i on,

GUI.

#
root = Tk()
root.title("Koa-2")

= ApplicationCroot)
root. mai nl ()

, ,

GUI.

~ ~

, .

(www.courseptr.com/downloads)

Chapter 10.

mad_l ib. .

tkinter

, , , ,
:

#
#
from tkinter import *

tki nter,

304

10. .

Application

Appl ication create_widgets( ):

class Application(Frame):
""" GUI-n.
def ~init~(self. master):
""" . """
superCApplication. self). init Cmaster)
self.grid()
~
~
self.create_widgets()

create_widgets()

GUI

"""

Application

, u,

, ,

def create_widgets(self):
"""

text va 1ue:

# -
LabelCself.
text = " "
).grid(row =. column =. columnspan = 2. sticky = W)
#
LabelCself.
text = " : "
).grid(row = 1. column =. sticky = W)
self.person_ent = Entry(self)
self.person ent.grid(row = 1. column = 1. sticky = W)
#
Label Csel f.
text = " . . : "
).grid(row = 2. column =. sticky = W)
self.noun ent = Entry(self)
self.noun-ent.grid(row = 2. column = 1. sticky = W)
#
Label(self.
text =" :"
).grid(row = 3. column =. sticky = W)
self.verb_ent = Entry(self)
self.verb ent.gridCrow = 3. column = 1. sticky = W)
#
Label(self.
text =" (-):"
).grid(row = 4. column =. sticky = W)
# ""

self.is_itchy = BooleanVar()
Checkbutton(self.

text

305

= "",

= self.is_itchy
).grid(row = 4. column = 1. sticky

variae

= W)
# ""
self.is_joyous = BooleanVar()
Checkbutton(self.
text = "".
variale = self. is_joyous
).grid(row = 4. column = 2. sticky = W)

"1"

self.is electric = BooleanVar()


Checkbutton(self.
text = "".
variale = self.is electric
).grid(row = 4. column = 3. sticky = W)
#
Label(self.
text = "Body rt:"
).grid(row = 5. column =. sticky = W)
# n.
se 1f. body_part = Stri ngVar()
self.body part.set(None)
# n
body parts = ["n". " ". "n "]
column = 1
for part in body_parts:
Radiobutton(self.
text = part.
variale = self .body_part.
value = part
).grid(row = 5. column = column. sticky = W)
column += 1
#
ButtonCself.
text = " ".
command = self.tell_story
).grid(row = 6. column =. sticky = W)
self.story txt = Text(self. width = 75. height = 10. wrap = WORO)
self.story=txt.grid(row = 7. column =. columnspan = 4)

tell_story()

Application

, ,

, , , ,
.

def tell_story(sel f):


"'"'
."""

10. .

306

# get values from the GUI

person = self.person ent.getC)


noun = self .noun ent~get()
verb = self.ver=ent.get()
adjectives = ""
if self.is_itchy.get():
adjectives += ". "
if self.is_joyous.get():
adjectives += ". "
if self. is electric.get():
adjectives += ". "
body part = self.body part.get()
# story = " "
story += person
story += "
.

story
story
story
story
story
story
story
story
story
story
story
story
story
story
story
story
story
story
#

+=
+=
+=
+=
+=
+=
+=
+=

noun.titleC)
". "
noun
" "
person + "
". "
adjectives

"

"

" .

+=" .

+=
+=
+=
+=
+=
+=
+=
+=
+=

person
" .

"

" + body_part + "

"

"

noun
" .
person + "

"

"?

verb
".

"

"

."

self.story txt.delete(O.O. ENO)


self.story=txt.insertCO.O. story)
r
.
l i cat i on,

mainloop()

#
root = Tk()
rt.titl(" ")

= ApplicationCroot)
root. ma i nl ()

307

. ~

-
.
, , , ,
. ,

Gri d.

- . ,
- GUI.

>>,
11 .

3: .
, !.
, .

11

.
<< >>

, ,

.
. ,
,

Python.

;
;

;
;

, ;
.


, ,
. :

.
, :
.
.
,

, . . 11.111.2.

pygame l i vewi res

pygame

livewires

),

Python

, , . .-

pygame

309

livewires

11.1 .

11 .2.

310

11.

, .

pygame 1i vewi res, r

, , ,
r

. r r.
r.

pygame, (Pete Shinners), - ,

Python .

, .

, l i vewi res - ,
r, , ,
pygame, .
1i vewi res
.

pygame,

1i vewi res

.
, ,

pygame l i vewi res.


(www.courseptr.com/downloads) Software.

, .
~~~~~~~~~~~~~~~~~~~~~~~~~~-

UveWires (http://www.tivewires.org.uk),
, LiveWires livewires,
-. ,
. , ;
.

pygame, http://www.pyga-

me.org.


, 1 -

<11>, .

l i vewi res. <1 , ,


. .

11.3.

<1r :1> <11'J) :1>


.

. .

311

11.3. . ,

~~~~~~~~~~~~~~~~~~~~~~~~~~

, n kinter,

livewires

IDLE.

Windows,

. ,
" GUI" 10.

downloads)

Chapter 11.

1i vewi res

(www.courseptr.com/

new_graphics_wi ndow. .

games

games,

.
- ,

from.

from,

import

, ).

#
#

1i vewi res:

from livewires import games

games

312

11.

games ,

games

. 11.111.2.

, .
6111

11.1. games

scree

(graphics scree)- ,
, r

mouse
keyboard

6111

11.2. games

Sprite

01

Text

Sprite.

, -

Message

Text.

games.init(screen_width = 640. screen_height = 480. fps = 50)


i ni t ()

games

. ,

screen _wi dth, , , screen_hei ght.

, .

,
~),

fps

( frames

per second -

games.screen.mainloop()

games,
mainloop() fps
. , ,

screen -

11.4.

screen

50 .
11.3,

313

11..

width
height
fps
back.ground
all ojects
event_grab

screen

n ( )

,
, , n
. , True, - False

11.4.

add(sprite)

Sprite

screen

( )

d()

mainloop()
quit()

. - .
screen , Ji.


" ~

" ~.

. 11.4,
.
4' ~. "
~. mainloop( ).
-

downloads)

Chapter

11.

(www.courseptr.com/

background_image. .

#
#
from livewires import games
games.init(screen_width = 640. screen_height = 480. fps = 50)
wall image = games. load image("wall .jpg". transparent = False)
games.screen.background-= wall_image
games.screen.mainloop()


- ,

314

11. .

.
, :

wall _image

games. load_image("wall .jpg". transparent

False)

<~ pygame window

11.4.

background screen

l oad_image() games,
wa l l . j pg -

wa l l _i mage.

~~~~~~~~~~~~~~~~~~~~~~~~~~

, , ,

7.

, ,

, , .
, .

load_image() : () -
- transparent.
, , , transparent.

, ()

transparent

False.

, , ,
JG.

l oad_ image() -

315

. ,
,

GIF, PNG,

TGA.


- -
, background screen.
:

games.screen.background

wall_image

wa 11 _i mage.

n1( ) ,

r
, ,

480 ;

640

.
640

480

, . , r

, : ( ) (
).

,
, (; ).

. ,

, ,

(639; 479). . 11.5


Game Over,

. ,
.


, ,
, , , ,
.
, .

316

11.5.

11. .

,
. ,
, .
, <:< :
,

.
. , I-

Microsoft Office

. ,

. (!.

Microsoft , , Office 2007 .

: ,

, .

,
, :

317

01

-
-, ,
,

.
.

11.6.

mainloop()

. -

(www.courseptr.com/downloads) Chapter 11. pizza_sprite.py.

11.6. -

, ,

#
#

Sprite

from livewires import games


games.init(screen width = 640. screen height = 480. fps = 50)
wall_image = games.load_image("wall .jpg". transparent = False)
games.screen.background = wall_image
pizza_image = games . load_image( "pizza .bmp")
pizza = games.Sprite(image = pizza_image. = 320. = 240)
games.screen.add(pizza)
games .screen .mainloop()

318

11.


,
-:

pi zza_i mage

games .1 oad_image( "pi zza. bmp")

:
transparent.

True,

, , .
-
, .

transparent,
, .
, , :
.

11.7 .

11.7. .

transparent,

, ( , ),
;

. .

11.8 ,

, ~ .

, ,
,
.
~~~~~~~~~~~~~~~~~~~~~~~~~

, , ,
. ,

, , .

pizza

games.Sprite(image = pizza_image.

= 320.

240)

319

11.8. -

trasparet, True,

False

Spri te
(320; 240 ), .
pizza. Sprite,

, () ().


, ,
. :

games .screen.add(pizza)

add()

~~~~~~~~~~~~~~~~~~~~~~~~~~

, . ,


- .
. , .

, .
, . , -
.
, , , ,

: ,
. ,
,

320
.

11.5 11.6

11.

Sprite,

, , .

11.5. Sprite

it

angle

dx

dy
left
right
top

01

ottom

01

image

-, 01

over1appig_sprites

is_collideae

, , ,

11.6.

Sprite

update()

.
mainloop()

destroy()

r
- ,
, -
. : games

Text.

r
!
,
Text. 4 !,
4 ,
, , .
, .

11.9.

321

11.9. Text

downloads)

Chapter 11.

(www.courseptr.com/

bi g_score. .

# !

#
from livewires import games . color
games .init(screen_width = 640. screen_height = 480. fps = 50)
wa 11 _i mage = games .1oad_ i mage( "wa 11 . jpg". transparent = Fa 1se)
games.screen.background = wall image
score = games .Text(value = 1756521.
size = 60 .
color = color.ack .
550.
= 30)
games.screen .add(score)
games.screen .mainloop()
=

livewires,

color

games,

color,

, .

Text

Message

322

11.

( ,

l i vewi res ).

color.
i mport :
from livewires import games. color

l i vewi res

1or

games.

Text

Text .
mai nl ( ), Text score:

score = games.Text(value = 1756521.


size = 60.
color = color.ack.
= 550.
= 30)
- Text

: , , , ,
.

val ue 17 56521. ,
(, va 1ue, Text
). s i ze 60 -
. , .
1or 1or.1 ack, l or.

, . ,

(550; 30) -

550 30,

Text

,
:

games.screen.add(score)

mai nl ()

score.

Text - Sprite,
, . ,
Text, . 11.7.

11.7. Text

value
color

, r

323


, -
. , ,

~, ,

Message.

r r
- .

Message

mainloop( );

: !.
, , .
.

11.10.

.11.10. !

downloads)

#
#

Chapter 11.

from livewires import games . color

you_won. .

(www.courseptr.com/

324

11.

games.init(screen width = 640. screen height = 480. fps = 50)


wall_image = games. load_imageC"wall .jpg". transparent = False)
games.screen.background = wall_image
won_message = games.Message(value ="!".
size = 100.
color = color.red.
= games.screen.width/2.
= games.screen.height/2.
l i fet i me = 250.
after_death = games.screen.quit)
games.screen.addCwon_message)
games.screen.mainloop()

color

accaMessage, Text, color.


,

games

l or:

from livewires import games. color

Message

Message, games.
- Text: ,
.

, .
-

Message , Text,
l ifetime after_death. l ifetime
, ma i n1( ),
. after _death
, r, Message .
after _death None,
:

- .

won_message

Message
=

mainloop():

games.Message(value ="!",
size = 100,
color = color.red.
= games.screen.width/2.
= games.screen.height/2.
lifetime = 250.
after_death = games.screen.quit)

! ,
. Message
1i fet i me, 250, <1 ~

5 ,

mainloop()

50-.

325

01

after_death.

games. screen. qui t (),

.
~~~~~~~~~~~~~~~~~~~~~~~~~

after_death


screen

width, ,
height, .

,
.

, ,

Message ,
games. screen. width/2 games. screen. height/2.
, - ,

. ,

.

Message

games.screen.add(won_message)
Message - Text,
, . ,
Message, . 11.8.
6111

11.8.

Message

lifetime

, mainloop(),
.
. -

after_death

, . None


, .
,

Spri te

326

11.

r
- ~-1>.
,

11.11.

11.11.

, ,

down!oads) Chapter 11.


#
#

from livewires import games


games.init(screen_width = 640 . screen_height = 480 . fps = 50)
wall_image = games.load_image("wall.jpg". transparent = False)
games .screen.background = wall_image
pi zza_ image = games . l oad_ i mage( "pi zza . bmp")
the_pizza = games .Sprite(image = pizza_image .
= games .screen.width/2.
= games.screen.height/2 .
dx = 1.

dy
games.screen.add(the_pizza)
games.screen.mainloop()

1)

(www.courseptr.com/

movi ng_pi zza . .

327

r r
, , ,

. -

dx dy:

the_pizza

games.Sprite(image = pizza_image.
= games.screen.width/2.
= games.screen.height/2.
dx = 1.
dy = 1)

Sprite dx dy,

(d - , ). , dx-
,

dy -

ma i n1 ( )

dx , - ;
dy , - .
- dx dy
. dx dy,

. ,

dx dy 1, ,
ma i nl ( ) , 1
()

().

r
- , ,
.

, , .
,

. .
, -,

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

, , ,
. , , , .


, , , ,
, ,

, . , ,
, dy
, .

328

11.

dx.

11.12

. 11.12. ,

downloads)

Chapter 11.

(www.courseptr.com/

bounci ng_pi zza. .

#
#

from livewires import games


games.init(screen_width = 640. screen_height

480. fps

50)

games

Sprite

-,
: .

Spri te .

329

Pizza:

class Pizza(games.Sprite):
""" . '""'

update()

, Pizza
. ,

mai nl ( ), :

update()

dx

dy;

Spri te

update()

update(),
Pi zza -

def update(self):
"""

if self.right > games.screen.width or self.left <:


self.dx = -self.dx
if self.bottom > games.screen.height or self.top <:
self.dy = -self.dy
,

mainloop()

. ,
.

ri ght, ,
screen. wi dth, -
. l eft, ,
games.

, .
dx,
~ .

bottom, ,

games. screen. hei ght, - .


top, ,

, .
dy - .


,
:

def main():
wall_image = games.load_image("wall.Jpg", transparent
games.screen.background = wall_image

False)

330

11.

pizza_image = games.load_image("pizza.bmp")
the_pizza = Pizza(image = pizza_image.
= games.screen.width/2.
= games.screen.height/2.
dx

1.

dy = 1)

games.screen.add(the_pizza)
games.screen.mainloop()
#!

main() 1
. :
, Pizza, Sprite.
update(), , ,
",

l i vewi res, -

: .
.

l i vewi res .

r r

mouse games .

.
, ~.

, , .
. 11.13.
-

downloads)

(www.courseptr.com/

Chapter 11. . movi ng_pan. .

r r
, , :

#
#
from l i ve 1i res i mport games
games.init(screen_width = 640. screen_he;ght = 480. fps

if

name
main()

main()
_main_

50)

,
main()
, - import . - .. . .

331

11.13.

i ni t ()

games
mouse,

Pan -:

class Pan(games.Sprite):

"""" . """

def update(self) :
'""'

self .x = games .mouse.x


self.y = games.mouse .y

Spri te,

mouse

update() Pan
mouse ), ,
( mouse ). ,
, (
.

332

11.

main() ,
.
:

def mainO:
wal l_image = games. load_image("wall .jpg". transparent
games.screen.background = wall_image
pan_image = games. l oad_i mage( "pan. bmp")
the_pan = Pan(image = pan_image.
= games.mouse.x.
= games.mouse.y)
games.screen.add(the_pan)

False)

games . mouse. , games .mouse.y, Pan , .


ma i n <) i s_vi si l mouse,
.

games.mouse.is_visile

= False

True,

, Fa l se, :
, .


main() event_grab screen,
( ) :

games.screen.event_grab

True

True,

, .

event_grab False,

: .
~~~~~~~~~~~~~~~~~~~~~~~~~

n , .
,

Esc.


, , ma i n() ma i nl ( ) ,
,

games.screen.mainloop()

mai n()

ma i n().

333

mouse

11.9.
111611111

11.9. mouse

, , :

is_visie

True -

False -

- True


.
,

;
. .
, .

. ,

, ,

: .
,
.
.

11.14 11.15.

(www.courseptr.com/
downloads) Chapter 11. s l i ppery_pi zza . .
-

#
#

from livewires import games


import random
games.init(screen_width = 640. screen_height = 480. fps = 50)

random -

,
.

334

11.14. ,

11.

- ...

11 . 15. . ..

335

Pan,

class PanCgarnes.Sprite):
"""" . . '"'"
def update(self):
""" . .
self.x = games.mouse.x
self.y = games.mouse.y
self.check_collide()
def check_col l ideCself):
""" . .
for pizza in self.overlapping_sprites:
pizza.handle_collide()

update()

check_collide(),

, , ,

Pan. ,
Pan .
handle_col l ide( ). , @~

overlapping_sprites

Pi zza:

class Pizza(games.Sprite):
"""" . """
def handle_collide(self):
'""'
self.x = random.randrange(games.screen.width)
self.y = random.randrangeCgames.screen.height)

handl _ l l i de(),
Pi zza.

"""

main( ):

def main():
wall_image = games.load_image("wall.jpg", transparent
games.screen.background = wall_image
pi zza _image = games. l oad_imageC "pi zza. bmp")
pizza_x = random.rar.drangeCgames.screen.width)
pizza_y = random.radrange(games.screen.height)
the_pizza = PizzaCimage = pizza_image. = pizza_x.
games.screen.addCthe pizza)
pan _image = games. l oad_ image( "pan. bmp")

False)

pizza_y)

336

11.

the_pan = Pan(image = pan_image.


= games.mouse.x.
= games.mouse.y)
games.screen.add(the pan)
games.mouse.is_visible = False
games.screen.event_grab = True
games.screen.mainloop()
# !
main()
, , .

Pi zza Pan.

, .
;
.

ma i n( ) ma i nl ( ). r

mai n( ).

l i vewi res,

,
.

,
. -

(www.courseptr.com/downloads) Chapter 11. pizza_

panic.py.

r
,
:

#
# .
from livewires import games. color
import random
games.init(screen_width = 640. screen_height

480. fps

50)

games , l or
.

random ,
- . ,
i ni t ( )

games.


Pan - ,
. ,

337

: .
.

- image.

~>

class

Pa(games.Sprite):

image

ma i ().

games. l oad_i mage( ". bmp")

_init_()

-,
:

def

_iit_(self):

"""

Text

sel f) ._init_(image = . image.


= games.mouse.x.
bottom = games.scree.height)
self.score = games.Text(value = . size = 25. color = color.ack.
top = 5. right = games.scree.width - 10)

superCPa.

games.scree.add(self.score)

super() , - i i t ()
Sprite. score -

, . ,
.

update()

def update(sel f):


"""

self.x = games.mouse.x
if self. left < :
se lf. l eft =
if self.right > games.scree.width:
self.right = games.scree.width
self.check_catch()
,
-. ,

l eft

338

11.

, , ,
. ,

l eft .
ri ght, , ,
games. screen. wi dth, .
, ri ght games . screen. wi dth

check_catch() . ,
:

def check_catch(self):
"'"'

. .

for pizza i self.overlapping sprites:


self.score.value += 10 self.score.right = games.screen.width - 10
pizza.handle_caught()
, ,
10 . Text

1 -

handle_caught() ,

Pizza

,
:

class Pizza(games.Sprite):
.

image
speed

games.load_image("pizza.bmp")

image -

speed -

1,

. -
Pi zza, .

_init_()

def

init Cself.

. =

Pi zza:

90):

-;;-;;-" Pi zza. "'"'

super(Pizza.

= Pizza.image,

self).~init~(image

dy

=
=

= ,

Pizza.speed)

Pi zza.

, 90,

339

update()

def update(self):

if seif.bottom > games.screen.height:


se lf. end game ( )
self. destroy()

, .

end_game( ), .

handle_caught()

Pi zza:
def handle_caught(self):

'"'

"

se 1f. destroy()
, , , <m

Pi zza

destroy() -

end_game()

. ,
.

def end game(self):

"""- . """

end_message = games.Message(value = "Game Over".


size = 90.
color = color.red.
= games.screen.width/2.
= games.screen.height/2,
lifetime = 5 * games.screen.fps.
after_death = games.screen.quit)
games.screen.addCend_message)

Message,

, .

~~~~~~~~~~~~~~~~~~~~~~~~~

end_game() , . ,
5 , , , ,
. 12 , ,

, ,
.

340

11.

Chef

Chef -

-, , ,

class Chef(games.Sprite):
.

i mage

. -. .

games. 1oad_i mageC "chef. bmp")

image -

_init_()

-:

def

55. speed = 2. odds_change = 200):


"'"' Chef. "'"'
superCChef. self).~init~(image = Chef.image.
= games.screen.width / 2.

~init~Cself. =

=,

dx = speed)
self.odds change = odds change
self.time-til drop = .

Chef. image.

image

55,

- odds_change -

dx

2.

odds _change ti me_t i l _drop.

, ,

odds _
change 200, 200,

. , ,

. ,

update( ).

t i me_t i l _drop - i nl (),

.
; , Chef
. ,

check_drop( ).

update()

,
- :

def updateCsel f):


""" . . """
if self.left < or self.right > games.screen.width:
self.dx = -self.dx

341

elif random.randrange(self.odds_change)
self.dx = -self.dx
self.check_drop()

==:

~ ( ) .

. ,

sel f. dx = -sel f. dx.

odds_

hng- , .
, ,

check_drop()

Chef.

check_drop()

ma i nl (), , ,
50 :

def check_drop(self):
'""'

if self.time_til_drop

>:

self.time til drop -= 1


else:
- new_pizza = Pizza(x = self.x)
games.screen.add(new pizza)

# ""
30 %

self.time_til_drop = int(new_pizza.height * 1.3 / Pizza.speed)

t i me_t i l _drop,

. , ,

1;
Pizza, time_til_drop .
, Chef (

), , ,

. t i me_t i 1_
drop ,

. .

main()

ma i n( ) :
def main():
""" . """
wall image = games.load image("wall.jpg", transparent = False)
games.screen.background-= wall_image
the chef = ChefC)
games.screen.addCthe_chef)

30%

342

11.

the_pan = )
games.screen.add(the_pan)
games.mouse.is_visie = False
games.screen.event_grab = True
games.screen.mainloop()

#!

main()
.
- .
, ,

. ,
ma i nl ( ). ma i n( ) .

l i vewi res

. , ,
.

. ,
4'- ,
. ,

, .

, n .
n : /
, , ,
.

, , , ( )
- , .

- . r
,

, .

12

, ,

.

<< >>

, .

, .
, , :

,
.


, ,
, . ,

~., ,
.
, , .

. , ,
, , .
, ,
.
, ,

. .

12.1 1 12.2.

. : N ASA,

Heritage Team - AURA/STScl.

The

344

12. ,

, .

~~ g wi~v

12.1.

. ,

12.2.

345

i nput ( ) , . -
. , games ,
.

r

~
. ,
. ,
,

D-

S-

. ,

. ,

W D

12.3.

.12.3. ,

downloads) Chapter 12. read_key . .

(www.courseptr.com/

346

12. , , .

l i vewi res,

, :

#
#
from livewires import games
games.init(screen_width = 640. screen_height = 480. fps = 50)


- .
update() , , .
, .

class Ship(games.Sprite):

"""

"""

def update(self):

"""

if games. keyboa rd. i s_pressed (games. K_w):


self .y -= 1
if games. keyboa rd. i s_pressed(games. K_s):

self.y += 1
if games.keyboard.is_pressed(games.K_a):
self.x -= 1
i f games. keyboard. i s_pressed(games. K_d):
self.x += 1
keyboard games.
( ) .

is_pressed()

keyboard, True,
Fal se - .

is_pressed()

,
W, S, D. W, ()

1 . S,
1 .
() 1, , D
1, .
i s_pressed()

, . , ,

D S :
update( ), ,
Shi .
games , .
i s_pres sed ( ).
W games. K
_w, S - games. K_s, - games. _

347

D - games. K_d.

. ,

, .

games. _.

. , , ,

games. _.

. , ,

1,

games. _1.


, . , ,

games. K_SPACE.

l i vewi res

ma i n ) .

mai nl ( ).

def mainO:
nebula_image = games.load_imageC"nebula.jpg", transparent
games.screen.background = nebula_image
ship_image = games. load_image("ship.bmp")
the ship = Ship(image = ship image.
= games.screen.width/2.
= games.screen.height/2)
games.screen.add(the ship)
games.screen.mainloopC)
mainO

False)

11 , .
1i vewi res .

-.

<<
, ,

. -, ,

+--,

4-

90,

0.

1
2
(180),

-
270,

. .

12.4.

348

12. , , .

~~~~~~~~~~~~~~~~~~~~~~~~~~

,
, , .

.12.4. , ,

downloads)

Chapter 12.

(www.courseptr.com/

rotate_sprite. .

#
#
from livewires import games
games.init(screen_width = 640. screen_height = 480. fps 50)
l ass Shi ( games. Spri te):
.
def update(self) :
'""' .
if games.keyboard .is_pressed(games.K_RIGHT):
self .angle += 1
i f games. keyboa rd. i s_pressed (games. K_LEF) :
self.angle -= 1
if games.keyboard.is_pressed(games.K_l):
self.angle =
if games .keyboard.is_pressed(games .K_2):
self .angle = 90

"

349

if games.keyboard.is pressed(games.K 3):


self.angle = 180if games.keyboard.is_pressed(games.K_4):
self.angle = 270
def main():
nebula_image = games.load_imageC"nebula.jpg", transparent
games.screen.background = nebula image
ship_image = games. load_image("ship.bmp")
the_ship = Ship(image = ship_image.
= games.screen.width/2,
= games.screen.height/2)
games.screen.addCthe_ship)
games.screen.mainloop()
main()

False)

angle

angl .

( ).
, ,
, .

update()

, -. ,

angle Ship , ,
1. ,
+-. , angl

1 .

angl . 1
angle
0. 2 angl 90,
90.
3, angl 180 .
, 4, angle 270,


, -
.
,

games

- Animation.


~
. ,

. , , ,

12. , , .

350

.
.

12.5.

12.5.

, , ,

( ),

.
, , ,
. .

12.6.

downloads)

Chapter 12.

(www.courseptr.com/

l os i on. .


,
:

#
#

from livewires import games


games.init(screen_width = 640 . screen_height

= 4.

fps

50)

351

!i Ar<Sof! ~fioto$tud10

12.6.

IIJ@Jr8J

nebula_image = games. load_image( "nebula .jpg" . transparent = 0)


games .screen.background = nebula_image

Ani mat i on

, .
. ,
.

12.6:

explosion_files

["explosionl .bmp".
"explosion2.bmp".
"explosion.bmp".

"explosion4.bmp".
"explosion5 .bmp".
"explosion . bmp".

"explosion7 .bmp".
"explosion8 .bmp" ,
"explosion9.bmp"J

12. , , .

352


u Ani mat i on :

explosion

games.Animation(images = explosion_files.
= games.screen.width/2.
= games.screen.height/2.
n_repeats = .
repeat_interval = 5)
games.screen.add(explosion)

Animation

Sprite

. ,
.

,
.

,
, , .

) -. l osi on_fi

l es

n_repeats (
, ).
, .

n_repeats

. ; ,

,
.

repeat _i nterva l

) .
, ; ,

, , .

5.

repeat _i nterva l

, , .

mai nl ()

screen:

games.screen.mainloop()


.
, , ,

,

games.
l i vewi res

, .

, ,

353

, . .

12.7

( , ) .

12.7.

~~~~~~~~~~~~~~~~~~~~~~~~

f!:f .
, , 1.f .

, .

- (www.courseptr.com/
downloads) Chapter 12. sound_and_music . .


,
W -. W V ,
, .

#
#
from livewires import games
games.init(screen_width = 640. screen_height = 480 . fps = 50)
load_sound() games WV-.
#
missile_sound = games. load_sound("missile .wav")

- ,
mi ss i l . wav epee
o mi ssi l e sound.

12. , , .

354

~~~~~~~~~~~~~~~~~~~~~~~~~

WV-

load_sound().

games. musi . l oad( "theme .mid")


,
, .

5:

choice = None
while choice !="":
print(

1 -

23 4 -

5 -

6-

choice = input( "


pri nt ()
#
if

")

choi == "":
pri nt (" .")

, .
1:

choi == "1" :
missile_sound.play()

1 if

rint(" .")

, l ()
.

. , ,
. ,

pl ()

play() ,
,

, .

355


, 1

. , , 1 )

3,
-1.

( ).

elif choice == "2":


1 = i ntC i nput( "
): "))
missile_sound.play(loop)

( -1 =

rint(" .")

,
,

pl ()

r
, ero
stop( ). ,
. stop() ,
, 1i vewi res .
, 3 ,
:

elif choice == "":


missile_sound.stop()
rint(" .")

1
1i vewi res , .
, -
. , ,
: , W AV,
,

OGG

MIDI.

, , ,

.
, ,
.


, ,

music

music

games.

12. , , .

356

games .music. load( "theme.mid")

, IDI- theme.mid.
games. mus i . 1oad (),

, , ,


:1 :

elif choice == "4":


games.music.play()
rint(" .")

theme. mi d.

games. mus i . l ()


, l ()
. , ,

games. mu-

s i . l ( ) 3, (
). -1.
:

1if

choi == "5" :
loop = int(input("Coo
): "))
games.music.play(loop)

? (-1 =

rint("~ :.

")

,
,

play( ).

r
6,
:

elif choice == "6":


games.music.stop()
rint(" .")

, games. mu-

s i . s top (),

. ,

,
.

l i vewi res

357

#
else:

rint(". ".
input("\n\nHae

Enter.

choice)

.")

r
, ,

~.

,
. ,

- : ,
.

r
,
( - ),

, .

,
.

, .
, ,

, ~ ,
.

- , ,
.

- , ,
.
, .

,

, .

, , .

, .
.

358

12. , , .

,
, .~: .
,
.


, , ,
:

Shi - ;
Missile- ;
Asteroid - ;
l os i on - .
- . ,

games. Sprite,

l os i on

Shi , Mi ss i l Asteroi d
games. Ani mat i on.

, ,
.

, , , ,
, ,

. :

, ;
, ;
;

, -;
.


, ,

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

, .

359

- 1

, ,
. ,

.
.

12.8.

12.8.

J -

downloads)"

Chapter 12.

(www.courseptr.com/

astrocrashOl . .

r
:

# -1
#
import random
from livewires import games
games.init(screen_width = 640. screen_height

480. fps

50)

random ,

360

12. , , .

Asteroid
Asteroi d , :

class Asteroid(games.Sprite):
'""' . . '""'
SMALL = 1
MEDIUM = 2
LARGE = 3
images = {SMALL : games. load_image("asteroid_small .bmp").
MEDIUM: games.load imageC"asteroid med.bmp").
LARGE : games. load_image("asteroid_big.bmp") }
SPEED = 2
, ,

, SMALL, MEDIUM LARGE,

, -
. , ,
. ,

SPEED,
.

_init()_

-:

def

init Cself. . , size):


"""
super(Asteroid. self).~init~(
image = Asteroid.images[size].

"""

=.=.

dx

dy

random.choice([l. -1])
random.choiceC[l. -1])
self.size = size

*
*

Asteroid.SPEEO
Asteroid.SPEEO

*
*

random.random()/size.
random.random()/size)

, size,
:

Asteroid.LARGE.

size

Asteroid.SMALL, Asteroid.MEDIUM

i mage Spri te (

Asteroi d). ,
,
-

Asteroi d

Spri te.

, ,
,

Spri te.

, ,

. Asteroid
s i ze.

update()

, ,
, :

361

def update( sel f):


""" .
if self.top > games.screen.height:
self.bottom =
if self .bottom < :
self.top = games.screen.height
if self.left > games.screen.width:
self.right =
if self.right < :
se l f. l eft = games. screen. wi dth

main()

ma i n( )

def main():
#

nebul _image = games. l oad_image( "nebul . jpg")


games.screen.background = nebula image
# 8
for i in range(8):
= random.randrange(games.screen.width)
= random.randrange(games.screen.height)
size = random.choice([Asteroid.SMALL. Asteroid.MEDIUM. Asteroid.LARGEJ)
new_asteroid = Asteroid(x = . =, size = size)
games.screen.add(new_asteroid)
games.screen.mainloop()

# !
mai n()

,
.
.

- 2

- 2 ~ - 1~.

,
. --+
, +- - .
.

12.9.

downloads)

Chapter 12.

(www.courseptr.com/

astrocrash02. .

362

12. , , .

.12.9.

Ship

, ,

Shi , :

class Ship(games .Sprite):


""" .

"""

image = games. load_image("ship .bmp")


ROTATION STEP = 3
def update(self):
""" .
if games . keyboard. i s pressed(games . LEF) :
self.angle -= Ship .ROTATION STEPif games .keyboard.is pressed(games.K RIGHT):
self .angle += Ship .ROTATION S ~.

. . -, -

i mage . -,

, ,
ROTAION

STEP.

Ship

, ,

Shi
main( ):

363

#
the ship = Ship(image = Ship.image.
= games.screen.width/2.
= games.screen.height/2 )
games.screen .add(the_ship)


.
j ,
, .

, ,
.

r
~

- 3

, ,

. .

12.10.

12.1.

downloads)

Chapter 12.

(www.courseptr.com/

astrocrashO. .

364

12. , , .

math

import math. random


,
: ,
.

Ship

VELOCIY_

STEP

Shi :

VELOCITY STEP = .03


,
; , , , .

sound,

sound

games.load_sound("thrust.wav")

update() Ship

update() Ship ,
. :

t. , :

if games.keyboard.is_pressedCgames.K_UP):
Ship.sound.playC)
, ,

j,

- dx dy Ship. ,
, ,
?

( , ,
). ,
, .

, :

ang1e

self.angle

math.pi /

180 #

, , .

Python math ,

l i vewi res -

, ),

, , ,

pi

math,

~:~>.

365

, ,

sin()

cos()

math

,
1

dx dy :
Ship.VELOCITY STEP * math.sin(angle)
Ship.VELOCITY=STEP * -math.cos(angle)

self.dx
self.dy

+=
+=

, ma th . s i n( ng l ) ,
, -math.cos(angle) -
, 1 .

.
, : ~ . ,

update()

Asteroid

Shi :

""

if self.top > games.screen.height:


self .bottom =
if self.bottom <:
self.top = games.screen.height
if self.left > games.screen.width:
self. right =
if self. right < :
self.left = games.screen.width
,
- .

.
~~~~~~~~~~~~~~~~~~~~~~~~~~

.
, ,

. , r
r r r ,
.


, .

,
. ,
; , ,
.

,
.

. .

, ,

, .

. .

12. , , .

366

- 41>

- 4

, ,

. , , : ,
,

50 _r . ,
-
- 4i.,

- ,
.
.

12.11.

downloads)

Chapter 12.

(www.courseptr.com/

astrocrash04. .

12.11.

update()

update()

Shi ,

Ship

. , :

367

. ;:J

if games.keyboard.is pressed(games.K SPACE):


new_missile = Missile(self.x. self.y. self.angle)
games.screen.add(new_missile)

Mi ss i 1eCself. . self .. self. angl )


Mi ss i 1.

-,

Missile

Mi ss i 1

, .

, :

class Missile(games.Sprite):
""" .
image = games.load_image("missile.bmp")
sound = games.load sound("missile.wav")
BUFFER = 40
VELOCITY FACTOR = 7
LIFEIME = 40
i mage

sound ,
BUFFER

.
.

( ,
, ). VELOCIY_FACTOR
. , LIFEIME

, , ).

_init_()

def

~init~<self.

"""

ship_x. ship_y. ship_angle):

ship_x,
ship_y ship_angle. : , -,

, -,

.
,

Missile.sound.play()
, , ,
:

#
angle = shio_angle * math.pi / 180

368

12. , , .

buffer_x = Missile.BUFFER * math.sin(angle)


buffer_y = Missile.BUFFER * -math.cosCangle)
= ship_x + buffer_x
= ship_y + buffer_y
.
;

Mi ssi l . BUFFER.

Shi :

#
dx = Missile.VELOCITY_FACTOR * math.sin(angle)
dy = Missile.VELOCITY_FACTOR * -math.cos(angle)

Spri te :

#
superCMissile. self) ._init_Cimage

Missile. image.

=.=,

dx

dx. dy

dy)

l i fetime,
self.lifetime = Missile.LIFETIME

Mi ssi l )

update()

update( ). :

def update( se lf):


""" .
# " "
self.lifetime -= 1
if self. lifetime ==:
self.destroy()

- , l i fet i
. , Mi ssi 1 .

updateC)

#
if self.top > games.screen.height:
self.bottom =
if self.bottom < :
self.top = games.screen.height
if self.left > games.screen.width:
self.rignt =
if self.right < :
self.left = games.screen.width

369

. ,
- .

50 . ,

, .
.

- 5i>

- 5

, ,
. .

12:12.

.12.12.

downloads) Chapter 12. astrocrash05. .

(www.courseptr.com/

370

12. , , .

Ship

Shi :

MISSILE DELAY = 25
MISSILE_DELAY -

. ,
, .

Ship

-:

def _init_(self. . ):
"'"'
super(Ship. selfJ._init_(image = Ship.image. = .
self.missile wait =

= )

mi ssi l e_wait.

- games . Spri te.

mi ssi l e_wait

, .

Shi

update()

update()
missi le_wait .

Ship

# .

if self.missile_wait > :
self.missile wait -= 1
, ,
:

# .

if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait


new_missile = Missile(self.x. self.y. self.angle)
games.screen.add(new_missile)
self.missile_wait = Ship.MISSILE_DELAY
, , ,

==:

missile_wait

MISSILE_DELAY,

mi ssi le_wait

371

r
,

.
. , - , ,

.
. : ,
, , .

r
~

- 6

overl appi ng_spri tes, .

, :
, ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~

, ,
, ,

, . ,
.

12.13.
(www.courseptr.com/downloads) Chapter 12.
astrocrash06.py.

upda te ( )

update()

Missile

Mi s s i l :

if self.overlapping_sprites:
for sprite in self.overlapping_sprites:
sprite.die()
self.die()
-
( ), ,

die( ).
Mi ss i 1.

Missile

die()

die()

Asteroid, Ship

Missile

. :

372

12. , , .

12.13. ,

, .

def die(sel f):


""" . """
self .destroy()
Mi ss i l

di ( ) ,

update()

update()

Ship

Shi

#
if self.overlapping_sprites:
for sprite in self .overlapping_sprites:
sprite .die()
self.die()
-
, ,

update()

die( ). ,
Mi ssi 1.

, , .
.

373

die()

Ship

Mi s s i 1:

def die(self):
"'"'

'"'"

se 1f. destroy()

Ship die( ),

SPAWN

Asteroid

Asteroid

SPAWN -

di ()

die()

Asteroid

Asteroi d :

def die(self):
"""

"""

if self.size != Asteroid.SMALL:
for i in range(Asteroid.SPAWN):
new asteroid = Asteroid(x = self.x.
= self.y.
size = self.size - 1)
games.screen.add(new_asteroid)
self .destroy()
, , , Asteroi d.

SPAWN Asteroi d.

.
,

. , ,
.

- . .

374

12. , , .

- 7

- 7 games. Ani mat i on,

. ,
, .
, , ,

12.14.

12.14.

downloads)

Chapter 12.

(www.courseptr.com/
astrocrash07. .

Wrapper

, :

games . Spri te

Wrapper.

update()

Wrapper update( ),

, :

375

class Wrapper(games.Sprite):
""" . . . .
def update(self):
""" .
if self.top > games.screen.height:
self.bottom =
if self.bottom < :
self.top = games.screen.height
1 f se lf. 1eft > games. screen. wi dth:
self. right =
if self.right <:
self.left = games.screen.width

, . ,

, Wrapper,
update( ), .

di()

die( ), :

def di se lf):
""" .

self. destroy()

Collider

. ,
Shi Mi ssi l . Wrapper
Col l ider, ,
, ,

update()

update( ), :

class ColliderCWrapper):
""" n. .
.

111111

def updateCself):
""".

"""

super(Collider. self).update()
if self.overlapping sprites:
for sprite in self.overlapping sprites:
sprite.die()
self.die()

update()

11 i der

update()

, Wrapper, .
.

376

12. , , .

- ,

die( ),

di()
di (), 11 i der

def die(self):
"""

new explosion = Explosion(x = self .x.


games.screen.add(new explosion)
self .destroy()

= self .y)

, ,

Explosion.

1os i on, ,

Asteroid

Asteroi d Wrapper:

class Asteroid(Wrapper):

Asteroid Wrapper update(),


update() . !
, die()
As teroi d se1f. di ( ) :

super(Asteroid. self).die()
,

di ()

Wrapper

Asteroi d

Shi

Ship

11 i der:

class Ship(Collider):

update()

super(Ship. self).update()
, .

update()

Collider

update()

Shi . ,
update() ,

, ,

Shi

.
,

Col l ider.

di ( ):

377

Missile

Mi s si l , l l i der:

class MissileCCollider):

update()

super(Missile. self).update()
Shi , . update()
l l i der ,

updateC) Mi ss i l .

Wrapper),

die()

Collider).
~~~~~~~~~~~~~~~~~~~~~~~~

, ,

, -

www.courseptr.com/

downloads.

Explosion

Explosion ga-

mes. Ani mat i on.


class Explosion(games.Animation):
"""

""

sound = games. l oad_soundC " l osi on. wav")


images = ["explosionl.bmp".
"explosion2.bmp".
"explosion.bmp".

"expl os ion4. bmp".


"expl osi on5. bmp".
"explosion.bmp".

"explosion7.bmp".
"explosion8.bmp".
"explosion9.bmp"J

- i mages -

sound .

- l os i on.

def _; nit_Cself. . ):
super(Explosion. self)._init_Cimages

Explosion.images.

=,

repeat interval

is_collideae

Explosion.sound.play()

=
=

4. n repeats
False)

1.

378

12. , , .

,
.

( games . Ani ma t i on ),

, . , .

n_repeats

1,

l os i on.

i mages

.
,

collideae

i mages.

False,

4.

repeat_ i nterva l,

i s_

, ,

<t ,

- Explosion.so-

und.play().
~~~~~~~~~~~~~~~~~~~~~~~~~

, games.Aimation

, -.

, ,

,
- . , ,
,
. ,

.

- 8

, ,
, ,

. ,

, .

12.15.

downloads)

(www.courseptr.com/
Chapter 12. astrocrash08. .

color

games

l i vewi res

l or:

from livewires import games. color

color

- .

Game Over

379

, ,

p~g~ window

12.1 S.

, ,

Gm

Game -

. , ,

, . - ,
: , l () - , advance() ,

end ( ) -

, game
. ,
, , ,

, game ,
. , , game
.
Game, ,

ma i n( ) .

_init_()

Game

class Game(object) :
"""

"""

380

12. , , .

def

~init~<self):
""" Game.
#

self. level =
# .
self.soud =

games. load sound("level .wav")

# .

self.score = games.Text(value =.
size = 30.
color = color.white.
top = 5.
right = games.screen.width - 10.
is collideae = False)

games.screen.add(self.scorJ

# .

self.ship = Ship(game = self.


= games.screen.width/2.
= games.screen.height/2)
games.screen.add(self.ship)
1eve l .

sound

, .

score ,
. i s_col l idea
F l se, ,
~ . , shi - ,
.

play()

play( ), .

def play(self):
""" . """
#
games. mus i . l oad( "theme. mi d")
games.music.play(-1)
#
nebula_image = games. load_image( "nebula .jpg")
games.screen.background = nebula image
# 1
se l f. advance()
#
games.screen.mainloop()
,
. ,
.
Game

- advance( ),

, ( , ).
, games. screen. ma i nl (

).

381

, ,

advance()

advance()

l evel, ~~ ,

.

def advanceCself):
'""'
self. level += 1

. ?
,

. , , ,

- . . ; ,

. , , .

#
BUFFER = 150
#
for i i range(self. level):
# .

BUFFER

#
x_min = random.randrange(BUFFER)
min = BUFFER - min

# .

distance = random.randrange(x min. games.screen.width - min)


y-distance = random.randrange(y-min. games.screen.height - min)
#- . = self.ship.x + x_distance
= self.ship.y + distance
# .
%= games.screen.width
%= games.screen.height
#
new_asteroid = Asteroid(game = self.
=.=,

size = Asteroid.LARGE)
games.screen.add(new asteroid)

BUFFER

. ,
. _mi n

, ; _mi n .

random,

x_min y_min

BUFFER.

382

12. , , .

x_di stance -

. , , :

, x_mi n.
, y_di stance - .
, ,
_mi n .

x_distance.

: y_di stance.
,
.
.

, Asteroi d

game.

Game, ,
Game. sel f.
advance()
:

#
level_message = games.Message(value =""+ str(self.level).
size = 40.
color = color.yellow.
= games.screen.width/2.
= games.screen.width/10.
lifetime = 3 * games.screen.fps.
is collideae = False)
games.screen.add(level message) # ( 1- )
if se 1f. 1eve l > 1 :
self.sound.play()
nd()
end () Game
Over, . 5

. .

def end(self):

'""'
# 5-
end_message

"""

'Game Over'
games.Message(value = "Game Over".
size = 90.
color = color.red.
= games.screen.width/2.
= games.screen.height/2.
lifetime = 5 * games.screen.fps.

383

, ,

after death

games.screen.quit.

is_collideae = False)

games.screen.add(end_message)

Asteroid

Asteroi d

. , ,

POINTS

POINTS:

30

- ,
.
, .
,
, .

,
- tota l, , :

total

-
- ,

Asteroid

Asteroi d. tota 1

Asteroid.total

+=

Game,
.

def

Asteroi d:

~init~(self.

game.

. .

size):

game , Game.
Asteroi d:

self.game

game

, Asteroi d

game -

. As teroi d

Game, advance( ).

die()

Asteroid

di () Asteroi d . -, ,

Asteroi d. tota 1 :

Asteroid.total

-=

384

12. , , .

Asteroid.POINTS

, (
, ).

ri ght

score

self.game.score.value += int(Asteroid.POINTS / self.size)


self.game.score.right = games.screen.width - 10
( )

Game. Asteroid

new_asteroid

Asteroid(game = self .game.


di () Asteroi d. tota 1
=

: ? ,

advance() Game,
.

# .

if

Asteroid.total == :
self.game.advance()

Ship

Ship

. -,

VELOCIY_MAX, :

VELOC

Asteroid,

Ship

Ship Game,

. - Asteroi d

Shi :
def _init_(self. game.

. ):

game Game,
Shi :

self.game

game

Shi game -
Shi

Game, end( ).

update()

Ship

update() Shi :

, dx
:

dy, _VELOC I,

385

#
self.dx = min(max(self.dx. -Ship.VELOCITY ). Ship.VELOCITY )
self.dy = min(max(self.dy. -Ship.VELOCITY-AX).
Ship.VELOCITY-MAX)
, dx

dy -Sh i . VELOC I_
Sh i . VELOC I_.
min() max( ). min() ,

max() - . , , ,
, , ,

die()

Ship

, .
Ship die(

Game,

), , , end()

def die(self):
."".
self.game.end()
super(Ship. self).die()

"""

main()

Game, ma i n() .
Game l (),

,
.

def main():
astrocrash = Game()
astrocrash.play()

main()

,
, . , ,

. ,

, ,
. , ,
, .
,

- ,
.

386

12. , , .

, -
. , - <
: , J\
.

( - (Simo Says).
11 ,
.

- , n
.

. :
.

-
-

www.courseptr.com/downloads.

r, ,
.

. :
pye_source. zi

, ;

pye _softwa re

- ,
, Python 3.1.1 Windows.
. .1 pye_source.zip, . .2

pye_software.zip.
n8 .1. pye_source.zip

chapterOl
chapter02
chapter03
chapter04
chapterOS

chapterO

chapter07
chapter08
chapter09
chapterlO

1
2
3
4
5

8
9
10

chapterll
chapter12

pytho

Pytho

pygame
livewires

11,
12,

,
,

n8 .2. pye_software.zip

pygame

3.1.1 Windows
1.9.1, Python 3.1.
) livewires

Windows

~~~~~~~~~~~~~~~~~~~~~~~~~~

pygame Windows py3e_software.zip


Python 3.1 ( 3.1. 3.1.9).

Python

3.1.,

livewires
,
1i

vewi res,

. -

1i vewi res

livewires

1i vewi

res -

, , . . .1.

l ivewi res, ,

pygame.

8.1.

livewires

games
color

games

games

. . .2.

8.2.

games

Scree

Sprite

Text

r . Text - Sprite

Message

, .

Message -

Text

389

games

Animatio

, . Aimatio -

Sprite
Mouse

Music

Screen

Screen . games. i ni t )
screen Screen; ,

. . .3

Screen, .

.4

8.3.

Screen

:n

width
height
fps

ackgroud

all objects

evet_grab

, , . , True, - False

8.4. Screen

get_width()
get_height()
get_fps()

get_ackgroud()

set_ackgroud
(ew_ackgroud)

ew_ackgroud

get_all_objects()

01 ,

get_evet_grab()

, . ,


set_evet_grab

True,

- False

(ew_status)

ew_status. rue

add(sprite)

False -
Sprite

remove(sprite)

clear()

mailoop()

quit()

Sprite

390

livewlres

Sprite

Spri te
. . .5 Spri te, . .6 -
.

.5.

Sprite

Coiicro

image
width
height
angle

position
top

. (, )

ottom

left
right
dx
dy
velodty
overtapping_sprites
is_collideable

interval

, ,
. True, , False -

.6.

(dx, dy)

tick()

Sprite

_init_(image [, agle]
. image
[, ] [,] [, top]
, .
[, ottom] [, left] [, right] angle, , , dx dy . top, ottom,
[, dx] [, dy] [, interval]
left: right N.
[, is_collideable])
, . interval
1, is_collideable - True
get_image()
-,
set_image{new_image)
ew_image
get_height()

get_width()

get_angle()

set_angle{new_angle)
new_angle

geLx()
set_x(new_x)
new_x
get_y()

391

games

set_y(new_y)
get_position()
set__position
(new__position)
get_top()
set_top(new_top)
get_bottom()

set_ottom(new_bottom)

new_ottom

new_y

n
,

new_position

new_top

get_left()

set_left(ew_left)

new_left
get_right()

set_right( new_right)
new_right
get_dx()

set_dx(new_dx)
new_dx
get_dy()

set_dy(new_dy)
new_dy
get_velocity()

set_velocity
<0
(new_velocity)
new_velocity
get_over1apping_sprites() ,

overlaps(other)

True, other,
False . False,
is_collideae False

get_is_collideae()

, .

True

False -

(new_status)

new_status.
True,
, False -

get_interval()
set_interval
(new_interval)
update()


new_interval

tick()

set_is_collideae

tick()
tick()

. ;
mainloop(). , Sprite,

interval

mainloop(). Sprite,

. ,

destroy()

t
Spri te. Text
Text , Sprite. . .7
Text, . .8 - .

Text -

. ,

392

n .7.

value

size

livewires

Text

. , -

color

color

text, size color

8.8.

Text

_init_(va\ue, size, co\or


[, angle] [, ] [, ] [, top]
[, ottom] [, left:] [, right]
[, dx] [, dy] [, interval]
[, is_collideae])

. n value - , , size- , color - .


angle, , , dx dy . n top, ottom,

left right

None. n
, . n interval
1, is_co/lideae - True

get_va/ue()

set_value(new_value)

new_value

get_size()

set_size(new_size)

get_color()

set_color(new_color)

new_color .
, color

new_size

Message

Message -

Text.

Message

Message

,
.

Message

Message

after _death.

Text.

(, ),

. ssg
init (): init

None.
(value. size. color [. angle]
[. ] [.][. top] [. bottom] [. left] [~right] [.dx] [. dy] [. lifetime] [. is
col l ideaeJ [. after_death]). .
value - , , size - , color - .
angle, ,, dx dy . top, bottom, left right
None. ,
.

1i fet i me

393

games

mai nl ()

, .

, .

l i fetime , i s_col l ideab le - True.


None.

after_death

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

lifetime Message , ,
lifetime, interval.

Animation

Ani mat i on
Ani mat i on
, Spri te

Ani mat i on -

Spri te.

, .

, . .9.

8.9. Animation

images
n_repeats

-
, ,

. ,
.

nimtin

init

():

init

(images [. angle] [.

[.] [. top] [. bottom] [. left] [. rightJ[. dx] [.dy] [. repeat interval]

[. n_repeats] [.
images

is_co'lidealeJ). .
-,

, .
.

None.

top, bottom, l eft

ri ght

angl ,

, ,

dx dy

repeat _i nterva l
ck ) , ,
n_repeats ,

t i
.

ais

1.

collideale-True.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

repeat_iterval Animation , ,
repeat_interval, interval.

Mouse

mouse

Mouse . games. init()


Mouse,

. ,
.

. .11.

Mouse

. .1 ,

394

6n .10.

livewires

Mouse

position

. (, )

is_visile

, ,
. True - , False - . True

n .11.

Mouse

get_x()
set_x(new_x)
get_y()

set_y(new_y)

get_positio()

set_position
(new_position)

, -

set_is_visie

.
True, , False -

new_x

new_y

(new_visibllity)

new_position
new_viSibllity

, . True,
button_umber , False

is_pressed
(button_numer)

Keyboard

rd .

keyboard

Keyboard,

games. i ni t ()

,
.

i s _pressed ( key),
True, , Fa l se . ,

games.
, . .15.

Music

Music

,
. ,
. :
,
. .12.

WAV,

OGG MIDI.

Music

395

games
.12.

Music

load(filename)

filename . -
,

play([loop])

loop+l

-1,

fadeout(millisec)

millisec

stop()

games

games

. .13.
.13.

games

ilt([scree_width,]

screen_width
screen_height, fps .
screen - games.Screen,
. mouse - . games.Mouse, r . kd - .

[screen_height,] [fps])

games.Keyoard, . ,
music, games.Music,

load_image(filename
[, trasparent])

-, filename.
transparet True ( ),

scale_lmage(image,
x_scale [, y_scale])

-,
image, x_scale ,
y_scale . y_scale
, x_scale
.

load_sound(filename)

, WV-

filename

l oad _sound (),

. . .14.
.14.

play([loop])

Sound

loop+ 1 .

-1,

fadeout(millisec)
stop()

millisec

396

livewires

games

l or ,

. . .15.
.15.

nw

K_REURN

Retum
Pause

K_PAUSE
K_ESCAPE
K_SPACE
K_EXCLAIM
K_QUOEDBL

K_HASH
K_OOLLAR
K_AMPERSAND
K_QUOE
K_LEFPAREN

Esc

.
!

.
&

K_RIGHPAREN

(
)

K_ASERISK

K_PLUS

K_MINUS
K_PERIOD
K_SLASH

K_l

_2

_4

_s

5
6

_
_7

_8
_9

K_COLON
K_SEMICOLON
K_LESS
K_EQUALS
K_GREAER
K_QUESION

7
8
9
:
;
<
=
>
?

K_LEFBRACKE

K_ACKSLASH

games

397

games

_RIGR

_R

K_UNDERSCORE

f
K_g
K_h
K_i
K_j
k
KI
Km
K_n

F
G

q
r

t
K_u
K_v
K_w

DELEE

_l
_2
_

_4
5

7
_8

_9

u
v
w

Delete
Keypad 1 0
Keypad 1
d 2
d 3
d 4
d 5
Keypad 6
d 7
d 8
d 9
~

. .

398

8.15 ()

nw

__PERIOD

__DIVIDE

K_KP_MULIPLY
K_KP_MINUS
K_KP_PLUS
K_KP_ENTER
__EQUALS
K_UP
K_DOWN
K_RIG
K_LEF

K_INSERT
_

K_END
K_PAGEUP
K_PAGEDOWN
K_Fl
K_F2

Period
Keypad Divide
d Multiply
d Mius

d Plus
Keypad Enter
Keypad Equals
Up Arrow
Down Arrow
Right Arrow
Left Arrow
Insert
Home
End
Page Up
Page Down
Fl
F2

_F

K_F4
K_FS

F4
FS

_F

K_F7
K_F8
K_F9
K_F10
K_F11
K_F12
K_NUMLOCK
K_CAPSLOCK
K_SCROLLOCK

F7
F8
F9
F10
F11
F12
Num Lock
Caps Lock
Scroll Lock
Shift
Shift

K_RSHIF
K_LSIF
K_RCRL

tl

K_LCRL

K_RALT
K_LALT
K_LSUPER
K_RSUPER
K_HELP

K_PRIN

K_BREAK

Ctrl
Alt
Alt

Windows
Windows

Help
Print Screen
Break

livewlres

col or

399

color

color

, 11-r

red -

green -

1ue

white -

da rk_red -

dark_green -

ack -

dark_ue

dark_gray -

gray -

l ight_gray -

yel l ow -

brown -

pi nk -

purp l -

-;

-;
-;

;
-;

;
;


_additional_cards(),

274

(s- )

add(),
50, 51

_pass_tie(),

( )

33
50, 51

49, 52
55

( )

// ( ) 55
/( ) 55
% (

55

*( )

53
+( ) 55
> ( ) 78
>= (
) 78
< ( ) 78
<=(

78

!= (

77
77
+( ) 52, 65, 129
*( ) 55
/( ) 214
#( ) 41
( ) 49, 51, 199, 202
_( ) 234
==

( )

205
+

205
add(sprite),

241
@property, 238
Python

( )

screen 313, 389

251

319

advance(), 381
after_ death, 325
all_objects, screen 389
and, 96
angle, 320, 349, 390
Animation, 351, 389, 393
append(), 142, 144
Application
, 288
, 289
SII- 48
ask_numer(), 184, 185, 264, 265
ask_yes_no(), 172, 184, 185, 264
Asteroid.SPAWN, 373
Asteroid, 360
die(), 373, 383
_init_(), 360
update(), 360
376
- 383
373
383

background, 313, 389


BJ_ Card, 267, 269
BJ_Dealer, 268, 272
BJ_Deck, 268, 270
Bj_Game,
_additional_cards(), 274
_init_(), 273

401

play(), 27 4
still_playing, 273
268, 273
BJ_Hand, 268, 270
BJ_Player, 268, 272
BooleanVar, 300
botto, 320, 390

contlgure(), 287
congrat_,,inner(),

d,

241

_pass_tie(),

241

play(), 242
talk(), 242

capitalize(), 63
cards,

269

Card,
Hand

191

Critter, 241
eat(), 242

bust(), 273

1!,

cos(), 365
count(), 144
create_widgets(), 289, 291, 304

241

242

#, 32

ero

251
251
250
check_catch(), 338
check_drop(), 341
Chet",
check_drop(), 341
_init_(), 340
update(), 340
340
clear(), screen 251, 313, 389
close(), 198, 203

Collider,
die(), 376
update(), 375

D
dea\(), 257
Deck, 253
delete(), 296
del, 140
destroy(), 320, 339, 391
display_board(), 184, 186
display_instruct(), 184, 185
display(), 170
dup, 206
dx, 320, 390
dy, 320, 390

375

color,
321, 324, 378
399
388
color, 322, 392
colunspan, 293
colun, 293
comand, 291
computer_ve(), 184, 188

eat(), 242
elif, 80
else, 79, 83, 212
end_game(), 339
end{), 382
end, 47
s-

50

49

r 49

402

49

50

48
event_grab, 313, 389
except, 210, 212
Explosion, 377

Music, 394
Screen, 389
Sprite, 390
Text, 391
269, 311
396
388

395
G,

fadeout(), 395
False, 89
flip_first_card(), 273
t1oat(), 68
fps, screen 313, 389

379
advance(), 381
end(), 382
_init_(), 379
play(), 380
geon1etry(), 283

get_all_objects(), screen 389


get_angle(), 390
get_background(), screen 389
get_bottorn(), 391
get_color(), 392
get_dx(), 391

Over 2.0,

Garne Over,

44

35

print(), 36

37
36
38
37
38
39
r 38
38
42
41
30
42
41
gaes.init(), 336
garnes.init(), 312
games.load_image(), 314
games,
Animation, 393
Keyboard, 394
Message, 392
s, 393

get_dy(), 391
get_event_grab(), screen 389
get_fps(), sc.reen 389
get_height(), 390
get_image(), 390
get_interval(), 391
get_is_collideale(),

391

get_left(), 391
get_overlapping_sprites(), 391
get_position(), 391, 394
get_right(), 391
get_size(), 392
get_top(), 391
get_value(), 392
get_ velocity(), 391
get_width(), 389
get_x(), 390, 394
get_y(), 390, 394
get(), 155, 158, 295
give_me_five(),y

171

403

give(), 251
grid(), 285, 293

]
Java32

handle_caught(), 339
handle_collide(), 335
nd,
Card 252
height, 313, 390
Hello World, 30
human_move(), 184, 188

Keyboard, 389, 394


keyboard, 312
KeyError, 210
keys(), 158

L
left, 320, 390
legal_oves(),

1
IDLE35

print(), 36

35
38

37

37

39

38
38

images, 393
image, 320, 390
import, 265
IndexError, 210
index(), 144
init(), 395
input(), 280
insert(), 144, 296
instruction(), 168
interval, 390
IOError, 210
is_busted(), BJ_Hand 271
is_collideale, 320, 390
. is_hitting(), 272
is_pressed(), 346, 394
is_visile, 333, 394
items(), 159

184, 186
\ifetie, 325
livewires,
color, 399
gaes, 388
308, 388
load_iage(), 314
load_sound(), 395
load(), 395
load, 206
lose(), 272
lower(), 62, 63

mainloop(),

283, 306

313

math, 364
_ VELOCIY,

Message, 312

325
388, 392

324
Missile,
die(), 371
_init_(), 367
update(), 368, 371
372
367

384

404

mood, r 241
moon_weight, 70
Mouse, 389, 393
nuse, 312
Music, 389, 394

\, 264
populate(), 256
(),

144
position, 390, 394
private_method(), 235
pulic_method(), 235
pygame, 31
Python 31

N
NaeError,

210
new_board(), 184, 186
next_ock(), 215, 217
next_line(), 215
next_turn(), 184, 191
not. 96
n_repeats, 352, 393

33

32

31

33

Windows33

odds_change, 340
open_file(), 214
open(), 197
or, 97
overlapping_sprites, 320, 390
overlaps(), 391

Pan,
check_catch(), 338
_init_(), 337
update(), 337

pickle.dnp(),

205
205

pickle.load(),
pickle, 204
pieces(), 184, 186
Pizza, 338
cnd_gae(), 339
handle_caught(), 339
_init_(), 338
updatc(), 339
player.is_hitting(), 274

337

Python Tuto,

33

Q
quit(),

screen 313

R
randint(), 74, 101
random.choice(), 130, 162
rando.randange(), 114
rando.shuffle(), 257
random, 102
randint(), 74
randrange(), 75
74, 114, 359
7 4
randrange(), 75, 265
range(), 108
rb 205
rb+ 205
read_global(), 180
read_it.txt, - 197
readlines{),
203

34

405

readline(), 199
readline([)), 203
read(), 198
rd([]),
203
remove(sprite), screen 389
reove(), 143, 144
replace(), 63
revea\(), 295
reverse(), 144
right, 320, 390
rowspan, 294
row, 293

s
scale_image(), 395
Screen, 388, 389
mainloop(), 389
screen, 312
self.update_text(), 299
se\f, 223, 227
set_angle(), 390
set_background(), screen 389
set_ottom(), 391
set_color, 392
set_dx(), 391
set_dy(), 391
set_ event_grab(), screen 389
set_image(), 390
set_interva\(), 391
set_is_collidea\e(), 391
set_is_visi\e(), 394
set_left(), 391
set_position(), 391, 394
set_right(), 391
set_size(), 392
sct_top(), 391
set_ value, 392
set_velocity(), 391
set_x(), 390, 394

set_y(), 391, 394


shadow _g\oba\(), 181
shelve.open(), 206
shelve, 204
Ship,
die(), 385
update(), 364, 370, 372, 384
376
- 370, 384
362, 370
364, 384
sin(), u 365
size, 392
sort(), 143, 144
Sprite, 312, 320, 388, 390
status(), 231
sticky, 294
still_playing. 21:i
stop(), 355, 395
StringVar, 302
strip(), 63
str(), 68
sun_ \\:eight, 70
super(), u 337
swapcase(), 63
sync(), 207
SyntaxError, 210
sys.exit(), 214

talk(), 223, 224, 234, 242


tell_story(), 305
text_file, 197
Text, 312, 391
Text,
322
322
tick(), 391
time_ til_ drop, 340
title(), 63, 283

406

tkinter, 279, 282, 288, 303


top, 320, 390
total, 231
True, 83, 85, 88
TypeError, 210

169, 172

98

99

99

UML (
) 248
update_count(), 291
update_text(), 299
update(),
320, 391
upper(), 62, 63

349
~ Animation 352
351
212

37

387

ValueError, 210
values(), 159
value, 322
variale, 302
VELOCIY _MAX, 384
velocity, 390

228

228

234

233

234
227

W V, 353
wb205
wb+ 205
welcome(), 216
width, 313, 389
winner(), 184, 187
Wrapper, 374
die(), 375
update(), 374
writelines(),

write(),

231

226

221

233

202, 203

239
238

201, 203

354

353
355

z
ZeroDivisionError,

229

231

210

355

50

231

350

407

355

356

355

380

356

332
67

356

147
149

145
149
147
148
146
37

352

&

283, 285, 287


283
tkinter 282
281

260
255

11

91
break 93
continue 93
86
88

178

182

88

78

181
182
177
178

101

327

332

332

126
75

(GUI) 277

330

update() 329
Sprite 328

180

86, 93

180

72

, r

37
70
, 37, 55

259

258

171

312
games 311
12
31
332

331

408

232

44

55

55

168

239

47

45
47

55

46

239

350

347

265

253
222
221
233

198

202

201
200
352, 353, 355, 357

154

152

176

101

37

115
r 175
, 111

172

172
167, 168, 169

50

204

30

color 399
games 396
117
159

232

( fps) 312

41

285

286

174, 176

287

in 154

46

152

378

106

224

225

if

77

225

409

77

Gid

79

78

grid(),

285

77
break

293
Entry 294
Text 295
295
.'I

93

93
continue

93

.'I

93
from 311
try 208, 212

128
125

235
223
221

126

in 128

123
124

125

223

263

128

258

233

126

235

104

62, 224

144

129

284

284

125

285

285

149

291

55

129

262

74

and 96
not96
or97

261

65

298

178

346

93

261

258

265

126

62

259

258

260

410

252

253
252

113
78

37

115

144, 149

178


86

else 212
211
208
212
try/except 208
209

280
291
291

65

303
300

301
200

57

258

162
57

32

262
246

56

56

57
-

249

50

128
137

109

in 111
len() 110

49

111

108
214, 215, 295
210

in

156
157
157

()

171

290

.~

170

282

69

154

125

46

49

228

47

77

312

173

411

365
38

280

121

199
198

175
174
262, 27 4

112

()96

58

105

153
152
<1< - 156
156
152
158

111

99

57

Tkinter

281

318

255
256, 261
255

281
280

268

98

99

246

323

248
249

284

138
351
138

206
149

205
285

135

108

in 137
len() 137

Python 34
34, 387
58
-

221, 223, 362

280

315

239
238

137
138
138
183
139

142

68

412

144

140
144
141
142

Text

color 321
320
Text 322
Python 36
74, 265
r 88

347
325

319
318

316
315

328

318

119

122
139

232

229

335
335

89

77

93

77

333

94

42
201
115
53

Python
Windows 34

67
41

62

52

91
88

232

86

86

85

322

194

37

47, 169

200
202
201
197

204
203

61
62

206
205

413

t'or

194
197

198

200
200

106
200
107

106

296

299

298

313
315

108
109
109

while

313

85

168
265

86

86

games 395
169

165

168

169
37

55

53

84

107

169
183

206

randint(), 7 4
randrange(), 75
random 74
72
55

345

150

346
36

55

67

355

356

221

147
125

200

125

126
102

139

414

140

126

Button () 280
Chcckbutton () 280
Entry ( ) 280
Frae () 279
Label () 279
Radiobutto ()

290

291
291

289

284

280

Text ( ) 280
295

Grid 293

32

Python

. r

. 11

192!02, -, . (.

n n

r),

3, , n.

005-93, 2; 95 3005 -

30.01.14. 70, 100/16. Yc.n. n. . 33,540. 1000. 677.


R
142300, R , . , . , . 1

7.

www.chpd.ru, E-mail: sales@chpd.ru, 8(495)988-63-76, /. 8(496)726-54-10