Вы находитесь на странице: 1из 143

Python

0.2

07 . 2016

1 python

2 Python
2.1 Python Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2 Python linux (ubuntu, linux mint ) . . . . . . . . .

2
2
6

3 . IDLE

4 Python
11
4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5 . ?

13

6 if-elif-else, , if/else
18
6.1 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
6.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
6.3 if/else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
7 for while, break continue, else
7.1 while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.2 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.3 continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.4 break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7.5 else . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

21
21
21
22
22
22

8 , keyword
23
8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
8.2 keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
9
25
9.1 , . . . . . . . . . . . 25
9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
10 : , ,
29
10.1 (int) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
i

10.2 (oat) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
10.3 (complex) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
11 Python:
35
11.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
12 .
12.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
12.3 . . . . . . . . . . . . . . . . . . . . . . . . . . .

38
38
39
40

13 . format
43
13.1 format . . . . . . . . . . . . . . . . . . 43
14 (list).
46
14.1 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
14.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
14.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
15
49
15.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
15.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
16 (tuple)
51
16.1 , ? . . . . . . . . . . . . . . . . . . . . . . . 51
16.2 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
16.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
17 (dict) .
54
17.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
18 (set frozenset)
57
18.1 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
18.2 frozenset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
19
60
19.1 , def . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
19.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
19.3 , lambda . . . . . . . . . . . . . . . . . . . . . . . 62
20 python. try - except

63

21 (bytes bytearray)
68
21.1 Bytearray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
22 . .
70
22.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
22.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
23 With ... as -

73

ii

24 PEP 8 - Python
24.1 . . . . . . . . . . . . . . . . . . . . . .
24.2 . . . . . . . . . . . . . . . . . .
24.3 . . . . .
24.4 . . . . . . . . . . . . . . . . . . . . .
24.5 . . . . . . . . . . . . . . . . . . .
24.6 . . . . . . . . . . . .
24.7 . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

75
75
76
81
84
85
86
90

25 Python. PEP 257


95
25.1 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
25.2 . . . . . . . . . . . . . . . . . . . . . . . . . . 96
25.3 . . . . . . . . . . . . . . . . . . . . . . . . . 96
26 : , import from
26.1 . . . . . . . . . . . . . .
26.2 . . . . . . . . . . . . . . . . . . . . . . . . . . .
26.3 from . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
26.4 Python . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

27 - .

98
98
99
99
100
103

28 , ,
105
28.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
28.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
28.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
29
107
29.1 . . . . . . . . . . . . . . . . . . . . . . . . 108
30
30.1 .
30.2 . . . . . . . . . . . . . . .
30.3 . . . . . . . . . . . . . .
30.4
30.5 . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

112
114
115
117
119
120

31 python- pip
31.1 pip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
31.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
31.3 pip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

122
. 122
. 122
. 123

32
32.1 UnboundLocalError,
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
32.2 Python? . . . .
32.3 (lambda),
, ? . . . . . . . . . . . . . . . .
32.4
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

124
. 124
. 125
. 126
. 127
iii

32.5 ? . . . . . . . . . . . . .
32.6 ? . . .
32.7
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
32.8 y x? . . . . . . . .
32.9 ? . . . . . . . . . . . . .
32.10 Python? . . . . . . . . . . . . . . . . . . . . . . .
32.11 ? . . . . . . . . . . . .
32.12 ? . . . . . . . . . . . . . . . . . . . . . . . .
32.13 ? . . . . . . . . . . . . . . . . . . .
32.14 Python ?: C? . . . . . . .
32.15 ? . . . . . . . . . .
32.16 -22 // 10 -3? . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
32.17 ? . . . . . . . . . . . . . . . . . . . . . . . . . .
32.18 /? . . . . . . . . .
32.19 ? . . . . . . . . .
32.20 ? . . . . . . . . . . . . .
32.21 ? . . . . . . . . . . . . . . . . . . . . . . .
32.22 a_tuple[i] += [item] , ? . . . .

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

. 127
. 128
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

129
129
131
132
132
132
133
133
133
134
134
135
135
136
136
137

iv

python

, Python,
.
, python:
xml/html
http
GUI ( )
-
FTP
,


, ...
, python ,
, , - .
Python , . , python IT, , , Google Yandex. python .

Python

, python 3 . , SMS :)

2.1 Python Windows


python . , python , . . https://python.org/downloads/windows/, latest python
release python 3.
python 2 .
python 3.4.1.

Python, 0.2

Python ( ). - . , download
page.

2.1. Python Windows

Python, 0.2

, . Windows x86 MSI


installer ( 32- ), Windows x86-64 MSI installer ( 64-
). .

, python . .
Python Software Foundation, , . , ,
exe .

( ).

2.1. Python Windows

Python, 0.2

. .
.

, . , .

2.1. Python Windows

Python, 0.2

python...
Finish. , Python! python windows
IDLE. !

2.2 Python linux (ubuntu, linux mint


)
( ctrl+alt+t). :
python3

, python 3:
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

, : python 3.
*python3*:
sudo apt-get install python3

mintinstaller / synaptic / ubuntu / .


python linux IDLE. , . *idle3* (
python3-idle).
2.2. Python linux (ubuntu, linux mint )

Python, 0.2

, . (gedit, vim, emacs...) :


python3 path_to_file.py

(, IDLE, -
).

2.2. Python linux (ubuntu, linux mint )

. IDLE

IDLE.
python IDLE ( Python,
).
Windows, .

IDLE ( ), . ,
hello world.
hello world python, :
print("Hello world!")

IDLE Enter. :

Python, 0.2

! python! ( - ).
, ,
,
print(3 + 4)
print(3 * 5)
print(3 ** 2)

, -, . ,
.
, , IDLE File New
File ( Ctrl + N).

:
name = input(" ? ")
print(",", name)

( ? ), , Enter name.
print ,
, , name.
F5 ( IDLE Run Run Module , ,
, . IDLE .
, , .
- ( -
, - ):

Python, 0.2

! ,
IDLE. ,
python . python, . !

10

Python

Python, , .

4.1
( ).
.
, , . . 1 , ,
. 4 ( , ).
Python
, ,
, .
:

4.2
, :
a = 1; b = 2; print(a, b)

! .
.
. , :

11

Python, 0.2

if (a == 1 and b == 2 and
c == 3 and d == 4): #
print('spam' * 3)

, , . , :). :
if x > y: print(x)

, , , .
PEP 8 Python Python. PEP 257.

4.2.

12

. ?

! ? python 3, ,
.
: . ,
.
: (
.
( , , ),
, .
: IDLE .
: input. SyntaxError.
:
>>> a = input()
hello world
File ``<string>'', line 1
hello world
^
SyntaxError: unexpected EOF while parsing
: Python 2.
: Python 3.
: - , .
:
name = raw_input()
print name

:
File "a.py", line 3
print name

13

Python, 0.2

^
SyntaxError: invalid syntax

: Python 2.
: Python 2 Python 3. Python 3. , Python 3 :
name = input()
print(name)

: TypeError: Cant convert int object to str implicitly.


:
>>> a = input() + 5
8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

: .
: int(). , , input() !
>>> a = int(input()) + 5
8
>>> a
13

: SyntaxError: invalid syntax.


:
a = 5
if a == 5
print('!')

:
File "a.py", line 3
if a == 5
^
SyntaxError: invalid syntax

: .
:
a = 5
if a == 5:
print('!')

14

Python, 0.2

: SyntaxError: invalid syntax.


:
a = 5
if a = 5:
print('!')

:
File "a.py", line 3
if a = 5
^
SyntaxError: invalid syntax

: .
:
a = 5
if a == 5:
print('!')

: NameError: name a is not dened.


:
print(a)

: a . , .
: .
a = 10
print(a)

: IndentationError: expected an indented block.


:
a = 10
if a > 0:
print(a)

: .
:
a = 10
if a > 0:
print(a)

: TabError: inconsistent use of tabs and spaces in indentation.


15

Python, 0.2

:
a = 10
if a > 0:
print(a)
print('!')

:
File "a.py", line 5
print('!')
^
TabError: inconsistent use of tabs and spaces in indentation

: .
: .
a = 10
if a > 0:
print(a)
print('!')

: UnboundLocalError: local variable a referenced before assignment.


:
def f():
a += 1
print(a)
a = 10
f()

:
Traceback (most recent call last):
File "a.py", line 7, in <module>
f()
File "a.py", line 3, in f
a += 1
UnboundLocalError: local variable 'a' referenced before assignment

: , .
:
def f():
global a
a += 1
print(a)

16

Python, 0.2

a = 10
f()

: , / .
:
>>> f = open('output.txt', 'w', encoding='utf-8')
>>> f.write('bla')
3
>>>

: , .
:
>>> f = open('output.txt', 'w', encoding='utf-8')
>>> f.write('bla')
3
>>> f.close()
>>>

: . :)
:

17

if-elif-else, ,
if/else

if-elif-else ( ) - Python. , , , .

6.1 if
if ,
elif, , , else.
if :
if test1:
state1
elif test2:
state2
else:
state3

( true, 1 - ):
>>> if 1:
...
print('true')
... else:
...
print('false')
...
true

( , ):
a = int(input())
if a < -5:
print('Low')
elif -5 <= a <= 5:

18

Python, 0.2

print('Mid')
else:
print('High')

elif
switch - case .

6.2 Python
, 0, - .
, 0, None -

True False
and or -
:
X and Y

, X Y .
X or Y

, X Y .
not X

, X .

6.3 if/else
:
if X:
A = Y
else:
A = Z

, , , 4 .
if/else:
A = Y if X else Z

Y, X , Z.
6.2. Python

19

Python, 0.2

>>> A = 't' if 'spam' else 'f'


>>> A
't'

6.3. if/else

20

for while, break continue,


else

for while, break continue,


else, , ,
.

7.1 while
While - Python, .
, .
>>> i = 5
>>> while i < 15:
...
print(i)
...
i = i + 2
...
5
7
9
11
13

7.2 for
for , , while. ( ), .
>>> for i in 'hello world':
...
print(i * 2, end='')
...
hheelllloo wwoorrlldd

21

Python, 0.2

7.3 continue
continue , (for
while)
>>> for i in 'hello world':
...
if i == 'o':
...
continue
...
print(i * 2, end='')
...
hheellll wwrrlldd

7.4 break
break .
>>> for i in 'hello world':
...
if i == 'o':
...
break
...
print(i * 2, end='')
...
hheellll

7.5 else
else, for while, ,
break, . else
, break.
>>> for i in 'hello world':
...
if i == 'a':
...
break
... else:
...
print(' a ')
...
a

7.3. continue

22

, keyword

- Python, keyword.

8.1
False - .
True - .
None - .
and - .
with / as - .
assert - , .
break - .
class - , .
continue - .
def - .
del - .
elif - , .
else - . for/else if/else.
except - .
nally - try, ,
.
for - for.
from - .
global - , , .
23

Python, 0.2

if - .
import - .
in - .
is - 2 .
lambda - .
nonlocal - , , .
not - .
or - .
pass - .
raise - .
return - .
try - , .
while - while.
yield - -.

8.2 keyword
-, keyword - , .
keyword.kwlist - .
keyword.iskeyword() - .

8.2. keyword

24

Python 3.

9.1 ,
bool(x) - bool, . , False,
True.
bytearray([ [, []]]) - bytearray. Bytearray - 0<=X<256. , .
bytes([ [, []]]) - bytes, 0<=X<256.
bytearray().
complex([real[, imag]]) - .
dict([object]) - .
oat([X]) - . , 0.0.
frozenset([]) - .
int([object], [ ]) - .
list([object]) - .
memoryview([object]) - memoryview.
object() - , .
range([start=0], stop, [step=1]) - start stop step.
set([object]) - .
slice([start=0], stop, [step=1]) - start stop step.
25

Python, 0.2

str([object], [], []) - .


__str__.
tuple(obj) - .

9.2
abs(x) - ( ).
all() - True, (, ).
any() - True, - . False.
ascii(object) - repr(), , , -ASCII .
bin(x) - .
callable(x) - True , ( ).
chr(x) - , x.
classmethod(x) - .
compile(source, lename, mode, ags=0, dont_inherit=False) -
, eval exec. .
delattr(object, name) - name.
dir([object]) - , , .
divmod(a, b) - a b.
enumerate(iterable, start=0) - , .
eval(expression, globals=None, locals=None) - .
exec(object[, globals[, locals]]) - Python.
lter(function, iterable) - , function .
format(value[,format_spec]) - ( ).
getattr(object, name ,[default]) - default.
globals() - .
hasattr(object, name) - name.
hash(x) - .
help([object]) - .
9.2.

26

Python, 0.2

hex() - .
id(object) - . ,
.
input([prompt]) - . Prompt - .
isinstance(object, ClassInfo) - , ClassInfo
. ,
.
issubclass(, ClassInfo) - , ClassInfo. .
iter(x) - .
len(x) - .
locals() - .
map(function, iterator) - ,
function.
max(iter, [args ...] * [, key]) - .
min(iter, [args ...] * [, key]) - .
next(x) - .
oct() - .
open(le,
mode=r,
buffering=None,
encoding=None,
errors=None,
closefd=True) - .

newline=None,

ord() - .
pow(x, y[, r]) - ( x ** y ) % r.
reversed(object) - .
repr(obj) - .
print([object, ...], *, sep= , end=\n, le=sys.stdout) - .
property(fget=None, fset=None, fdel=None, doc=None)
round(X [, N]) - N .
setattr(, , ) - .
sorted(iterable[, key][, reverse]) - .
staticmethod(function) - .
sum(iter, start=0) - .
super([ [, ]]) - .
type(object) - .
type(name, bases, dict) - name.
9.2.

27

Python, 0.2

vars([object]) - . - .
zip(*iters) - , , -.

9.2.

28

10

: , ,

Python 3: , , .
.

10.1 (int)
Python 3 . :
x+y
x-y
x*y
x/y
x // y
x%y
-x
abs(x)
divmod(x, y)
x ** y
pow(x, y[, z])





(x // y, x % y)

xy ( )

, python 3, ,
(, ).
>>> 255 + 34
289
>>> 5 * 2
10
>>> 20 / 3
6.666666666666667
>>> 20 // 3
6
>>> 20 % 3
2
>>> 3 ** 4
81

29

Python, 0.2

>>> pow(3, 4)
81
>>> pow(3, 4, 27)
0
>>> 3 ** 150
369988485035126972924700782451696644186473100389722973815184405301748249

10.1.1

x|y
x^y
x&y
x << n
x >> y
~x

10.1.2
int.bit_length() - , ,
.
>>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6

int.to_bytes(length, byteorder, *, signed=False) - ,


.
>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little')
b'\xe8\x03'

classmethod int.from_bytes(bytes, byteorder, *, signed=False) -


.
>>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')

10.1. (int)

30

Python, 0.2

4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680

10.1.3
, , , . ,
, , , 19 10011.
. Python
:
int([object], [ ]) - . ,
2 36 .
bin(x) - .
hex() - .
oct() - .
:
>>> a = int('19') #
>>> b = int('19.5') #
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() with base 10: '19.5'
>>> c = int(19.5) # ,
>>> print(a, c)
19 19
>>> bin(19)
'0b10011'
>>> oct(19)
'0o23'
>>> hex(19)
'0x13'
>>> 0b10011 #
19
>>> int('10011', 2)
19
>>> int('0b10011', 2)
19

10.1. (int)

31

Python, 0.2

10.2 (oat)
, . (- ) ,
:
>>> 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1
0.9999999999999999

( Decimal Fraction)).
:
>>> a = 3 ** 1000
>>> a + 0.1
Traceback (most recent call last):
File "", line 1, in
OverflowError: int too large to convert to float

:
>>> c = 150
>>> d = 12.9
>>> c + d
162.9
>>> p = abs(d - c) #
>>> print(p)
137.1
>>> round(p) #
137

10.2.1
oat.as_integer_ratio() - , .
oat.is_integer() - .
oat.hex() - oat hex ( ).
classmethod oat.fromhex(s) - oat .
>>> (10.5).hex()
'0x1.5000000000000p+3'
>>> float.fromhex('0x1.5000000000000p+3')
10.5

( Python ),
Python .
math .

10.2. (oat)

32

Python, 0.2

>>> import math


>>> math.pi
3.141592653589793
>>> math.sqrt(85)
9.219544457292887

random .
>>> import random
>>> random.random()
0.15651968855132303

10.3 (complex)
Python :
>>> x = complex(1, 2)
>>> print(x)
(1+2j)
>>> y = complex(3, 4)
>>> print(y)
(3+4j)
>>> z = x + y
>>> print(x)
(1+2j)
>>> print(z)
(4+6j)
>>> z = x * y
>>> print(z)
(-5+10j)
>>> z = x / y
>>> print(z)
(0.44+0.08j)
>>> print(x.conjugate()) #
(1-2j)
>>> print(x.imag) #
2.0
>>> print(x.real) #
1.0
>>> print(x > y) #
Traceback (most recent call last):
File "", line 1, in
TypeError: unorderable types: complex() > complex()
>>> print(x == y) #
False
>>> abs(3 + 4j) #
5.0
>>> pow(3 + 4j, 2) #

10.3. (complex)

33

Python, 0.2

(-7+24j)

cmath.

10.3. (complex)

34

11

Python:

Python - , , , .
, .

11.1
Python . , .

11.1.1
S = 'spam"s'
S = "spam's"

- .
, ,
.

11.1.2 -
,
.

35

Python, 0.2

\n
\a
\b
\f
\r
\t
\v
\N{id}
\uhhhh
\Uhhhh. . .
\xhh
\ooo
\0





ID
16- 16-

32- 32-

16-
8-
Null ( )

11.1.3 -
r ( ),
.
S = r'C:\newt.txt'

, , . :
S = r'\n\n\\'[:-1]
S = r'\n\n' + '\\'
S = '\\n\\n'

11.1.4
,
. , , .
>>> c = '''
... ,
... '''
>>> c
' \n, \n '
>>> print(c)

,

11.1.

36

Python, 0.2

.
.

11.1.

37

12

, , .
, - .

12.1
()
>>> S1 = 'spam'
>>> S2 = 'eggs'
>>> print(S1 + S2)
'spameggs'


>>> print('spam' * 3)
spamspamspam

( len)
>>> len('spam')
4


>>>
>>>
's'
>>>
'a'
>>>
'a'

S = 'spam'
S[0]
S[2]
S[-2]

38

Python, 0.2

, Python ,
.

: [X:Y]. X , Y ;
Y . 0,
- .
>>> s = 'spameggs'
>>> s[3:5]
'me'
>>> s[2:-2]
'ameg'
>>> s[:6]
'spameg'
>>> s[1:]
'pameggs'
>>> s[:]
'spameggs'

, , .
>>> s[::-1]
'sggemaps'
>>> s[3:5:-1]
''
>>> s[2::2]
'aeg'

12.2
, Python
, .
>>> s = 'spam'
>>> s[1] = 'b'
Traceback (most recent call last):
File "", line 1, in
s[1] = 'b'
TypeError: 'str' object does not support item assignment
>>> s = s[0] + 'b' + s[2:]
>>> s
'sbam'

, .

12.2.

39

Python, 0.2

12.3

S = str; S = str; S = str; S = str
S = s\np\ta\nbbb
S = rC:\temp\new
S = bbyte
S1 + S2
S1 * 3
S[i]
S[i:j:step]
len(S)
S.nd(str, [start],[end])
S.rnd(str, [start],[end])
S.index(str, [start],[end])

S.rindex(str, [start],[end])

S.replace(, )
S.split()
S.isdigit()
S.isalpha()
S.isalnum()
S.islower()
S.isupper()
S.isspace()

S.istitle()
S.upper()
S.lower()
S.startswith(str)

12.3.



(
)

( )




. -1
. -1
.

ValueError
.
ValueError






(, (\f), (\n), (\r), (\t)
(\v))



S str

40

Python, 0.2

12.1

S.endswith(str)
S str
S.join()
S
ord()
ASCII
chr()
ASCII
S.capitalize()
,
S.center(width, [ll])
,
ll (
)
S.count(str, [start],[end])
[, ] (0 )
S.expandtabs([tabsize])
,

, . TabSize
, 8
S.lstrip([chars])

S.rstrip([chars])

S.strip([chars])


S.partition()
,
, ,
. , ,
,
S.rpartition(sep)
,
, ,
.
, , ,
S.swapcase()

,
S.title()

,
S.zll(width)
width,

12.3.

41

Python, 0.2

12.1

S.ljust(width, llchar= )
width,
llchar
S.rjust(width, llchar= )
width,

llchar
S.format(*args, **kwargs)

12.3.

42

13

. format

( , ) , , , ( , . .). .
%, format.

13.1 format
, - :
>>> 'Hello, {} !'.format('Vasya')
'Hello, Vasya!'

,
( ):
>>> '{0} , {1} , {2} '.format('a', 'b', 'c')
'a, b, c'
>>> '{} , {} , {} '.format('a', 'b', 'c')
'a, b, c'
>>> '{2} , {1} , {0} '.format('a', 'b', 'c')
'c, b, a'
>>> '{2} , {1} , {0} '.format(*'abc')
'c, b, a'
>>> '{0} {1} {0} '.format('abra', 'cad')
'abracadabra'
>>> 'Coordinates: {latitude} , {longitude} '.format(latitude='37.24N', longitude='115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude} , {longitude} '.format(**coord)
'Coordinates: 37.24N, -115.81W'

format . :

43

Python, 0.2


::=

::=
::=
)

::=

"{" [ ] ["!" ] [":" ] "}"


arg_name ("." | "[" "]")*
"r" ( ) | "s" (
.

:
>>> "Units destroyed: {players[0]} ".format(players = [1, 2, 3])
'Units destroyed: 1'
>>> "Units destroyed: {players[0]!r} ".format(players = ['1', '2', '3'])
"Units destroyed: '1'"

::=
::=
::=
::=
::=
::=
::=

[[fill]align][sign][#][0][width][,][.precision][type]
'{' '}'
"<" | ">" | "=" | "^"
"+" | "-" | " "
integer
integer
"b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" |
"n" | "o" | "s" | "x" | "X" | "%"

-.
:

<
- ( )
( ).
>
.
=
, .
.
^
.
:

+
-

.
- , .
- , .

13.1. format

44

Python, 0.2

d,
i, u
o
x
X
e
E
f, F
g
G
c
s
%

.
.
( ).
( ).
( ).
( ).
( ).
. ( ),
, -4 , .
. ( ),
, -4 , .
( - ).
.
100, ,
%.

, :
>>> coord = (3, 5)
>>> 'X: {0[0]} ; Y: {0[1]} '.format(coord)
'X: 3; Y: 5'
>>> "repr() shows quotes: {!r} ; str() doesn't: {!s} ".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
>>> '{:<30} '.format('left aligned')
'left aligned
'
>>> '{:>30} '.format('right aligned')
'
right aligned'
>>> '{:^30} '.format('centered')
'
centered
'
>>> '{:*^30} '.format('centered') # use '*' as a fill char
'***********centered***********'
>>> '{:+f} ; {:+f} '.format(3.14, -3.14) # show it always
'+3.140000; -3.140000'
>>> '{: f} ; {: f} '.format(3.14, -3.14) # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f} ; {:-f} '.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:
f}'
'3.140000; -3.140000'
>>> # format also supports binary numbers
>>> "int: {0:d} ; hex: {0:x} ; oct: {0:o} ; bin: {0:b} ".format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d} ; hex: {0:#x} ; oct: {0:#o} ; bin: {0:#b} ".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
>>> points = 19.5
>>> total = 22
>>> 'Correct answers: {:.2%} '.format(points/total)
'Correct answers: 88.64%'

13.1. format

45

14

(list).

, , ,
.

14.1 ?
Python -
( , ).
, . . , (, )
list:
>>> list('')
['', '', '', '', '', '']

:
>>> s = [] #
>>> l = ['s', 'p', ['isok'], 2]
>>> s
[]
>>> l
['s', 'p', ['isok'], 2]

, (
), .
- . -
, . for.
>>> c = [c * 3 for c in 'list']
>>> c
['lll', 'iii', 'sss', 'ttt']

46

Python, 0.2

:
>>> c = [c * 3 for c in 'list' if c != 'i']
>>> c
['lll', 'sss', 'ttt']
>>> c = [c + d for c in 'list' if c != 'i' for d in 'spam' if d != 'a']
>>> c
['ls', 'lp', 'lm', 'ss', 'sp', 'sm', 'ts', 'tp', 'tm']

for .

14.2
, - .
, .

14.3

list.append(x)
list.extend(L)
list.insert(i, x)
list.remove(x)
list.pop([i])
list.index(x, [start
[, end]])
list.count(x)
list.sort([key =
])
list.reverse()
list.copy()
list.clear()



list, L
i- x
, x
i- . ,

start end
x
x


( python 3.3)
( python 3.3)

, , ,
, .
>>> l = [1, 2, 3, 5, 7]
>>> l.sort()
>>> l
[1, 2, 3, 5, 7]
>>> l = l.sort()
>>> print(l)
None

, , :

14.2.

47

Python, 0.2

>>> a = [66.25, 333, 333, 1, 1234.5]


>>> print(a.count(333), a.count(66.25), a.count('x'))
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]

, ,
.

14.3.

48

15

15.1
, :
>>> a = [1, 3, 8, 7]
>>> a[0]
1
>>> a[3]
7
>>> a[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

, .
IndexError.
a ,
: , .
Python ,
, :
>>> a = [1, 3, 8, 7]
>>> a[-1]
7
>>> a[-4]
1
>>> a[-5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

49

Python, 0.2

15.2
Python, , .
item[START:STOP:STEP] - START, STOP ( ), STEP.
START = 0, STOP = , STEP = 1. , - (
, ) .
>>>
>>>
[1,
>>>
[3,
>>>
[1,
>>>
[1,

a = [1, 3, 8, 7]
a[:]
3, 8, 7]
a[1:]
8, 7]
a[:3]
3, 8]
a[::2]
8]

:
>>>
>>>
[7,
>>>
[1,
>>>
[8,
>>>
[]

a = [1, 3, 8, 7]
a[::-1]
8, 3, 1]
a[:-2]
3]
a[-2::-1]
3, 1]
a[1:4:-1]

, START < STOP, STEP . , :


>>> a = [1, 3, 8, 7]
>>> a[10:20]
[]

,
(, ).
>>>
>>>
>>>
[1,
>>>
>>>
[0,

a = [1, 3, 8, 7]
a[1:3] = [0, 0, 0]
a
0, 0, 0, 7]
del a[:-3]
a
0, 7]

15.2.

50

16

(tuple)

, (tuple) , .
, - .

16.1 , ?
. , ( ), ( ).
. :
>>>
>>>
>>>
36
>>>
44

a = (1, 2, 3, 4, 5, 6)
b = [1, 2, 3, 4, 5, 6]
a.__sizeof__()
b.__sizeof__()

:
>>> d = {(1, 1, 1) : 1}
>>> d
{(1, 1, 1): 1}
>>> d = {[1, 1, 1] : 1}
Traceback (most recent call last):
File "", line 1, in
d = {[1, 1, 1] : 1}
TypeError: unhashable type: 'list'

16.2 ?
, - .
, .
51

Python, 0.2

:
>>>
>>>
()
>>>
>>>
()
>>>

a = tuple() # tuple()
a
a = () #
a

:
>>> a = ('s')
>>> a
's'

. . ? ! ?
>>> a = ('s', )
>>> a
('s',)

! ! - . , , , , , . , :
>>> a = 's',
>>> a
('s',)

, , , ,
.

tuple()
>>> a = tuple('hello, world!')
>>> a
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!')

16.3
, (, , index() count() ). -
.
, python - :

16.3.

52

Python, 0.2

a, b = b, a

16.3.

53

17

(dict) .

, , ,
, , .
Python -
. -.
, . . -, :
>>> d = {}
>>> d
{}
>>> d = {'dict': 1, 'dictionary': 2}
>>> d
{'dict': 1, 'dictionary': 2}

-, dict:
>>> d = dict(short='dict', long='dictionary')
>>> d
{'short': 'dict', 'long': 'dictionary'}
>>> d = dict([(1, 1), (2, 4)])
>>> d
{1: 1, 2: 4}

-, fromkeys:
>>> d
>>> d
{'a':
>>> d
>>> d
{'a':

= dict.fromkeys(['a', 'b'])
None, 'b': None}
= dict.fromkeys(['a', 'b'], 100)
100, 'b': 100}

-, ,
.

54

Python, 0.2

>>> d = {a: a ** 2 for a in range(7)}


>>> d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

:
>>> d = {1: 2, 2: 4, 3: 9}
>>> d[1]
2
>>> d[4] = 4 ** 2
>>> d
{1: 2, 2: 4, 3: 9, 4: 16}
>>> d['1']
Traceback (most recent call last):
File "", line 1, in
d['1']
KeyError: '1'

, ,
, .
(. ), .
? , :
, (, for while), .

17.1
dict.clear() - .
dict.copy() - .
classmethod dict.fromkeys(seq[, value]) - seq
value ( None).
dict.get(key[, default]) - , , , default ( None).
dict.items() - (, ).
dict.keys() - .
dict.pop(key[, default]) - . ,
default ( ).
dict.popitem() - (, ). ,
KeyError. , .
dict.setdefault(key[, default]) - , , , default ( None).

17.1.

55

Python, 0.2

dict.update([other]) - , (, ) other. . None ( !).


dict.values() - .

17.1.

56

18

(set frozenset)

! python,
.

18.1 ?
python - , .
:
>>> a = set()
>>> a
set()
>>> a = set('hello')
>>> a
{'h', 'o', 'l', 'e'}
>>> a = {'a', 'b', 'c', 'd'}
>>> a
{'b', 'c', 'a', 'd'}
>>> a = {i ** 2 for i in range(10)} #
>>> a
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
>>> a = {} # !
>>> type(a)
<class 'dict'>

, , , .
:
>>> words = ['hello', 'daddy', 'hello', 'mum']
>>> set(words)
{'hello', 'daddy', 'mum'}

57

Python, 0.2

: , ...
len(s) - ( ).
x in s - x s.
set.isdisjoint(other) - , set other .
set == other - set other, other
set.
set.issubset(other) set <= other - set other.
set.issuperset(other) set >= other - .
set.union(other, ...) set | other | ... - .
set.intersection(other, ...) set & other & ... - .
set.difference(other, ...) set - other - ... - set, other.
set.symmetric_difference(other); set ^ other - , , .
set.copy() - .
, :
set.update(other, ...); set |= other | ... - .
set.intersection_update(other, ...); set &= other & ... - .
set.difference_update(other, ...); set -= other | ... - .
set.symmetric_difference_update(other); set ^= other - , , .
set.add(elem) - .
set.remove(elem) - . KeyError,
.
set.discard(elem) - , .
set.pop() - . , , .
set.clear() - .

18.2 frozenset
set frozenset , set - , frozenset - . .

18.2. frozenset

58

Python, 0.2

>>> a = set('qwerty')
>>> b = frozenset('qwerty')
>>> a == b
True
>>> True
True
>>> type(a - b)
<class 'set'>
>>> type(a | b)
<class 'set'>
>>> a.add(1)
>>> b.add(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'

18.2. frozenset

59

19

, ,
def, return lambda, ,
.

19.1 , def
python - , . def.
:
def add(x, y):
return x + y

return , . x y.
:
>>> add(1, 10)
11
>>> add('abc', 'def')
'abcdef'

(, ,
!):
>>> def newfunc(n):
...
def myfunc(x):
...
return x + n
...
return myfunc
...
>>> new = newfunc(100) # new -
>>> new(200)
300

60

Python, 0.2

return, None:
>>> def func():
...
pass
...
>>> print(func())
None

19.2

. ,
, .
>>> def func(a, b, c=2): # c -
...
return a + b + c
...
>>> func(1, 2) # a = 1, b = 2, c = 2 ( )
5
>>> func(1, 2, 3) # a = 1, b = 2, c = 3
6
>>> func(a=1, b=3) # a = 1, b = 3, c = 2
6
>>> func(a=3, c=6) # a = 3, c = 6, b
Traceback (most recent call last):
File "", line 1, in
func(a=3, c=6)
TypeError: func() takes at least 2 arguments (2 given)

, *:
>>> def func(*args):
...
return args
...
>>> func(1, 2, 3, 'abc')
(1, 2, 3, 'abc')
>>> func()
()
>>> func(1)
(1,)

, args - ,
, .
,
**:

19.2.

61

Python, 0.2

>>> def func(**kwargs):


...
return kwargs
...
>>> func(a=1, b=2, c=3)
{'a': 1, 'c': 3, 'b': 2}
>>> func()
{}
>>> func(a='python')
{'a': 'python'}

kwargs , , -,
, .

19.3 , lambda
,
. lambda. ,
, def func():
>>> func = lambda x, y: x + y
>>> func(1, 2)
3
>>> func('a', 'b')
'ab'
>>> (lambda x, y: x + y)(1, 2)
3
>>> (lambda x, y: x + y)('a', 'b')
'ab'

lambda , , return, ,
:
>>> func = lambda *args: args
>>> func(1, 2, 3, 4)
(1, 2, 3, 4)

19.3. , lambda

62

20

python. try - except

(exceptions) - python.
, .
- :
>>> 100 / 0
Traceback (most recent call last):
File "", line 1, in
100 / 0
ZeroDivisionError: division by zero

ZeroDivisionError,
. :
>>> 2 + '1'
Traceback (most recent call last):
File "", line 1, in
2 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> int('qwerty')
Traceback (most recent call last):
File "", line 1, in
int('qwerty')
ValueError: invalid literal for int() with base 10: 'qwerty'

TypeError ValueError .
, ,
.
python , , . python 3.3, .
BaseException - , .

63

Python, 0.2

SystemExit - , sys.exit .
KeyboardInterrupt -
( Ctrl+C).
GeneratorExit - close generator.
Exception - ( ) , .
* StopIteration - next,
.
* ArithmeticError - .
FloatingPointError -
. .
OverowError - ,
.
( python ), .
ZeroDivisionError - .
* AssertionError - assert .
* AttributeError - ( ).
* BufferError - , , .
* EOFError - ,
.
* ImportError - .
* LookupError - .
IndexError - .
KeyError - ( ,
).
* MemoryError - .
* NameError - .
UnboundLocalError -
, .
* OSError - , .
BlockingIOError
ChildProcessError - .
ConnectionError - , .
64

Python, 0.2

BrokenPipeError
ConnectionAbortedError
ConnectionRefusedError
ConnectionResetError
FileExistsError - ,
.
FileNotFoundError - .
InterruptedError - .
IsADirectoryError - , .
NotADirectoryError - , .
PermissionError - .
ProcessLookupError - .
TimeoutError - .
* ReferenceError - .
* RuntimeError - , .
* NotImplementedError - , .
* SyntaxError - .
IndentationError - .
TabError - .
* SystemError - .
* TypeError - .
* ValueError - , .
* UnicodeError - , /
unicode .
UnicodeEncodeError - , unicode.
UnicodeDecodeError
unicode.

UnicodeTranslateError - , unicode.
* Warning - .
, , , . try - except.
:
65

Python, 0.2

>>> try:
...
k = 1 / 0
... except ZeroDivisionError:
...
k = 0
...
>>> print(k)
0

try , , except . ,
. , ArithmeticError,
FloatingPointError, OverowError ZeroDivisionError.
>>> try:
...
k = 1 / 0
... except ArithmeticError:
...
k = 0
...
>>> print(k)
0

except , (
, . .). except , except Exception.
, ( , except ).
, , nally else. Finally
, , (, - , , ). else
, .
>>> f = open('1.txt')
>>> ints = []
>>> try:
...
for line in f:
...
ints.append(int(line))
... except ValueError:
...
print(' . .')
... except Exception:
...
print(' ?')
... else:
...
print(' .')
... finally:
...
f.close()
...
print(' .')
...
# : try, except, else,
finally.
...
. .
.

66

Python, 0.2

67

21

(bytes bytearray)

Python - ?
, . , .
? - . - (,
, ...).
:
>>> b'bytes'
b'bytes'
>>> ''.encode('utf-8')
b'\xd0\x91\xd0\xb0\xd0\xb9\xd1\x82\xd1\x8b'
>>> bytes('bytes', encoding = 'utf-8')
b'bytes'
>>> bytes([50, 100, 76, 72, 41])
b'2dLH)'

(, ), .
bytes 0 255, ,
chr.
>>> chr(50)
'2'
>>> chr(100)
'd'
>>> chr(76)
'L'

?
, . /
- (, , ). decode:
>>> b'\xd0\x91\xd0\xb0\xd0\xb9\xd1\x82\xd1\x8b'.decode('utf-8')
''

68

Python, 0.2

21.1 Bytearray
Bytearray python - . bytes , . , -, .
>>> b = bytearray(b'hello world!')
>>> b
bytearray(b'hello world!')
>>> b[0]
104
>>> b[0] = b'h'
Traceback (most recent call last):
File "", line 1, in
b[0] = b'h'
TypeError: an integer is required
>>> b[0] = 105
>>> b
bytearray(b'iello world!')
>>> for i in range(len(b)):
...
b[i] += i
...
>>> b
bytearray(b'ifnos%}vzun,')

21.1. Bytearray

69

22

. .

python : / , .
, . , , .
open:
f = open('text.txt', 'r')

open , , 3 : , .
. , , .

r
w
x
a
b
t
+

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

, , , rb - .
rt.
, encoding, .
.

22.1
, .
, .
- read, , , n
, ( n).
70

Python, 0.2

>>> f = open('text.txt')
>>> f.read(1)
'H'
>>> f.read()
'ello world!\nThe end.\n\n'

- , for:
>>> f = open('text.txt')
>>> for line in f:
...
line
...
'Hello world!\n'
'\n'
'The end.\n'
'\n'

22.2
. :
>>> l = [str(i)+str(i-1) for i in range(20)]
>>> l
['0-1', '10', '21', '32', '43', '54', '65', '76', '87', '98', '109', '1110', '1211
', '1312', '1413', '1514', '1615', '1716', '1817', '1918']

:
>>> f = open('text.txt', 'w')

write:
>>> for index in l:
...
f.write(index + '\n')
...
4
3
3
3
3

, , , : write .

close:
>>> f.close()

22.2.

71

Python, 0.2

. (, , ?), .
>>> f = open('text.txt', 'r')
>>> l = [line.strip() for line in f]
>>> l
['0-1', '10', '21', '32', '43', '54', '65', '76', '87', '98', '109', '1110', '1211
', '1312', '1413', '1514', '1615', '1716', '1817', '1918']
>>> f.close()

, . (,
. .) . . python
, pickle json,
.

22.2.

72

23

With ... as -

with ... as
. , try...except...nally.
with ... as:
"with" expression ["as" target] ("," expression ["as" target])* ":"
suite

, :
1. with ... as.
2. __exit__ .
3. __enter__. with as, __enter__ .
4. suite.
5. __exit__, , suite
. , ,
None, .
with - as , :
with A() as a, B() as b:
suite

with A() as a:
with B() as b:
suite

with ... as? , .


- .
open, with ... as, , .
73

Python, 0.2

:
with open('newfile.txt', 'w', encoding='utf-8') as g:
d = int(input())
print('1 / {} = {} '.format(d, 1 / d), file=g)

, ,
.

74

24

PEP 8 - Python

, python,
, python.
PEP 8 .
- , . , , PEP
(, , , ).
: , . ,
,
. ,
, .
.
. .
. , , , . , , .
, :
1. ,
, .
2. , (, ) ,
.

24.1


?


75

Python, 0.2




:








:
:
* ,
*
*
*
*
*
*
*
*
*

24.2
24.2.1
4 .
, (, ),

24.2.

76

Python, 0.2

. : ,
.
:
#
foo = long_function_name(var_one, var_two,
var_three, var_four)
#
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)

:
# ,

foo = long_function_name(var_one, var_two,


var_three, var_four)
# ,
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)

:
# .
foo = long_function_name(
var_one, var_two,
var_three, var_four)

//
, :
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)

, :

24.2.

77

Python, 0.2

my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)

24.2.2 ?
- .
,
.
Python 3 .
Python 2 .
Python 2 -t, (warnings) , -tt, (errors).
!

24.2.3
79 .
(
), 72 .
, ,
.
. , , , 80 100 ( 99 ), ,
72 .
Python
79 ( / 72).
Python , .
, . .

24.2.

78

Python, 0.2

. ,
with , :
with open('/path/to/some/file/you/want/to/read') as file_1, \
open('/path/to/some/file/being/written', 'w') as file_2:
file_2.write(file_1.read())

- assert.
. , . :
class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s , %s " %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)

24.2.4
.
.

. (, ).
, .
Python control+L (whitespace), , . , control+L .

24.2.5
Python UTF-8 (ASCII Python 2).
ASCII (Python 2) UTF-8 (Python 3) .

24.2.

79

Python, 0.2

,
, , ASCII ;
\x, \u, \U \N - ASCII .
python 3.0 : ASCII , , (
). ,
ASCII . : () test case, ASCII , () . ,
, .

.

24.2.6
, , .
:
import os
import sys

:
import sys, os

, :
from subprocess import Popen, PIPE

,
, .
:
1.
2.
3.
.
__all__ .
,
(, , )
(,
sys.path):

24.2.

80

Python, 0.2

import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example

,
, , :
from . import sibling
from .sibling import example

.
,
Python 3.
, :
from myclass import MyClass
from foo.bar.yourclass import YourClass

, :
import myclass
import foo.bar.yourclass

myclass.MyClass foo.bar.yourclass.YourClass.
(from import *) ,
, , , .
,
API (,
Python (
, ).

24.3
24.3.1 :
, .
:
spam(ham[1], {eggs: 2})

24.3.

81

Python, 0.2

spam( ham[ 1 ], { eggs: 2 } )

, :
:
if x == 4: print(x, y); x, y = y, x

:
if x == 4 : print(x , y) ; x , y = y , x

,
:
:
spam(1)

:
spam (1)

, :
:
dict['key'] = list[index]

:
dict ['key'] = list [index]

(
) , :
:
x = 1
y = 2
long_variable = 3

:
x
= 1
y
= 2
long_variable = 3

24.3.2
: (=, +=, -= ), (==, <, >, !=, <>, <=, >=, in, not in, is, is not),
24.3.

82

Python, 0.2

(and, or, not).


, . , , , .
:
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

:
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)

=, .
:
def complex(real, imag=0.0):
return magic(r=real, i=imag)

:
def complex(real, imag = 0.0):
return magic(r = real, i = imag)

( ).
:
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()

:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

while, for if , , , .
24.3.

83

Python, 0.2

!
:
if foo == 'blah': do_blah_thing()
for x in lst: total += x
while t < 10: t = delay()

, :
if foo == 'blah': do_blah_thing()
else: do_non_blah_thing()
try: something()
finally: cleanup()
do_one(); do_two(); do_three(long, argument,
list, like, this)
if foo == 'blah': one(); two(); three()

24.4
, , , . , !
.
, ,
, ( !).
, . , , .
.
, , , , 120%,
, .

24.4.1
(, ),
, , . # (
).
,
#.
24.4.

84

Python, 0.2

24.4.2
.
, . . # .
, . :
x = x + 1

# Increment x

, :
x = x + 1

24.4.3
, , , .
, ,
. def.
PEP 257 , . , , . ,
, :
"""Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"""

24.5
Subversion, CVS RCS ,
:
__version__ = "$Revision: 1a40d4eaa00b $"
# $Source$

24.5.

85

Python, 0.2

24.6
python ,
, , .
, - , .

24.6.1
, API
, , .

24.6.2 :
. , , , .
:
b ( )
B ( )
lowercase ( )
lower_case_with_underscores ( )
UPPERCASE ( )
UPPERCASE_WITH_UNDERSCORES ( )
CapitalizedWords ( , CapWords, CamelCase). : , HTTPServerError , HttpServerError.
mixedCase ( CapitalizedWords , )
Capitalized_Words_With_Underscores ( !)
, , , . python,
. , os.stat() , st_mode, st_size, st_mtime . ( ,
POSIX,
).
X11 public-. python
, ,
.
24.6.

86

Python, 0.2

, :
_single_leading_underscore: , . , from M import * , .
single_trailing_underscore_:
python, :
Tkinter.Toplevel(master, class_='ClassName')

__double_leading_underscore: , FooBar
__boo _FooBar__boo.
__double_leading_and_trailing_underscore__ ( ): ,
, . , __init__, __import__ __le__.
, , .

24.6.3 :
,
l ( ), O ( ) I ( ) .
. l, L.

, . , .
,
.
,
,
Unix, ,
, Windows, Mac, DOS.
, C++, python ( ), /++
, , _socket.

24.6.

87

Python, 0.2


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

, . Error (, , ).

, . , .
, , from M
import *, __all__, . , , ( , ).

,
, .
mixedCase , , .

self .
cls .
python, ,
. , class_ , clss. (, ).

24.6.

88

Python, 0.2


, : , .
.
, .
Python : Foo __a,
Foo.__a. ( , Foo._Foo__a.) ,
, ,
.
: __ (. ).


, . : MAX_OVERFLOW,
TOTAL.

, ( - ) . ,
. , .
, ,
. , , ,
, .
, python .
API (
protected). ,
,
. , , , API ,
.
:
.

24.6.

89

Python, 0.2

,
. , (, , , (class
method) cls).

(accessor/mutator, get/set, . .) ,
python , . (properties),
.
1: (properties) (
Python 3 ).
2: , ; , , , .
3: , - , () .
, , , ,
, . python , , .
1: :
, .
2:
__getattr__(), .
3: , .

24.7
, (PyPy,
Jython, IronPython, Pyrex, Psyco .).
, CPython
a+=b a=a+b. Jython.
.join() python.
None
is is not, . , if x,
24.7.

90

Python, 0.2

if x is not None , ,
, None,
False!
, 6 (__eq__, __ne__, __lt__, __le__, __gt__, __ge__), , .

functools.total_ordering() .

PEP 207 , y > < y, y >= <= y,


== y != y. ,
sort() min() <, max() >. ,
, .
def, - .
:
def f(x): return 2*x

:
f = lambda x: 2*x

Exception, BaseException. BaseException ,


.
. Python 3, raise X
from Y
.
( raise X Python 2
raise X from None Python 3.3+), ,
(, KeyError AttributeError
).
, raise ValueError(message)
raise ValueError, message.
python 3.
, - ,
.
,
except:.
, :

24.7.

91

Python, 0.2

try:
import platform_specific_module
except ImportError:
platform_specific_module = None

except: SystemExit, KeyboardInterrupt,


, ,
control+C. , except Exception:.
except:, :
1. ;
, , .
2. ,
- .
try...nally.
, , Python 2.6:
try:
process_data()
except Exception as exc:
raise DataProcessingFailedError(str(exc))

, Python 3, ,
.
,
, Python 3.3, errno.
try...except ,
. ,
.
:
try:
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)

:
try:
# !
return handle_value(collection[key])

24.7.

92

Python, 0.2

except KeyError:
# KeyError,
handle_value()
return key_not_found(key)

, with
, .
, , - , . :
:
with conn.begin_transaction():
do_stuff_in_transaction(conn)

:
with conn:
do_stuff_in_transaction(conn)

, , __enter__
__exit__ - .
.
string
API unicode-. ,
python 2.0.
Python 3 .
.startswith() .endswith()
.
startswith() endswith() . :
:
if foo.startswith('bar'):

:
if foo[:3] == 'bar':

isinstance(), :
:
if isinstance(obj, int):

24.7.

93

Python, 0.2

if type(obj) is type(1):

, , , unicode-. python 2 str unicode ,


:
if isinstance(obj, basestring):

, Python 3, unicode basestring ( str)


bytes ( ).
(, , ) , false:
:
if not seq:
if seq:

:
if len(seq)
if not len(seq)

,
, ( reindent.py) .
True False ==:
:
if greeting:

:
if greeting == True:

:
if greeting is True:

24.7.

94

25

Python. PEP 257

python - , , ,
.
PEP 257 , python, , python .
PEP - :
, ( ).
PEP , .
, , -
. (, docutils), , .

25.1 ?
- , , , .
__doc__ .
, , , ,
. ( __init__) .
__init__.py.
, triple double quotes . rraw triple double quotes,
.
: .

95

Python, 0.2

25.2
.
. :
def kos_root():
"""Return the pathname of the KOS root directory."""
global _kos_root
if _kos_root: return _kos_root

, . .
. .
.
/
( ). :
def function(a, b):
"""function(a, b) -> list"""

C (,
), . ,
.
- :
def function(a, b):
"""Do X and return a list."""

(, Do X !)

25.3

, . , ,
. , ,
. ,
(. ).
( ), - ,
,
; , . , ,
.
25.2.

96

Python, 0.2

( )
, ,
(, , -h,
).
, . ( )
, .
, , , ,
( ), , ( ) . ( , , , ).
(.. __init__.py) .
, , , , , , .
. , , (
). __init__. .
- ,
, .
override, ,
; extend, ,
( ).
, , :
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
if imag == 0.0 and real == 0.0: return complex_zero
...

python (,
Lib python).

25.3.

97

26

: ,
import from

Python (-, , , ). ,
, , .
, . , Python,
, C C++.

26.1
import. , os :
>>> import os
>>> os.getcwd()
'C:\\Python33'

import .
, ,
. time random.
>>> import time, random
>>> time.time()
1376047104.056417
>>> random.random()
0.9874550833306869

,
. ,
e, math:

98

Python, 0.2

>>> import math


>>> math.e
2.718281828459045

, , AttributeError. ,
ImportError.
>>> import notexist
Traceback (most recent call last):
File "", line 1, in
import notexist
ImportError: No module named 'notexist'
>>> import math
>>> math.
Traceback (most recent call last):
File "", line 1, in
math.
AttributeError: 'module' object has no attribute ''

26.2
, -
, , as.
>>> import math as m
>>> m.e
2.718281828459045

math m, math (, ,
import math, m,
math).

26.3 from
from.
:
from < > import < 1> [ as < 1> ], [< 2> [ as
< 2> ] ...]
from < > import *

.
, as.

26.2.

99

Python, 0.2

>>> from math import e, ceil as c


>>> e
2.718281828459045
>>> c(4.6)
5

, ,
:
>>> from math import (sin, cos,
...
tan, atan)

from (, ) . sys:
>>> from sys import *
>>> version
'3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)]'
>>> version_info
sys.version_info(major=3, minor=3, micro=2, releaselevel='final', serial=0)

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

26.4 Python
. mymodule.py, - :
def hello():
print('Hello, world!')
def fib(n):
a = b = 1
for i in range(n - 2):
a, b = b, a + b
return b

, , main.py:
import mymodule
mymodule.hello()
print(mymodule.fib(10))

26.4. Python

100

Python, 0.2

:
Hello, world!
55

! ! , :

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

26.4.2 ?
, .
sys.path. ( ), , python.
, sys.path ,
(,
sys.path).

26.4.3 ?
. ,
, , - ,
. , , ,
. __name__, , __main__,
, , . , mymodule.py
:
def hello():
print('Hello, world!')
def fib(n):
a = b = 1
for i in range(n - 2):
a, b = b, a + b
return b
if __name__ == "__main__":

26.4. Python

101

Python, 0.2

hello()
for i in range(10):
print(fib(i))

26.4. Python

102

27

- .

- python.
- () , .
, . .
, .
Python - .
python - , , , .
python .
(), .
- .
,
.
python. :
>>> #
... class A:
...
pass

:
>>>
>>>
>>>
>>>
>>>
1

a = A()
b = A()
a.arg = 1 # a arg, 1
b.arg = 2 # b - arg, 2
print(a.arg)

103

Python, 0.2

>>> class A:
...
def g(self): # self - ,
...
# , ,
...
#
...
# .
...
return 'hello world'
...
>>> a = A()
>>> a.g()
'hello world'

:
>>> class B:
...
arg = 'Python' # arg,
...
# "Python"
...
#
...
def g(self):
...
return self.arg
...
>>> b = B()
>>> b.g()
'Python'
>>> B.g(b)
'Python'
>>> b.arg = 'spam'
>>> b.g()
'spam'

104

28

, ,

-
python, , , .

28.1
(
). .
Python
, , .
,
,
.
class A:
def _private(self):
print(" !")
>>> a = A()
>>> a._private()
!

: .
>>> class B:
...
def __private(self):
...
print(" !")
...
>>> b = B()
>>> b.__private()
Traceback (most recent call last):

105

Python, 0.2

File "<stdin>", line 1, in <module>


AttributeError: 'B' object has no attribute '__private'

,
___:
>>> b._B__private()
!

28.2
, ,
. , , :
>>> class Mydict(dict):
...
def get(self, key, default = 0):
...
return dict.get(self, key, default)
...
>>> a = dict(a=1, b=2)
>>> b = Mydict(a=1, b=2)

Mydict , , , get
None, 0.
>>> b['c'] = 4
>>> print(b)
{'a': 1, 'c': 4, 'b': 2}
>>> print(a.get('v'))
None
>>> print(b.get('v'))
0

28.3
- . ,
, .
, .
>>> 1 + 1
2
>>> "1" + "1"
'11'

28.2.

106

29

,
- .
, :
class A:
def go(self):
print('Go, A!')
class B(A):
def go(self, name):
print('Go, {} !'.format(name))

B A, go,
A.
python , , , , .
, __init__ . - .
>>> class A:
...
def __init__(self, name):
...
self.name = name
...
>>> a = A('Vasya')
>>> print(a.name)
Vasya

, .
__new__(cls[, ...]) .
( ).
__init__.
__init__(self[, ...]) - , .
__del__(self) - .

107

Python, 0.2

__repr__(self) - repr; , python.


__str__(self) - str, print format. .
__bytes__(self) - bytes .
__format__(self, format_spec) - format ( format
).
__lt__(self, other) - x < y x.__lt__(y).
__le__(self, other) - x <= y x.__le__(y).
__eq__(self, other) - x == y x.__eq__(y).
__ne__(self, other) - x != y x.__ne__(y)
__gt__(self, other) - x > y x.__gt__(y).
__ge__(self, other) - x >= y x.__ge__(y).
__hash__(self) - - , , .
__bool__(self) - . , __len__ (, , ).
__getattr__(self, name) - , (, ).
__setattr__(self, name, value) - .
__delattr__(self, name) - (del obj.name).
__call__(self[, args...]) - .
__len__(self) - .
__getitem__(self, key) - ( ).
__setitem__(self, key, value) - .
__delitem__(self, key) - .
__iter__(self) - .
__reversed__(self) - , .
__contains__(self, item) - (item in self).

29.1
__add__(self, other) - . x + y x.__add__(y).
__sub__(self, other) - (x - y).
__mul__(self, other) - (x * y).

29.1.

108

Python, 0.2

__truediv__(self, other) - (x / y).


__oordiv__(self, other) - (x // y).
__mod__(self, other) - (x % y).
__divmod__(self, other) - (divmod(x, y)).
__pow__(self, other[, modulo]) - (x ** y, pow(x, y[, modulo])).
__lshift__(self, other) - (x << y).
__rshift__(self, other) - (x >> y).
__and__(self, other) - (x & y).
__xor__(self, other) - (x ^ y).
__or__(self, other) - (x | y).
.
__radd__(self, other),
__rsub__(self, other),
__rmul__(self, other),
__rtruediv__(self, other),
__roordiv__(self, other),
__rmod__(self, other),
__rdivmod__(self, other),
__rpow__(self, other),
__rlshift__(self, other),
__rrshift__(self, other),
__rand__(self, other),
__rxor__(self, other),
__ror__(self, other) - , , , , , ,
.
, x + y x.__add__(y), , , y.__radd__(x). .
.
__iadd__(self, other) - +=.
__isub__(self, other) - -=.
__imul__(self, other) - *=.
__itruediv__(self, other) - /=.
29.1.

109

Python, 0.2

__ioordiv__(self, other) - //=.


__imod__(self, other) - %=.
__ipow__(self, other[, modulo]) - **=.
__ilshift__(self, other) - <<=.
__irshift__(self, other) - >>=.
__iand__(self, other) - &=.
__ixor__(self, other) - ^=.
__ior__(self, other) - |=.
__neg__(self) - -.
__pos__(self) - +.
__abs__(self) - (abs()).
__invert__(self) - (~).
__complex__(self) - complex.
__int__(self) - int.
__oat__(self) - oat.
__round__(self[, n]) - .
__enter__(self), __exit__(self, exc_type, exc_value, traceback) - .
,
:
import math
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Vector2D({} , {} )'.format(self.x, self.y)
def __str__(self):
return '({} , {} )'.format(self.x, self.y)
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self

29.1.

110

Python, 0.2

def __sub__(self, other):


return Vector2D(self.x - other.x, self.y - other.y)
def __isub__(self, other):
self.x -= other.x
self.y -= other.y
return self
def __abs__(self):
return math.hypot(self.x, self.y)
def __bool__(self):
return self.x != 0 or self.y != 0
def __neg__(self):
return Vector2D(-self.x, -self.y)
>>> x = Vector2D(3, 4)
>>> x
Vector2D(3, 4)
>>> print(x)
(3, 4)
>>> abs(x)
5.0
>>> y = Vector2D(5, 6)
>>> y
Vector2D(5, 6)
>>> x + y
Vector2D(8, 10)
>>> x - y
Vector2D(-2, -2)
>>> -x
Vector2D(-3, -4)
>>> x += y
>>> x
Vector2D(8, 10)
>>> bool(x)
True
>>> z = Vector2D(0, 0)
>>> bool(z)
False
>>> -z
Vector2D(0, 0)

, - ,
. ,
, .

29.1.

111

30

Python .
, ? , , , , python , ,
. , python .
, . , ,
, ,
.
:
>>> def my_shiny_new_decorator(function_to_decorate):
...
# -"".
,
...
# .
...
def the_wrapper_around_the_original_function():
...
print(" - , ")
...
function_to_decorate() #
...
print(" - , ")
...
#
...
return the_wrapper_around_the_original_function
...
>>> # , ,
.
>>> def stand_alone_function():
...
print(" , ?")
...
>>> stand_alone_function()
, ?
>>> # , , ,
,
>>> # , ,
,
>>> # :
>>> stand_alone_function_decorated = my_shiny_new_decorator(stand_alone_function)
>>> stand_alone_function_decorated()

112

Python, 0.2

- ,
, ?
- ,

, , , stand_alone_function,
stand_alone_function_decorated.
stand_alone_function:
>>> stand_alone_function = my_shiny_new_decorator(stand_alone_function)
>>> stand_alone_function()
- ,
, ?
- ,

, . ,
:
>>> @my_shiny_new_decorator
... def another_stand_alone_function():
...
print(" ")
...
>>> another_stand_alone_function()
- ,

- ,

, python :
another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)

, , ,
:
>>>
...
...
...
...
...
...
>>>
...
...
...
...
...
...
>>>
...
...
>>>

def bread(func):
def wrapper():
print()
func()
print("<\______/>")
return wrapper
def ingredients(func):
def wrapper():
print("##")
func()
print("~~")
return wrapper
def sandwich(food="----"):
print(food)
sandwich()

113

Python, 0.2

--->>> sandwich = bread(ingredients(sandwich))


>>> sandwich()
##
---~~
<\______/>

:
>>>
...
...
...
...
>>>

@bread
@ingredients
def sandwich(food="----"):
print(food)
sandwich()

##
---~~
<\______/>

, .
:
>>> @ingredients
... @bread
... def sandwich(food="----"):
...
print(food)
...
>>> sandwich()
##
---<\______/>
~~

30.1
, , , . ,
.
>>> def a_decorator_passing_arguments(function_to_decorate):
...
def a_wrapper_accepting_arguments(arg1, arg2):
...
print(", :", arg1, arg2)
...
function_to_decorate(arg1, arg2)

30.1.

114

Python, 0.2

...
return a_wrapper_accepting_arguments
...
>>> # , , ,
"",
>>> #

>>> @a_decorator_passing_arguments
... def print_full_name(first_name, last_name):
...
print(" ", first_name, last_name)
...
>>> print_full_name("Vasya", "Pupkin")
, : Vasya Pupkin
Vasya Pupkin

30.2
, , ,
Python , , (self). ,
, ,
self.
>>>
...
...
...
...
...
>>>
...
...
...
...
...
...
>>>
>>>

def method_friendly_decorator(method_to_decorate):
def wrapper(self, lie):
lie -= 3
return method_to_decorate(self, lie)
return wrapper
class Lucy:
def __init__(self):
self.age = 32
@method_friendly_decorator
def sayYourAge(self, lie):
print(" {} , ?".format(self.age + lie))
l = Lucy()
l.sayYourAge(-3)
26 , ?

, ,
, :
>>> def a_decorator_passing_arbitrary_arguments(function_to_decorate):
...
# ""
...
def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
...
print(" -?:")
...
print(args)

30.2.

115

Python, 0.2

...
print(kwargs)
...
function_to_decorate(*args, **kwargs)
...
return a_wrapper_accepting_arbitrary_arguments
...
>>> @a_decorator_passing_arbitrary_arguments
... def function_with_no_argument():
...
print("Python is cool, no argument here.")
...
>>> function_with_no_argument()
-?:
()
{}
Python is cool, no argument here.
>>> @a_decorator_passing_arbitrary_arguments
... def function_with_arguments(a, b, c):
...
print(a, b, c)
...
>>> function_with_arguments(1, 2, 3)
-?:
(1, 2, 3)
{}
1 2 3
>>> @a_decorator_passing_arbitrary_arguments
... def function_with_named_arguments(a, b, c, platypus=" ?"):
...
print(" {} , {} {} ? {} ".format(a, b, c, platypus))
...
>>> function_with_named_arguments("", "", "", platypus="!")
-?:
('', '', '')
{'platypus': '!'}
, ? !
>>> class Mary(object):
...
def __init__(self):
...
self.age = 31
...
@a_decorator_passing_arbitrary_arguments
...
def sayYourAge(self, lie=-3): #

...
print(" {} , ?".format(self.age + lie))
...
>>> m = Mary()
>>> m.sayYourAge()
-?:
(<__main__.Mary object at 0x7f6373017780>,)
{}
28 , ?

30.2.

116

Python, 0.2

30.3
, :
>>> def decorator_maker():
...
print(" ! :
.")
...
def my_decorator(func):
...
print(" - ! :
.")
...
def wrapped():
...
print (" - .\n"
...
" ,
.\n"
...
" .")
...
return func()
...
print(" .")
...
return wrapped
...
print(" .")
...
return my_decorator
...
>>> # .
>>> new_decorator = decorator_maker()
! :
.
.
>>>
>>> #
>>> def decorated_function():
...
print(" - .")
...
>>> decorated_function = new_decorator(decorated_function)
- ! : .
.
>>> # :
>>> decorated_function()
- .
, .
.
- .

:
>>> @decorator_maker()
... def decorated_function():
...
print(" - .")
...
! :
.
.
- ! : .

30.3.

117

Python, 0.2

.
>>> decorated_function()
- .
.
.
- .

, , , , , ?
>>> def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):
...
print(" ! :",
...
decorator_arg1, decorator_arg2)
...
def my_decorator(func):
...
print(" - . :",
...
decorator_arg1, decorator_arg2)
...
# !
...
def wrapped(function_arg1, function_arg2):
...
print (" - .\n"
...
" \n"
...
"\t- : {0} {1} \n"
...
"\t- : {2} {3} \n"
...
" "
...
.format(decorator_arg1, decorator_arg2,
...
function_arg1, function_arg2))
...
return func(function_arg1, function_arg2)
...
return wrapped
...
return my_decorator
...
>>> @decorator_maker_with_arguments("", "")
... def decorated_function_with_arguments(function_arg1, function_arg2):
...
print (" - : {0} "
...
" {1} ".format(function_arg1, function_arg2))
...
! :
- . :
>>> decorated_function_with_arguments("", "")
- .

- :
- :

- :

, , . *args **kwargs .

30.3.

118

Python, 0.2

30.4
, .
. , , , ,
. ,
.
, .
functools
functools.wraps, ( ,
, ..) -.
, functools.wraps .
>>> def foo():
...
print("foo")
...
>>> print(foo.__name__)
foo
>>> # , :
... def bar(func):
...
def wrapper():
...
print("bar")
...
return func()
...
return wrapper
...
>>> @bar
... def foo():
...
print("foo")
...
>>> print(foo.__name__)
wrapper
>>> import functools # "functools"
>>> def bar(func):
...
# "wrapper" "func"
...
# :
...
@functools.wraps(func)
...
def wrapper():
...
print("bar")
...
return func()
...
return wrapper
...
>>> @bar
... def foo():
...
print("foo")
...
>>> print(foo.__name__)
foo

30.4.

119

Python, 0.2

30.5
( ),
( , ).

, , :
>>>
...
...
...
...
...
...
...
...
...
...
...
...
>>>
...
...
...
...
...
...
...
...
...
...
>>>
...
...
...
...
...
...
...
...
...
...
...
...
>>>
...
...
...
...

def benchmark(func):
"""
, ,
.
"""
import time
def wrapper(*args, **kwargs):
t = time.clock()
res = func(*args, **kwargs)
print(func.__name__, time.clock() - t)
return res
return wrapper
def logging(func):
"""
, .
(, , !)
"""
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
print(func.__name__, args, kwargs)
return res
return wrapper
def counter(func):
"""
,
.
"""
def wrapper(*args, **kwargs):
wrapper.count += 1
res = func(*args, **kwargs)
print("{0} : {1} x".format(func.__name__, wrapper.count))
return res
wrapper.count = 0
return wrapper
@benchmark
@logging
@counter
def reverse_string(string):
return ''.join(reversed(string))

30.5.

120

Python, 0.2

...
>>> print(reverse_string(" "))
reverse_string : 1x
wrapper (' ',) {}
wrapper 0.00011799999999997923

>>> print(reverse_string("A man, a plan, a canoe, pasta, heros, rajahs, a
coloratura,"
... "maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag,"
... "a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash,"
... "a jar, sore hats, a peon, a canal: Panama!"))
reverse_string : 2x
wrapper ('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura,maps, snipe, .
..',) {}
wrapper 0.00017800000000001148
!amanaP :lanac a ,noep a ,stah eros ,raj a,hsac ,oloR a ,tur a ,mapS ,snip ,eperc
a , ...

30.5.

121

31

python- pip

pip - , , Python.

31.1 pip
pip python-,
pip.

31.1.1 Python 3.4+


Python 3.4, pip python.

31.1.2 Python <3.4


( https://pip.pypa.io/en/latest/installing.html ):
get-pip.py ( .py).
( ).
( Windows). , :
setuptools http://www.lfd.uci.edu/~gohlke/pythonlibs/#setuptools
pip http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip

31.2
pip - , , numpy:
Linux:

122

Python, 0.2

sudo pip3 install numpy

Windows:
pip3 install numpy

, : python ,
(, ,
pip , ).
:
C:\Python34\Tools\Scripts\pip3.exe install numpy

C:\Python34\Tools\Scripts\ PATH (
, stackoverow. - ).

31.3 pip
pip:
pip help - .
pip install package_name - ().
pip uninstall package_name - ().
pip list - .
pip show package_name - .
pip search - .
pip proxy user:passwd@proxy.server:port - .
pip install -U - ().
pip install force-reinstall - , , .

31.3. pip

123

32

, Python.

32.1 UnboundLocalError,
?
UnboundLocalError , - .
:
>>> x = 10
>>> def bar():
...
print(x)
>>> bar()
10

, :
>>> x =
>>> def
...
...

10
foo():
print(x)
x += 1

UnboundLocalError :
>>> foo()
Traceback (most recent call last):
...
UnboundLocalError: local variable 'x' referenced before assignment

, , ,
.

124

Python, 0.2

foo x , , . , print
, .
, :
>>> x = 10
>>> def foobar():
...
global x
...
print(x)
...
x += 1
>>> foobar()
10

, , (
), ,
:
>>> print(x)
11


nonlocal :
>>> def foo():
...
x = 10
...
def bar():
...
nonlocal x
...
print(x)
...
x += 1
...
bar()
...
print(x)
>>> foo()
10
11

32.2 Python?
Python, , , . - ,
, , , , .
, . ,
global
bar . , global , global .

32.2. Python?

125

Python, 0.2

32.3 (lambda),
,
?
, :
>>> squares = []
>>> for x in range(5):
...
squares.append(lambda: x**2)

5 , x**2 . , , , , , 0, 1, 4, 9, 16. , ,
16:
>>> squares[2]()
16
>>> squares[4]()
16

, x lambda ,
, , - .
, x=4 , 4**2 , 16 .
, x :
>>> x = 8
>>> squares[2]()
64

, :
>>> squares = []
>>> for x in range(5):
...
squares.append(lambda n=x: n**2)

, n=x n :
>>> squares[2]()
4
>>> squares[4]()
16

, .

32.3. (lambda),
, ?

126

Python, 0.2

32.4 ?
- ( cong cfg). import config . . , , . :
cong.py:
x = 0

mod.py:
import config
config.x = 1

main.py:
import config
import mod
print(config.x)

,
.

32.5 ?
from modulename import * .
, . , , . Tkinter threading.
. ,
.
, .
, :
(, sys, os, getopt, re)
(, site-packages)
, PIL, NumPy ..

, . Gordon McMillan :
32.4.
127
?

Python, 0.2

, import
<module> . ,
(from module import name ) .
- , , .
, , . , ,
.
, -. .
- .
, ,
, ,
.
, ,
, . ,
. ,
- , ,
. ,
sys.modules .

32.6 ?
. , :
def foo(mydict={}): # :
... compute something ...
mydict[key] = value
return mydict

, , mydict .
, mydict 2 , , foo() , mydict
.
, . . ,
. , ,
.
, (, , None),
. , , ,
.

32.6. ?

128

Python, 0.2

,
. , None ,
None /. , :
def foo(mydict={}):
...

:
def foo(mydict=None):
if mydict is None:
mydict = {} # create a new dict for local namespace

, . , , -
:
def expensive(arg1, arg2, _cache={}):
if (arg1, arg2) in _cache:
return _cache[(arg1, arg2)]
#
result = ... expensive computation ...
_cache[(arg1, arg2)] = result
#
return result

32.7 ?
* ** ;
. , * **:
def f(x, *args, **kwargs):
...
kwargs['width'] = '14.3c'
...
g(x, *args, **kwargs)

32.8 y x?
:
>>> x = []
>>> y = x

32.7. 129
?

Python, 0.2

>>> y.append(10)
>>> y
[10]
>>> x
[10]

, , , y x .
:
- . y = x -
y , , x .
.
append , [] [10] . x
y , [10] .
:
>>>
>>>
>>>
>>>
6
>>>
5

x = 5 #
y = x
x = x + 1 # 5 .
x
y

, x y , , x =
x + 1 5 . , 6
x ( , , x ).
2 (6 5) 2 , .
( y.append(10) y.sort() ) , ,
( y = y + [10] sorted(y) )
. Python ( ), ,
, None , . ,

y = y.sort()

, y, None ,
.
, , : . ,
+= , (a_list += [1,2,3]
a_list.extend([1,2,3]) ) , , some_tuple += (1,2,3)
some_int += 1 .
, 2 ,
is , id .

32.8. y x?

130

Python, 0.2

32.9 ?
: . ,
:
def linear(a, b):
def result(x):
return a * x + b
return result

:
class linear:
def __init__(self, a, b):
self.a, self.b = a, b
def __call__(self, x):
return self.a * x + self.b

,
taxes = linear(0.3, 2)

, ( ) taxes(10e6) == 0.3 * 10e6 + 2 .


- ,
. , , :
class exponential(linear):
# __init__
def __call__(self, x):
return self.a * (x ** self.b)

:
class counter:
value = 0
def set(self, x):
self.value = x
def up(self):
self.value = self.value + 1
def down(self):
self.value = self.value - 1

32.9. ?

131

Python, 0.2

count = counter()
inc, dec, reset = count.up, count.down, count.set

inc , dec , reset , .

32.10 Python?
, copy.
. copy:
newdict = olddict.copy()

:
new_l = l[:]

32.11 ?
dir(x) .

32.12 ?
, , . :
. def class
.
>>> class A:
...
pass
...
>>> B = A
>>>
>>> a = B()
>>> b = a
>>> print(b)
<__main__.A object at 0x7fbcc3ee5160>
>>> print(a)
<__main__.A object at 0x7fbcc3ee5160>

, : ,
B , A . ,
, a b ,
.

32.10. Python?

132

Python, 0.2

32.13 ?
Python.
>>> "a" in "b", "a"
(False, 'a')

- , , :
("a" in "b"), "a"


"a" in ("b", "a")

(= , += ).
, .

32.14 Python ?:
C?
. :
[on_true] if [expression] else [on_false]
x, y = 50, 25
small = x if x < y else y

32.15 ?
.
from functools import reduce
# < 1000
print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))
# 10
print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
f(x,f), range(10))))
#

32.13. ?

133

Python, 0.2

print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,


Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
#
\___ ___/ \___ ___/ |
|
|__ lines on screen
#
V
V
|
|______ columns on screen
#
|
|
|__________ maximum of "iterations"
#
|
|_________________ range on y axis
#
|____________________________ range on x axis

32.16 -22 // 10 -3?


i % j , j .
i == (i // j) * j + (i % j)

32.17 ?
, . , . , ,
io.StringIO , array:
>>> import io
>>> s = "Hello, world"
>>> sio = io.StringIO(s)
>>> sio.getvalue()
'Hello, world'
>>> sio.seek(7)
7
>>> sio.write("there!")
6
>>> sio.getvalue()
'Hello, there!'
>>> import array
>>> a = array.array('u', s)
>>> print(a)
array('u', 'Hello, world')
>>> a[0] = 'y'
>>> print(a)
array('u', 'yello, world')

32.16. -22 // 10 -3?

134

Python, 0.2

>>> a.tounicode()
'yello, world'

32.18 /?
.
- , . - .
def a():
pass
def b():
pass
dispatch = {'go': a, 'stop': b}

# Note lack of parens for funcs

dispatch[get_input()]()

getattr:
import foo
getattr(foo, 'bar')()

locals eval ( )
def myFunc():
print("hello")
fname = "myFunc"
f = locals()[fname]
f()
f = eval(fname)
f()

32.19 ?
S.rstrip("\r\n") , :
>>> lines = ("line 1 \r\n"
...
"\r\n"
...
"\r\n")

32.18. /?

135

Python, 0.2

>>> lines.rstrip("\r\n")
'line 1 '

32.20 ?
: http://code.activestate.com/recipes/52560/

32.21 ?
, :
>>> A = [[None] * 2] * 3

, :
>>> A
[[None, None], [None, None], [None, None]]

, :
>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]

, * ,
. *3 3 .
, , , , .
:
A = [None] * 3
for i in range(3):
A[i] = [None] * 2
w, h = 2, 3
A = [[None] * w for i in range(h)]

, , .
NumPy.

32.20. ?

136

Python, 0.2

32.22 a_tuple[i] += [item] , ?


- , - , - Python.
, , ,
+= , .
:
>>> a_tuple = (1, 2)
>>> a_tuple[0] += 1
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment

: 1 a_tuple[0] ,
, 2 , ,
, .
, :
>>> result = a_tuple[0] + 1
>>> a_tuple[0] = result
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment

- :
>>> a_tuple = (['foo'], 'bar')
>>> a_tuple[0] += ['item']
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment

, , ,
, !
>>> a_tuple[0]
['foo', 'item']

, , , :
__iadd__ , , += ,

, __iadd__ extend
,
32.22. a_tuple[i] += [item] , ?

137

Python, 0.2

>>> a_list = []
>>> a_list += [1]
>>> a_list
[1]

:
>>> result = a_list.__iadd__([1])
>>> a_list = result

, :
>>> result = a_tuple[0].__iadd__(['item'])
>>> a_tuple[0] = result
Traceback (most recent call last):
...
TypeError: 'tuple' object does not support item assignment

__iadd__ , ,
.

32.22. a_tuple[i] += [item] , ?

138

Оценить