Python
Programming
for the Absolute Beginner
rd
,"
t
Edition
COURSE TECHNOLOGY
CENGAGE Learning
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
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
...................................... 400
..............................................
25
.................................................. 26
.................................................. 27
............................................. 29
1.
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) ,
: .
.
, .
,
(Mic\1ael Dawson)
, .
, .
-.
U CLA . ,
, : <k ++
: - .
.
, , -
, . ,
, :
?~
, , . ,
,
~.
, ,
. ... ,
.
. ,
, ,
, ,
.
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
, 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-
- ()
.
, ,
. , ,
, , , .
. ;
- ,
.
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.
3.
1.2.
Python 3.1
~~~~~~~~~~~~~~~~~~~~~~~~
-, n
. , , ,
, .
www.courseptr.com/downloads . .
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
80U
NEWS
Pyd'lon 11
OOCUMEN N
OOWNLOD
l'lt
COMMUNJV
FOUNDJON
CORE OEYELOPMENT
Help
~Re'"'"'
lnde
Qulcltllnks~.7.2)
Read
DocumvntaHon
Wlnd~ /rstaller
~on
Soun:1D1'itribution
SOtJtttDlttrtulion
Python JG:s
2 or ptthon 3
Puhshed
Putshed.Sun,Ju
Python
1.3.
users uch
RtkSpte,
/ndustnal L!ght
nd
Wathlngton Pott:
Pytfion2 0137
Htlp M1ln1-ln W1.tt1
jl:nlng
~~i~M!iiili
Python Wlld
t-
Python lllerctiendlse
Pack11g1
2011 16:00+0200
Python,
~~~~~~~~~~~~~~~~~~~~~~~~~~
Python. ,
Python .
, ,
IDLE
Python
IDLE. ,
. -
. ,
.
IDLE :
Python. Python ,
, , .
. ~
Python 3.1
, ,
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.
Game Over
,
Python!
. , - ,
.
, :
, . (
), , .
Python.
-
.
pri nt ( ) , ,
, . ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~~
Python
. ,
. n
PRINT(Game Over)-
Print(Game Over)
37
IDLE
, , ,
. ,
, , .
pri nt () -
, , ,
Game Over.
~~~~~~~~~~~~~~~~~~~~~~~~
Python
r ,
. .
2.
() . .
"Game Over" - : , .
, , .
- , Python , - .
.
, , ,
Python. ~.
-. ~
. , , :
.
, ,
. , ,
38
( :
'primt'
1.
Game Over
).
, pri mt. ,
, . . ,
, , :
.
, , , ( ,
, ) .
,
. , .
,
Python, -
pri nt -
. , , "Game Over"
.
. ,
:
.
, : . ,
, ,
. , IDLE
. , , .
,
, , , , .
w r
,
, .
()
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
Run Module (
~ ).
. , .
Pyt.hcn
.1.1
(r11:74'l,
"copyriqht",
"cre:dit~"
or
"licee()"
[JISC v.1500
bit (Intel)] on
1n2
OVer
> 1
11
. 1 .6.
Game Over,
IDLE
1.6.
40
1.
Game Over
, 1> . , ,
IDLE,
- , .
- , . , ,
, .
,
. ,
, .
Game Over
, ,
,
.
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
#
, .
, .
. , -
, .
, ,
.
#. (
# ) .
. ,
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.2.
. - (www.courseptr.com/
downloads) Chapter 2;
game_over2. .
45
# Game Over - 2
#
2.2. .. .
end=" " )
_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("
. .
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 ()
... ,
?. , ,
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. , - .
; ,
.
,
, .
). 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.
\t
")
s-
, , , ,
.
, ,
.
, , , ,
,
s-. :
( ,
\ \ ), :
printC"\t\t\t \\ \\ \\ \\ \\ \\ \\")
printC"\t\t\t \\ \\ \\ \\ \\ \\ \\")
s-
\ n.
50
2. , -.
, , . \n ,
, .
:
print("\nOreoe :")
\ n,
:.
, ( ,
) .
s- \', \".
.
, :
rit(" \'\'.
\"\".")
, .
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" + " . " \
" +
" .
"
" +
""
" +
+ "
""
"
" +
"
" +
""
!")
print("\nEc . .
,")
rit(" ? . ")
print("pa .
")
rint(":")
rint(""
input("\n\nHae
10)
Enter.
.")
, ,
- ,
-
pri nt:
print("e
" +
"
'+'. ")
'+' . , .
: ,
, .
~ - -
. , , , ""
, :
print("\na
" .
,
,
22 .
.
. .
\ (
), .
53
, ( ,
);
.
, ,
. , -
,
.
r
, ,
:
rint(""
* 10)
:
"
"
".
*,
, .
, ;
.
,
* .
, , .
. , -
, -
. , Python
; ,
.
r r r
. -, ,
, .
, . - ,
~
( )
. .
.
2.5,
54
2. , -.
2.5. Python ,
, ,
(www.courseptr.com/
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 . ")
107
. ")
print("pea . ?")
inut(" .
Enter ." )
print("o ?")
inut( " .
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").
, :
,
. - name,
. ( ) 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 () , .
, .
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 .
- .
. :
.
, , ~.
, ,
- ~ .
: ,
~.
~
-. (
,
. .)
2.8.
2.8.
downloads)
Chapter 2.
(www.courseptr.com/
#
#
# .
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( ).
l ower( ) quote
. .
63
print(quote.title())
quote, ,
, ,
- .
, titl ( ).
:
print(quote.replace("y ".
" ''))
quote
, .
.
:
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( "
'':
")
):
")
, .
: .
2.9.
, .
, . ? ,
.
.
,
, , , , .
.
, ,
, .
,
. , ,
. ?
,
i nput ( )
, ,
. : ,
.
total =
+ ent +
guu +
games
, !
, , ? , -
,
. ? , ,
!
I:
+ , .
, .
, , , .
nnoxo, ()
? , . .
66
2. , -.
, ~.
,
i nput ( ), .
,
.
( w)
~ ,
.
.
2.1 .
. 2.1.61
300
.
-
( )
# 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
. ,
:
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 ()
?"))
, .
age :
, i nput ( ),
.
weight
: .
------------------------
: ,
. ,
name
name -
print("\nEc . :
"
". name.upper())
- , , -,
. ,
, , .
, , , ,
4~ .
2. , -.
70
called
name * 5
print{"\nEc ".)
print("o :")
print(called)
11 ed
name. called.
print{"\nTo
365 , 24 ,
".")
60 , 60
seconds,
moon_weight sun_weight
1 :
moon_weight = weight / 6
moon_weight.
print("\naee . ".
sun weight
weight * 27.1
"?")
, ,
.
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.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('-- -
password = inut(" : ")
i f password == "secret":
\n')
input(" \ n \ nHae
Enter .
. ")
---.------~
: :
.1
---
. , , secret.
. , . , ,
. -
. .
77
if
if
>.> :
if
password == "secret":
print("ocyn ")
. , ,
.
, ,
"secret",
i f,
n
i
f , ,
. , , ,
: ,
. , : >.>,
, , .
Python -: True - ,
F 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.
( ), ,
. ~:~.
").
,
,
. :
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 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
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
" ."
, .
, ,
. , - .
( ) , ,
. !
, -
..
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(" .
"\
" ".
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
~ ~ .
:
- Chapter 3;
, .
, :
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;
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
S. Mei er.
ci vi 1i zat i on
S. Mei er
, :
and.
usrnm
and , ,
, . :
,
password
==
"civilization".
-=
-----------------------
and ,
, r , r r.
.
.
.
i f-e 1if-e1 se
- ~. ,
,
.
, ,
, .
or
, .
,
guest
. , :
security = 1
98
3.
while
. ,
or.
or
, .
or
or
~>; , .
. .
:
"guest"
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 , .
1." 100,
i nput()
, i nt ( )
. gL.ess. ,
tri es, .
1.
102
. , while . ~
. ,
, . ( guess)
(the_number).
, ,
"))
guess != the_number,
guess the_number,
, ,
. :
print("Ba ! ".
print("B
the_number)
", tries. " !\n")
,
.
,
inut("\\n
Enter.
Enter:
.")
, . ,
,
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 :")
Enter.
. ")
for.
Chapter 4.
106
4.
f, .
4.2. for
, ,
for
for,
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
.\n")
- r t
i, j, k.
, . ,
, , , i, j k-
range( ). , range()
range()
, (
). , ,
2. 3. 4. 5. 6. 7. 8.
9].,.
, ;
1, , . . ,
i 9, .
~~~~~~~~~~~~~--~-~--~-~-~--
range() ,
r . ,
, , . ,
.
range(), http://www.python.org.
-----------------------
, , .
.
. , ,
5.
n: n
109
,
, :
range()
, .
,
. , [.
5. 10. 15.
45, 50 - ( ).
50-,
, , :
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[ ].
: .
:
>>> print(word[lJ)
>>> print(word[2])
>>>
print(word[J)
>>> print(word[4])
>>> print(word[5J)
~~~~~~~~~~~~~~~~~~~~~~~~~-
, , n
- . . ,
. 5,
. :
1.
, ,
.
:
.
. , , ,
, ,
. , ,
"":
114
>>>
4.
for,
. r
print(word[-2])
>>>
print(word[-3])
>
>>>
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() . ,
( )
( ). , , :
1, 2, 3, 4 5.
, ,
"".
, , .
,
:
for i i n range(lO):
position = random.randrange(low. high)
print("word[". position. "J\t". word[position])
, :
. ,
- ,
. , ,
>
>
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]=""
, ).
~ ~. ""
- word[l].
. ,
(
). ,
, .
+, .
, .
, , , ,
.
.
, . 4.8.
117
. 4.8.
for ,
- ,
. ,
, , - .
-
Chapter 4.
(courseptr.com/downloads)
no_vowe l s. .
#.
for
Enter.
new_message)
.")
VOWELS
new_message , :
"iu"
VOWELS .
, ,
,
, .
, .
118
4.
for,
, (
).
. -,
. , ,
, "aei u", VOWELS.
, , ,
, , , -
. -,
- , .
,
, .
,
.
~~~~~~~~~~~~~~~-----------------------
, , .
( r )
, Python, , .
. , ,
, .
. r.
'
Python, ,
.
---- - - .. - .. --- -- ----- - - - -- ----- -- - -- ----- ---------------- - - --------------- - - - -
.
, .
. , -.
, . ,
.
: , ,
,
. , ~~ :
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 . .
-5
-4
-3
-2
-1
rint("
''.
.")
print("
start = None
while start !=
Enter.
. ")
121
".
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
"] ",
end=" ")
:" ,
sta rt
fi ni sh:
printCword[start:finishJ)
- .
, . ,
;
. , , word "",
word[ :4]
word[0:4J.
, .
word [2: ]
, word[2: 5].
, ,
.
word [ : J -
word [: 5].
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 = ("" .
"".
"" .
" ")
:")
. ")
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:
"".
"".
" ")
. ,
, , .
, ( );
Python
.
~~~~~~~~~~~~~~~~~~~~~~~~~~~
, , .
, , : .
, - ,
.
. ,
,
- .
n
,
, -
, . :
126
4.
for,
printC"\nCoepoe :")
pri nt i nventory)
, .
for, , i nventory,
print("\na.
:")
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 .
: ")
.")
len()
1en ( ) , :
, .
. , ,
.
1en ()
print("Ceac " .
i nput( "\ nHae
Enter.
len(inventory) .
.")
"/-.")
128
4.
for,
r .
/-.
~~~~~~~~~~~~~~~~~~~~~~~~~~
, r
inventory
, .
in
( ),
i . , . ,
, :
#
if
" "
in
in inventory:
.")
" "
in inventory , "
i nventory. ,
"
.
- , .
(),
:
index = int(input("\nBee
print( " ". index.
" ".
4.13.
""
""
-4
-3
"))
inventory[index])
4.13.
-1
-2
.
. , ,
.
129
~ , ,
. :
4.14 ,
"" ""
-4
-3
-2
-1
. 4.14. , ,
r
, .
:
''.
"".
''.
"".
" ")
' ')
, .
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,
, ,
#
pri nt
''!
. .
(
Enter.
printC"Bo :".
.)
jumle)
.
,
Enter:
133
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
" "]
:")
.")
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
"
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.
.")
""],
, .
,
- .
, .
. ,
, .
r
.."d
-
.
. -
141
: ,
, .
.
5.6.
5.6.
. ,
, . - scores -
, . -
. choi , .
#
#
None. -
Chapter 5. high_scores. .
(courseptr.com/downloads)
scores = []
choice = None
whi 1.
.
:
142
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")
2,
score.
append( ),
score
"))
scores.
143
3,
. ,
, , . ,
.
scores. ,
.")
score
remove( ).
, ,
( score). ,
score, .
, . ,
score. remove()
, .
remove()
del.
remove()
, .
~~~~~~~~~~~~~~~~~~~~~~~~~~
remove().
, , .
if score in scores:
scores.remove(score)
,
.
4:
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.
:
, ,
. ,
. :
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
, ,
:
>
("".
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
score name,
149
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 _____.
.
" "
" "
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
"Uninstalled" :
" -.
1990-2000- . "}
5.1 .
, , :
geek. .
"Keyboard Plaque" : ".
".
. ,
Plaque" -
. ,
"Keyboard
-
, ". "
. ~>.'> ()
. , "Keyboard Plaque" ".
" .
. ,
, .
>.'> ,
. ,
, ,
, ,
. ;
.
154
5.
r
,
.
. ,
geek
> geek["404"]
" . .
404
' '."
'
, .
,
. .
,
. ,
, , , .
,
Python . :
, .
~~~~~~~~~~~~~~~~~~~~~~~~~~
n , r , ,
-, ).
in
,
. , , ,
.
i n:
else:
Dancing Baloney.")
Dancing Baloney.
print(" .
"Danc~ng
geek
Baloney",
"Dancing Baloney" in
155
, .
, ,
i n . . ,
, .
,
. (, ) ,
.
get()
-
get ). , 110
. ,
, . :
" ."))
getC) . - 1
. ,
. ,
" ".
get ) ,
; .
, , ,
, ,
) None. :
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,
:
.")
,
:
geek[termJ = definition
~~~~~~~~~~~~~~~~~~~~~~~~~
Pytho ( )
. , , ,
. ,
.
4, l i f:
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
, .
,
.
; .
random. choi ( )
WORDS word.
#
word = random.choiceCWORDS)
- so_fa r -
. - ,
. , (
), , .
# . -
wrong .
, , :
wrong =
, , ,
used.
used = []
1 .
, ,
:
print("opo
''.
!")
used)
rint"\n :\n".
so_far)
, . ,
,
so_far.
163
, ,
,
( , , ).
, .
, .
, ,
. ,
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
'-':")
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()
, ,
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,
: ""
"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.
age):
. ".
".
age. "
age . "
? \ n")
birthdayl("oap " .
i
rthdayl .
1)
" ")
" .
175
age ; 1)
".
" ")
irthday2(name; "")
12)
rthday2( name ; "". age ; 12)
i rthday2( "". 12)
input("\n\nHae Enter. .")
irthday2(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()
age
1):
name ,
age,
" ",
. :
i
rthday2()
. ,
: .
1 .
?.
~~~~~~~~~~~~~~~~~~~~~~~~~~
<,
. :
def monkey_around(bananas
177
, ?
-
. :
bi rthday2(name
"")
?.
1 .
birthday2(age = 12)
name -
: .
age,
12,
" ".
12 .
?.
:
irthday2(name
"".
age = 12)
12.
name
: . !
12 .
?.
, :
i
.
" "
.
12,
12 .
?.
~~~~~~~~~~~~~~~~~~~~~~~~~~~
,
. ,
, , ,
.
, , <1
, .
. .
: .
. , ,
178
. . -
.
. , , (.
6.7).
def funcl () :
varialel
def func2():
variale2
varialeO
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/
#
#
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
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()
. :
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()
, .
, ,
.
response = None
while response not in range(low. high):
response = int(inputCquestion))
return response
186
6.
. 111-
pieces()
, ,
, , .
.
def pieces():
""" ."""
computer =
human
no( ).
- ask_yes_
: .
new_board()
, :
def new_board():
""" .'""'
board = []
for square in range(NUM_SQUARESJ:
board.appendCEMPTY)
return board
display_board()
legal_moves()
: human_move() - ,
187
, computer _
move() - .
. ,
, ,
4-
,
[.
2. 6. 8]
( , .
6.9). ,
, . ,
, .
.
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
(0. 3.
4.
(2. 5.
(0. 4.
(2. 4.
(1,
6).
7).
8).
8).
6))
for , ,
.
if
,
. , , ,
.
wi nner,
.
188
6.
. -
for ) .
i f not i n rd :
return
.
, , , ,
None.
return None
human_move()
-,
, .
.
, ,
, .
, .
- 8):".
NUM
print("\nCeo ! . pyroe.\n")
computer_move()
computer_move()
, .
~~~~~~~~~~~~~~~~~~~~~~~~~~
, , . , ,
,
. , ,
. ,
,
.
189
,
. , computer_move()
, .
,
. (, .
.)
, ,
.
. , ,
, .
,
5.
( ), ,
, .
, ,
:
# . u
board
board[: J
-----------------------
, , .
, .
--------------------------,
( ), ,
, , .
{) .
, { ), ,
. ,
. ,
.
1. , ,
.
2. ,
, .
3.
,
:
. ,
190
. . r-
#
BEST_MOVES = (4. . 2. 6. 8. 1. 3. 5. 7)
print(" ". end=" ")
. ,
, ( ,
) , . ,
; . ,
,
. , ,
. ,
( , )
, . ,
, ;
. ,
.
1 .
board[moveJ =
,
BEST_MOVES, ,
:
, .
#
for move in BEST MOVES:
if move in legal_moves<board):
print(move)
return move
191
r-
- .
, ,
. , , .
, ,
, . 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
, , .
" !\n")
print("H!\n")
if
the_winner == computer:
print("Ka .
~.
\n" \
" .
.")
! - .
": . .
!")
192
. . -
\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. :
( courseptr.com/downloads)
197
print("\na .")
( ),
ero
. ~:
open( ), ,
text _ fi l . :
, .
- "read_i t. txt" - .
, Python ,
. , r
, , .
"r". r Python ,
. , ,
.
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)
. ,
:
>
>>>
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()
, .
, .
,
. , , :
print(text_file.readline(l))
:
>>>
print(text_file.readline(5))
>>>
text_file.close()
,
readl i neC)
readl i ne()
readl i ne()
read( ).
read()
. :
printCtext_file.readline())
>>> printCtext_file.readline())
>>>
print(text_file.readline())
>>>
text_file.close()
,
. , s
"\n".
200
7.
. :
>
>>>
1i nes
:
>>>
print(lines)
1\n . '
1i nes
2\n' .
'
3\n' J
:
>>>
print(len(lines))
>>>
>>>
text_file.close()
for
>
>>>
, ( 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 .")
wri te l i nes ()
. read l i nes ( ), wri te l i nes ( ) ,
: , .
:
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 .")
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(" . ")
= 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
: , .
pickle.dump(variety. f)
pickle.dump(shape. f)
pickle.dump(brand. f)
f.close()
, ,
, picklesl.dat
variety.
. ,
shape brand.
, :
: ,
.
rint("\n .")
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")
s;
.
------------------------
shelve.open()
Python
, .
207
. ,
. (
), "".
.
7.5.
s["variety"]
s["shape"J =
s["brand"] =
["".
["".
"".
"".
["".
"".
""]
""]
""]
. 1
"".
"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:
Python
"!" . ,
, .
Python
. ,
.t ,
!. ,
- .
.t
,
. ,
.
.
downloads)
7.5.
try/except.
(courseptr.com/
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
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):
""" ."""
via. txt,
category "". category
, main() .
216
7.
welcome()
we l come()
;
.
def welcome(title):
""" ."""
print("\t\topo
''
!\n")
r
i n(),
. :
, ( ),
.
def main():
trivia file = open file("trivia.txt". "r")
title: next lineCtrivia file)
welcomeCtitle)
score =
, ,
whi le,
category .
,
.
: (),
.
= 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 .
-.
.
r
name.
Critter -,
name. , ,
, . .
talk()
#
#
class Critter(object) :
""" """
def
i nit
8.6.
se lf. name) :
rint(" !")
227
self.name = name
def
~str~Cself):
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
print(Critter .total)
print("\nCoa . ")
print(critl .total)
input("\n\nHae
Enter.
.")
end=" ")
(courseptr.com/
231
total =
total
Critter .
, (
) .
- Pytho11 .
, ,
, , ,
.
;
.
Critter
total
print Critter.total
status()
"
-
:
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):
""" """
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.
, .
:
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
).
, :
>>> crit.~private_method()
Traceback (most recent call last):
File "<pyshell#l>". line 1. in <module>
crit.~private_method()
~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) :
""" "" "
_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(" .")
, : @,
, , ,
setter.
name,
. , , .
: - , .
new_name ,
. ,
_name ,
.
_name new_name , .
, - ,
.
name, ,
. :
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 "
".
print(crit.ame)
iut("\n\n Eter.
.")
,
. ,
. ,
-
Chapter
(www.courseptr.com/downloads)
8. critter_caretaker. .
241
Critter
Critter -
, m
. ,
-r
-
hunger boredom
, ,
.
#
# .
class Critter(object):
""" """
=.
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.
_pass_time( ).
def talk(self):
self.naire.
self._pass_time()
print("Me ".
"naw.\n")
eat()
eat () ,
food. , food
4.
. , ,
_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)
.
248
- . -
9.
, , ,
.
. /-
- UML (
),
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
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)
Card
Card,
.
#
class Card(object):
. """
RANKS = ["". "2". "". "4". "5". "6". "7".
SUIS = ["".
"".
""]
def
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 .")
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 = [ " " .
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()
, :
257
.")
print("Bo :")
print(deckl)
52 . ,
- . ,
deckl. shuffl ()
Deck shuffle(), random
, , . ,
,
.")
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
.")
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
Card , (
) . :
class
Unprintae_Card(Card) :
Unpri ntab l _ rd
rd. ,
. :
"""
def _str_(self):
return "<
"""
>"
Python 3 object, 2- .
, object 2- .
object. - . . .
260
9.
- . -
rd _st r _
) . ,
, ,
, .
,
, -
. -.
,
rd
. ,
rd. ,
, , .
Card, ,
i s_face_up.
, -,
, , ,
ra nk su i t. rd :
, ,
rank
suit
,
.
super()
-
,
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)
, .
print("\nneaa Unprintae_Card:")
print(card2)
rank "", suit -
"d", : <
>, Unprintae_Card
_str_()
"< >".
Positionae_
Card:
pri nt( "\n
print(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.
.")
,
.
, ,
,
. ,
()
, , ,
: 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.
,
.
, .
, . ,
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)
, 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 :")
ask_yes_no()
games ,
again
games.ask yes
n("\n ?
(y/n): ")
&-
,
Python,
, ~- .
, , (,
).
cards
-~- ~
rds.
rd
- ( courseptr.com/downloads)
Chapter 9.
cards. .
# cards
#
class Card(object);
"'"' . """
RANKS
SU 1TS
def
= ["".
= [ ""
"".
"".
""]
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
, , ,
, ,
: ( ). 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
games,
, ,
B_Card
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.
(,
, ( ,
"6" 6). ,
1; 1
. is_face_up False,
None.
n J_Deck
BJ_Deck
--.
rds. Deck.
,
BJ_Deck
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 _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:
t += card.value
#.
contains_ace = False
for card in self.cards:
if card.value == BJ_Card.ACE_VALUE:
contains = True
# 11. 11
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
class BJ_Player(BJ_Hand):
"""
"-".
def is hitting(self):
response = games.ask yes no("\n" + self.name +"
(Y/N): ")
- i s_hitt i ng() -
.")
True ,
, Fa l se - . bust () ,
, lose() . , lose()
, , wi nC) - . ,
, .
,
, , (
).
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()
. , ,
,
st i l l _p l ayi ng,
, .
_init_()
, .
class BJ_Game(object):
"""
-.
"""
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_
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 ( )
:
print(self.dealer)
else:
#
print(self.dealer)
self. additional cards(self.dealer)
if self.dealer. is-busted():
# .-
275
-
# . ;
, ,
. <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. 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 ,
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
11
. 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.
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/
tkinter
GUI
#
#
tkinter:
GUI
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 . ")
, .
, .
, :
= 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, :
Frame(root)
app .grid()
=
Button.
= !")
!.
; ,
, tk i nter . ,
GUI
287
, . ,
, , .
, .
#
bttn2 = ButtonCapp)
ttn2.grid()
, :
. ,
. . ,
configure( ):
text "
configure()
! ",
.
.
ttn
= Button(app)
ttn.grid()
text
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
#
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 :
cat i on ();
GUI
289
, . create _
widgets( ), .
, r
create_wi dgets ),
def create_widgets(self):
"""
"""
= " !")
self.ttn2 =
Button(self)
self.ttn2.grid()
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")
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()
. ,
= , ,
291
Grid
create_widget() :
def create widget(self):
""" . -
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, .
root.
, GUI .
1i cati
.
Grid
GUI- ,
- .
292
10.
. r
. :
, ,
. ,
. ,
.
,
.
Grid,
Grid
GUI.
100 ,
secret.
, , ,
. .
'7~ r:1G1<
10.11
10.12.
.,,j
! !I
. 1
,
10.11.
'74
i=l!;;JJ..13 ,,
/secret
. 1
100 ,
99,
10.12.
, ,
longevity. .
(www.courseptr.com/
293
Grid
r r
, :
#
#
Grid
""" GUI - .
"""
create_widgets( ).
Grid
create_widgets()
:
def create_widgets(self):
""" .
"""
" .
")
, ?
Grid
, :
self.inst_l.grid(row =.
column
=.
columnspan = 2.
s~icky
= WJ
grid() .
:
row
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
W)
#
self.pw_ent = Entry(self)
- Entry:
, .
,
:
self.pw_ent.gridCrow
1. column
1. sticky
W)
" " .
command
self .
r r.
295
Grid
revea l (),
, .
r o6nacr
- Text:
# .
self.secret_txt
wrap
:
. ,
NONE
.
,
~ ~:
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("")
, .
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:
"""
, :
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
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
Appl ication.
1i cat i :
class ApplicationCFrame):
""" GUI -.
def _init
"""
."."
Cself. master) :
"""
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()
,
".",
,
".". ,
" '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
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"
tell_story()
Application
, ,
, , , ,
.
10. .
306
story
story
story
story
story
story
story
story
story
story
story
story
story
story
story
story
story
story
#
+=
+=
+=
+=
+=
+=
+=
+=
noun.titleC)
". "
noun
" "
person + "
". "
adjectives
"
"
" .
+=" .
+=
+=
+=
+=
+=
+=
+=
+=
+=
person
" .
"
"
"
noun
" .
person + "
"
"?
verb
".
"
"
."
mainloop()
#
root = Tk()
rt.titl(" ")
= ApplicationCroot)
root. ma i nl ()
307
. ~
-
.
, , , ,
. ,
Gri d.
- . ,
- GUI.
>>,
11 .
3: .
, !.
, .
11
.
<< >>
, ,
.
. ,
,
Python.
;
;
;
;
, ;
.
, ,
. :
.
, :
.
.
,
, . . 11.111.2.
pygame
livewires
),
Python
, , . .-
pygame
309
livewires
11.1 .
11 .2.
310
11.
, .
, , ,
r
. r r.
r.
Python .
, .
, l i vewi res - ,
r, , ,
pygame, .
1i vewi res
.
pygame,
1i vewi res
.
, ,
, .
~~~~~~~~~~~~~~~~~~~~~~~~~~-
UveWires (http://www.tivewires.org.uk),
, LiveWires livewires,
-. ,
. , ;
.
pygame, http://www.pyga-
me.org.
, 1 -
<11>, .
11.3.
. .
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:
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.
i ni t ()
games
. ,
, .
,
~),
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
False)
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
, : ( ) (
).
,
, (; ).
. ,
, ,
Game Over,
. ,
.
, ,
, , , ,
.
, .
316
11.5.
11. .
,
. ,
, .
, <:< :
,
.
. , I-
Microsoft Office
. ,
. (!.
: ,
, .
,
, :
317
01
-
-, ,
,
.
.
11.6.
mainloop()
. -
11.6. -
, ,
#
#
Sprite
318
11.
,
-:
pi zza_i mage
:
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:
: , , , ,
.
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.
you_won. .
(www.courseptr.com/
324
11.
color
games
l or:
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.
.
~~~~~~~~~~~~~~~~~~~~~~~~~
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.
, ,
dy
games.screen.add(the_pizza)
games.screen.mainloop()
1)
(www.courseptr.com/
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/
#
#
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):
"""
mainloop()
. ,
.
ri ght, ,
screen. wi dth, -
. l eft, ,
games.
, .
dx,
~ .
bottom, ,
, .
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/
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) :
'""'
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)
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 . .
-
#
#
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.
Pi zza Pan.
, .
;
.
ma i n( ) ma i nl ( ). r
mai n( ).
l i vewi res,
,
.
,
. -
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 ().
_init_()
-,
:
def
_iit_(self):
"""
Text
superCPa.
games.scree.add(self.score)
super() , - i i t ()
Sprite. score -
, . ,
.
update()
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):
"'"'
. .
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):
super(Pizza.
= Pizza.image,
self).~init~(image
dy
=
=
= ,
Pizza.speed)
Pi zza.
, 90,
339
update()
def update(self):
, .
end_game( ), .
handle_caught()
Pi zza:
def handle_caught(self):
'"'
"
se 1f. destroy()
, , , <m
Pi zza
destroy() -
end_game()
. ,
.
"""- . """
Message,
, .
~~~~~~~~~~~~~~~~~~~~~~~~~
end_game() , . ,
5 , , , ,
. 12 , ,
, ,
.
340
11.
Chef
Chef -
-, , ,
class Chef(games.Sprite):
.
i mage
. -. .
image -
_init_()
-:
def
~init~Cself. =
=,
dx = speed)
self.odds change = odds change
self.time-til drop = .
Chef. image.
image
55,
- odds_change -
dx
2.
, ,
odds _
change 200, 200,
. , ,
. ,
update( ).
.
; , Chef
. ,
check_drop( ).
update()
,
- :
341
elif random.randrange(self.odds_change)
self.dx = -self.dx
self.check_drop()
==:
~ ( ) .
. ,
odds_
hng- , .
, ,
check_drop()
Chef.
check_drop()
ma i nl (), , ,
50 :
def check_drop(self):
'""'
if self.time_til_drop
>:
# ""
30 %
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,
The
344
12. ,
, .
~~ g wi~v
12.1.
. ,
12.2.
345
i nput ( ) , . -
. , games ,
.
r
~
. ,
. ,
,
D-
S-
. ,
. ,
W D
12.3.
.12.3. ,
(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):
"""
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
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. .
,
:
#
#
= 4.
fps
50)
351
!i Ar<Sof! ~fioto$tud10
12.6.
IIJ@Jr8J
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().
5:
choice = None
while choice !="":
print(
1 -
23 4 -
5 -
6-
")
choi == "":
pri nt (" .")
, .
1:
choi == "1" :
missile_sound.play()
1 if
rint(" .")
, l ()
.
. , ,
. ,
pl ()
play() ,
,
, .
355
, 1
. , , 1 )
3,
-1.
( ).
( -1 =
rint(" .")
,
,
pl ()
r
, ero
stop( ). ,
. stop() ,
, 1i vewi res .
, 3 ,
:
1
1i vewi res , .
, -
. , ,
: , W AV,
,
OGG
MIDI.
, , ,
.
, ,
.
, ,
music
music
games.
12. , , .
356
, IDI- theme.mid.
games. mus i . 1oad (),
, , ,
:1 :
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,
:
, 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
, ,
, -
. , ,
. ,
SPEED,
.
_init()_
-:
def
"""
=.=.
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
main()
ma i n( )
def main():
#
# !
mai n()
,
.
.
- 2
- 2 ~ - 1~.
,
. --+
, +- - .
.
12.9.
downloads)
Chapter 12.
(www.courseptr.com/
astrocrash02. .
362
12. , , .
.12.9.
Ship
, ,
Shi , :
"""
. . -, -
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
Ship
VELOCIY_
STEP
Shi :
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 :
""
.
~~~~~~~~~~~~~~~~~~~~~~~~~~
.
, ,
. , 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
-,
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. : , -,
, -,
.
,
Missile.sound.play()
, , ,
:
#
angle = shio_angle * math.pi / 180
368
12. , , .
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( ). :
- , 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.
(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.
mi ssi l e_wait
, .
Shi
update()
update()
missi le_wait .
Ship
# .
if self.missile_wait > :
self.missile wait -= 1
, ,
:
# .
==:
missile_wait
MISSILE_DELAY,
mi ssi le_wait
371
r
,
.
. , - , ,
.
. : ,
, , .
r
~
- 6
, :
, ,
.
~~~~~~~~~~~~~~~~~~~~~~~~~
, ,
, ,
, . ,
.
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. ,
, .
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
. ,
, .
, , ,
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):
"""
= self .y)
, ,
Explosion.
1os i on, ,
Asteroid
Asteroi d Wrapper:
class Asteroid(Wrapper):
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-
""
"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:
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 =
# .
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
# .
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
# .
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
Game. Asteroid
new_asteroid
: ? ,
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
~~~~~~~~~~~~~~~~~~~~~~~~~~
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
8.8.
Text
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 ()
, .
, .
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] [.
[. n_repeats] [.
images
is_co'lidealeJ). .
-,
, .
.
None.
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
. ,
.
. .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
. . .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
( )
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
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
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
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
406
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
&
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
-
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 -
R
142300, R , . , . , . 1
7.