Академический Документы
Профессиональный Документы
Культура Документы
0.2
07, 2017
1 python 1
2 Python 2
2.1 Python Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Python linux (ubuntu, linux mint ) . . . . . . . . . 8
3 . IDLE 10
4 Python 13
4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5 . ? 15
6 if-elif-else, , if/else 20
6.1 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
6.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
6.3 if/else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
8 , keyword 25
8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
8.2 keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
9 27
9.1 , . . . . . . . . . . . 27
9.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
i
10 : , , 31
10.1 (int) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
10.2 (oat) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
10.3 (complex) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
11 Python: 37
11.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
12 . 40
12.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
12.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
12.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
13 . format 45
13.1 format . . . . . . . . . . . . . . . . . . 45
14 (list). 48
14.1 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
14.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
14.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
15 51
15.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
15.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
16 (tuple) 54
16.1 , ? . . . . . . . . . . . . . . . . . . . . . . . 54
16.2 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
16.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
17 (dict) . 57
17.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
18 (set frozenset) 60
18.1 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
18.2 frozenset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
19 63
19.1 , def . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
19.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
19.3 , lambda . . . . . . . . . . . . . . . . . . . . . . . 65
21 (bytes bytearray) 71
21.1 Bytearray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
ii
23 . . 76
23.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
23.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
24 With ... as - 79
25 PEP 8 - Python 81
25.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
25.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
25.3 . . . . . . . . . . . . . . . . . . . . . . . . . 87
25.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
25.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
25.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
25.7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
28 - . 110
29 , , 112
29.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
29.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
29.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
30 115
30.1 . . . . . . . . . . . . . . . . . . . . . . . . 117
31 121
31.1 . . . . . . . . . . . . . . . . . . . . 123
31.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
31.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
31.4 . . . . . . . . . . . . . . . . . . . 128
31.5 . . . . . . . . . . . . . . . . . . . . . . . . . 129
33 133
iii
33.1 UnboundLocalError,
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
33.2 Python? . . . . . 134
33.3 (lambda),
, ? . . . . . . . . . . . . . . . . . 135
33.4
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
33.5 ? . . . . . . . . . . . . . . . . . . 136
33.6 ? . . . . . . . . 137
33.7 -
? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
33.8 y x? . . . . . . . . . . . . . 139
33.9 ? . . . . . . . . . . . . . . . . . . 140
33.10 Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
33.11 ? . . . . . . . . . . . . . . . . . 141
33.12 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
33.13 ? . . . . . . . . . . . . . . . . . . . . . . . . 142
33.14 Python ?: C? . . . . . . . . . . . . 142
33.15 ? . . . . . . . . . . . . . . . 142
33.16 -22 // 10 -3? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
33.17 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
33.18 /? . . . . . . . . . . . . . . 144
33.19 ? . . . . . . . . . . . . . . 145
33.20 ? . . . . . . . . . . . . . . . . . . 145
33.21 ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
33.22 a_tuple[i] += [item] , ? . . . . . . . . . 146
34 Python 148
34.1 (1) . . . . . . . . . . . . . . . . . . . . . . 148
34.2 (2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
34.3 (3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
34.4 (4) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
34.5 (5) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
34.6 (6) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
34.7 (7) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
34.8 XOR- (8) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
iv
1
python
, Python,
.
, python:
xml/html
http
GUI ( )
-
FTP
,
, ...
, python ,
, , - .
Python , -
. , python IT-
, , , Google Yandex. -
python .
1
2
Python
, python 3 . -
, SMS :)
Python Windows
python . , -
python , . -
. https://python.org/downloads/windows/, latest python
release python 3.
python 2 .
python 3.4.1.
2
Python, 0.2
Python ( ). -
- . , download
page.
, python . .
Python Software Foundation, , . , ,
exe .
( ).
. .
.
, . -
, .
python...
Finish. , Python! python windows
IDLE. -
!
( ctrl+alt+t). :
python3
, python 3:
, : python 3.
*python3*:
python3 path_to_file.py
(, IDLE, -
).
. IDLE
IDLE.
python IDLE ( Python,
).
Windows, -
.
10
Python, 0.2
IDLE ( ), -
. ,
hello world.
hello world python, :
print("Hello world!")
IDLE Enter. :
! python! ( - ).
, ,
,
print(3 + 4)
print(3 * 5)
print(3 ** 2)
, -, . ,
.
, , IDLE File New
File ( Ctrl + N).
11
Python, 0.2
( ? ), , -
Enter name.
print ,
, , name.
F5 ( IDLE Run Run Module) , ,
, . IDLE .
, , .
- ( -
, - ):
! ,
IDLE. ,
python . python, . !
12
4
Python
Python, , .
( ).
.
, , -
. . 1 , ,
. 4 ( , ).
Python
, ,
, -
.
, -
:
a = 1; b = 2; print(a, b)
13
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. 14
5
. ?
! ? -
python 3, ,
.
: . ,
.
: (
.
( , , ),
, .
: IDLE .
: input. SyntaxError.
:
>>> a = input()
hello world
File "<string>", line 1
hello world
^
SyntaxError: unexpected EOF while parsing
: Python 2.
: Python 3.
: - , .
:
15
Python, 0.2
name = raw_input()
print name
: Python 2.
: Python 2 Python 3. Python 3. -
, Python 3 :
name = input()
print(name)
>>> 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
a = 5
if a == 5
print('!')
16
Python, 0.2
: .
:
a = 5
if a == 5:
print('!')
a = 5
if a = 5:
print('!')
: .
:
a = 5
if a == 5:
print('!')
print(a)
: a . , -
.
: .
a = 10
print(a)
a = 10
if a > 0:
print(a)
: .
17
Python, 0.2
:
a = 10
if a > 0:
print(a)
:
File "a.py", line 5
print('!')
^
TabError: inconsistent use of tabs and spaces in indentation
: .
: .
a = 10
if a > 0:
print(a)
print('!')
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
: , .
:
18
Python, 0.2
def f():
global a
a += 1
print(a)
a = 10
f()
: , / .
:
: , .
:
: . :)
:
19
6
if-elif-else, ,
if/else
if-elif-else ( ) - -
Python. , , -
, .
if
if ,
elif, , , else.
if :
if test1:
state1
elif test2:
state2
else:
state3
( true, 1 - ):
>>> if 1:
... print('true')
... else:
... print('false')
...
true
20
Python, 0.2
( , -
):
a = int(input())
if a < -5:
print('Low')
elif -5 <= a <= 5:
print('Mid')
else:
print('High')
elif
switch - case .
Python
, 0, - .
, 0, None -
True False
and or -
:
X and Y
, X Y .
X or Y
, X Y .
not X
, X .
if/else
if X:
A = Y
else:
A = Z
6.2. Python 21
Python, 0.2
, , , 4 .
if/else:
A = Y if X else Z
Y, X , -
Z.
6.3. if/else 22
7
while
While - Python, .
, .
>>> i = 5
>>> while i < 15:
... print(i)
... i = i + 2
...
5
7
9
11
13
for
for , , -
while. ( -
23
Python, 0.2
), .
continue
continue , (for
while)
break
break .
else
7.3. continue 24
8
, keyword
- Python, -
keyword.
False - .
True - .
None - .
and - .
with / as - .
assert - , .
break - .
class - , .
continue - .
def - .
del - .
elif - , .
else - . for/else if/else.
except - .
25
Python, 0.2
nally - try, ,
.
for - for.
from - .
global - , , -
.
if - .
import - .
in - .
is - 2 .
lambda - .
nonlocal - , , -
.
not - .
or - .
pass - .
raise - .
return - .
try - , .
while - while.
yield - -.
keyword
-, keyword - , .
keyword.kwlist - .
keyword.iskeyword() - .
8.2. keyword 26
9
Python 3.
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() - , .
27
Python, 0.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() - .
9.2. 28
Python, 0.2
9.2. 29
Python, 0.2
super([ [, ]]) - .
type(object) - .
type(name, bases, dict) - name.
vars([object]) - . - .
zip(*iters) - , , -
-.
9.2. 30
10
: , ,
Python 3: , , .
.
(int)
Python 3 . -
:
x+y
x-y
x*y
x/y
x // y
x%y
-x
abs(x)
divmod(x, y) (x // y, x % y)
x ** y
pow(x, y[, z]) xy ( )
, python 3, ,
(, ).
>>> 255 + 34
289
>>> 5 * 2
10
>>> 20 / 3
31
Python, 0.2
6.666666666666667
>>> 20 // 3
6
>>> 20 % 3
2
>>> 3 ** 4
81
>>> pow(3, 4)
81
>>> pow(3, 4, 27)
0
>>> 3 ** 150
369988485035126972924700782451696644186473100389722973815184405301748249
x|y
x^y
x&y
x << n
x >> y
~x
int.bit_length() - , ,
.
>>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6
10.1. (int) 32
Python, 0.2
, , , -
. ,
, , , 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)
10.1. (int) 33
Python, 0.2
19
>>> int('0b10011', 2)
19
(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
oat.as_integer_ratio() - , .
oat.is_integer() - .
oat.hex() - oat hex ( ).
classmethod oat.fromhex(s) - oat .
>>> (10.5).hex()
'0x1.5000000000000p+3'
10.2. (oat) 34
Python, 0.2
>>> float.fromhex('0x1.5000000000000p+3')
10.5
( Python ),
Python .
math .
random .
(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):
10.3. (complex) 35
Python, 0.2
cmath.
10.3. (complex) 36
11
Python:
Python - , -
, -
, .
, .
Python . , -
.
S = 'spam"s'
S = "spam's"
- .
, ,
.
,
.
37
Python, 0.2
\n
\a
\b
\f
\r
\t
\v
\N{id} ID
\uhhhh 16- 16-
\Uhhhh. . . 32- 32-
\xhh 16-
\ooo 8-
\0 Null ( )
r ( ),
.
S = r'C:\newt.txt'
, , -
. :
S = r'\n\n\\'[:-1]
S = r'\n\n' + '\\'
S = '\\n\\n'
,
. -
, , .
>>> c = '''
... ,
... '''
>>> c
' \n, \n '
>>> print(c)
,
11.1. 38
Python, 0.2
.
.
11.1. 39
12
, , -
.
, - -
.
()
>>> S1 = 'spam'
>>> S2 = 'eggs'
>>> print(S1 + S2)
'spameggs'
>>> print('spam' * 3)
spamspamspam
( len)
>>> len('spam')
4
>>> S = 'spam'
>>> S[0]
40
Python, 0.2
's'
>>> S[2]
'a'
>>> S[-2]
'a'
, 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'
, 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
12.2. 41
Python, 0.2
, -
.
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]) . -
-1
S.rnd(str, [start],[end]) . -
-1
S.index(str, [start],[end]) .
ValueError
S.rindex(str, [start],[end]) . -
ValueError
S.replace(, )
S.split()
S.isdigit()
S.isalpha()
S.isalnum()
S.islower()
S.isupper()
12.3. 42
Python, 0.2
12.1
S.isspace()
(, -
(\f), (\n), -
(\r), -
(\t)
(\v))
S.istitle()
S.upper() -
S.lower() -
S.startswith(str) S str
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() ,
, ,
. -
, ,
,
12.3. 43
Python, 0.2
12.1
S.rpartition(sep) ,
, ,
.
, , -
, -
S.swapcase()
,
S.title()
, -
S.zll(width) width,
S.ljust(width, llchar= ) width,
-
llchar
S.rjust(width, llchar= ) width,
llchar
S.format(*args, **kwargs)
12.3. 44
13
. format
( , ) , , -
, (-
, . .). -
.
%, format.
format
, - :
,
( ):
45
Python, 0.2
format . :
::= .
::= [[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 46
Python, 0.2
d, .
i, u
o .
x ( ).
X ( ).
e ( ).
E ( ).
f, F ( ).
g . ( ),
, -4 , .
G . ( ),
, -4 , .
c ( - ).
s .
% 100, ,
%.
, :
'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 47
14
(list).
, , ,
.
Python -
( , ).
, . -
. , (, )
list:
>>> list('')
['', '', '', '', '', '']
>>> s = [] #
>>> l = ['s', 'p', ['isok'], 2]
>>> s
[]
>>> l
['s', 'p', ['isok'], 2]
, (
), .
- . -
48
Python, 0.2
, -
. for.
for .
, - .
, .
list.append(x)
list.extend(L) list, L
list.insert(i, x) i- x
list.remove(x) , x. ValueError,
list.pop([i]) i- . ,
list.index(x, x (
[start [, end]]) start end)
list.count(x) x
list.sort([key=])
list.reverse()
list.copy()
list.clear()
, , ,
, .
>>> l = [1, 2, 3, 5, 7]
>>> l.sort()
14.2. 49
Python, 0.2
>>> l
[1, 2, 3, 5, 7]
>>> l = l.sort()
>>> print(l)
None
, , :
, ,
( ,
NumPy).
14.3. 50
15
, :
>>> 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]
51
Python, 0.2
1
>>> a[-5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Python, , .
item[START:STOP:STEP] - START, STOP ( ), STEP.
START = 0, STOP = , STEP = 1. , - (
, ) .
>>> a = [1, 3, 8, 7]
>>> a[:]
[1, 3, 8, 7]
>>> a[1:]
[3, 8, 7]
>>> a[:3]
[1, 3, 8]
>>> a[::2]
[1, 8]
:
>>> a = [1, 3, 8, 7]
>>> a[::-1]
[7, 8, 3, 1]
>>> a[:-2]
[1, 3]
>>> a[-2::-1]
[8, 3, 1]
>>> a[1:4:-1]
[]
,
(, ).
>>> a = [1, 3, 8, 7]
>>> a[1:3] = [0, 0, 0]
>>> a
15.2. 52
Python, 0.2
[1, 0, 0, 0, 7]
>>> del a[:-3]
>>> a
[0, 0, 7]
15.2. 53
16
(tuple)
, (tuple) , -
.
, - .
, ?
. , ( -
), ( ).
. :
>>> a = (1, 2, 3, 4, 5, 6)
>>> b = [1, 2, 3, 4, 5, 6]
>>> a.__sizeof__()
36
>>> b.__sizeof__()
44
>>> 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'
54
Python, 0.2
, - .
, .
:
>>> a = ('s')
>>> a
's'
. . ? ! -
?
>>> a = ('s', )
>>> a
('s',)
! ! - . , , -
, , -
, . , :
>>> a = 's',
>>> a
('s',)
, , , ,
.
tuple()
16.2. ? 55
Python, 0.2
, (, , -
index() count() ). -
.
, python - -
:
a, b = b, a
16.3. 56
17
(dict) .
, , ,
, , .
Python -
. -.
, . -
. -, :
>>> d = {}
>>> d
{}
>>> d = {'dict': 1, 'dictionary': 2}
>>> d
{'dict': 1, 'dictionary': 2}
-, dict:
-, fromkeys:
57
Python, 0.2
>>> d
{'a': 100, 'b': 100}
-, ,
.
>>> 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), -
.
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 ( ).
17.1. 58
Python, 0.2
dict.popitem() - (, ). ,
KeyError. , .
dict.setdefault(key[, default]) - , , -
, default ( None).
dict.update([other]) - , (, ) other. -
. None ( !).
dict.values() - .
17.1. 59
18
(set frozenset)
! python,
.
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'>
, , , -
.
60
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.1. ? 61
Python, 0.2
frozenset
>>> 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 62
19
, ,
def, return lambda, ,
.
, def
python - , . -
def.
:
return , . -
x y.
:
(, ,
!):
63
Python, 0.2
... return x + n
... return myfunc
...
>>> new = newfunc(100) # new -
>>> new(200)
300
return, -
None:
. ,
, .
, -
*:
19.2. 64
Python, 0.2
(1,)
, args - ,
, .
,
**:
kwargs , , -,
, .
, lambda
,
. lambda. ,
, def func():
lambda , , return, ,
:
19.3. , lambda 65
20
(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 .
, ,
.
66
Python, 0.2
python , -
, . -
python 3.3, -
.
BaseException - , .
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 -
, .
67
Python, 0.2
* OSError - , .
BlockingIOError
ChildProcessError - .
ConnectionError - , -
.
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.
68
Python, 0.2
UnicodeTranslateError - , unicode.
* Warning - .
, , , -
. try - except.
:
>>> 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:
69
Python, 0.2
... f.close()
... print(' .')
... # : try, except, else,
finally.
...
. .
.
70
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'
?
, . /
71
Python, 0.2
- (, , -
). decode:
>>> b'\xd0\x91\xd0\xb0\xd0\xb9\xd1\x82\xd1\x8b'.decode('utf-8')
''
Bytearray
21.1. Bytearray 72
22
null ,
Java, C++, C# JavaScript. , .
null , -
.
Python?
, :
, null .
. , None
- , .
None :
my_none_variable = None
, None.
, -
. None, . :
# . ,
# ,
# . , MyDatabase DatabaseException
# , .
73
Python, 0.2
try:
database = MyDatabase(db_host, db_user, db_password, db_database)
database_connection = database.connect()
except DatabaseException:
pass
if database_connection is None:
print('The database could not connect')
else:
print('The database could connect')
Python -, None - ,
.
>>> type(None)
<class 'NoneType'>
None
() , None.
- is.
- == ( , -
, ).
:
null_variable = None
not_null_variable = 'Hello There!'
# The is keyword
if null_variable is None:
print('null_variable is None')
else:
print('null_variable is not None')
if not_null_variable is None:
print('not_null_variable is None')
else:
print('not_null_variable is not None')
# The == operator
if null_variable == None:
print('null_variable is None')
else:
print('null_variable is not None')
22.2. None 74
Python, 0.2
if not_null_variable == None:
print('not_null_variable is None')
else:
print('not_null_variable is not None')
null_variable is None
not_null_variable is not None
null_variable is None
not_null_variable is not None
, ! , . - .
. Python -
.
, , , MyObject == MyOtherObject.
class MyClass:
def __eq__(self, my_object):
# True
return True
my_class = MyClass()
if my_class is None:
print('my_class is None, using the is keyword')
else:
print('my_class is not None, using the is keyword')
if my_class == None:
print('my_class is None, using the == syntax')
else:
print('my_class is not None, using the == syntax')
, ? None
is.
( ) __eq__ , is
- .
22.2. None 75
23
. .
python : -
/ , .
, . , , .
open:
f = open('text.txt', 'r')
open , , -
3 : , .
. , , .
-
r ( ).
w , , ,
.
x , , .
a , .
b .
t ( ).
+
, , , rb - .
rt.
, encoding, .
.
76
Python, 0.2
, .
, .
- read, , , n
, ( n).
>>> 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'
. :
write:
23.1. 77
Python, 0.2
, , , : write -
.
close:
>>> f.close()
. -
(, , ?), .
>>> f.close()
, . (,
. .) . . python
, pickle json,
.
23.2. 78
24
With ... as -
with ... as
. , try...except...nally.
with ... as:
, :
1. with ... as.
2. __exit__ .
3. __enter__. with as, -
__enter__ .
4. suite.
5. __exit__, , suite
. , ,
None, .
with - as , -
:
79
Python, 0.2
with A() as a:
with B() as b:
suite
, ,
.
80
25
PEP 8 - Python
, python,
, python.
PEP 8 .
- , . , , PEP
(, , , ).
: , . ,
,
. ,
, .
.
. .
. , -
, , . -
, , .
, :
1. ,
, .
2. , -
(, ) ,
.
81
Python, 0.2
?
:
:
:
* ,
*
*
*
*
*
*
*
*
*
25.1. 82
Python, 0.2
4 .
-
, (, ),
. -
: ,
.
:
#
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)
:
# ,
# ,
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,
25.2. 83
Python, 0.2
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
, :
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
- .
,
.
Python 3 .
Python 2 .
Python 2 -t, -
(warnings) , -
-tt, (errors).
!
79 .
(
), 72 .
-
, ,
.
. , -
, -
, 80 100 (-
99 ), ,
72 .
25.2. 84
Python, 0.2
Python
79 ( / 72).
-
Python , .
, . -
.
. ,
with , -
:
- assert.
. -
, . :
class Rectangle(Blob):
.
.
. -
(, ).
, .
Python control+L (whitespace), -
, -
. , -
control+L .
25.2. 85
Python, 0.2
, , .
:
import os
import sys
import sys, os
, :
,
, .
:
1.
2.
3.
.
__all__ .
25.2. 86
Python, 0.2
,
(, , )
(,
sys.path):
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example
,
, , -
:
-
.
,
Python 3.
, :
, :
import myclass
import foo.bar.yourclass
myclass.MyClass foo.bar.yourclass.YourClass.
(from import *) ,
, , -
, .
,
API (,
Python (
, ).
, .
:
25.3. 87
Python, 0.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]
(
) , :
:
x = 1
y = 2
long_variable = 3
x = 1
y = 2
long_variable = 3
25.3. 88
Python, 0.2
: -
(=, +=, -= ), (==, <, >, !=, <>, <=, >=, in, not in, is, is not),
(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)
=, -
.
:
( ).
:
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()
25.3. 89
Python, 0.2
while, for if , -
, , .
!
:
, :
try: something()
finally: cleanup()
, , , . -
, !
.
, ,
, ( -
!).
, . -
, -
, .
.
, , , -
, 120%,
, .
25.4. 90
Python, 0.2
(, ),
, , . -
# (
).
,
#.
.
, . -
. -
# .
, -
. :
x = x + 1 # Increment x
, :
x = x + 1 #
, , , .
, ,
. def.
PEP 257 , . , -
, . ,
, :
"""Return a foobang
"""
25.4. 91
Python, 0.2
-
.
python ,
, , -
.
, - -
, .
, API
, , .
. , -
, , .
:
b ( )
B ( )
lowercase ( )
lower_case_with_underscores ( )
UPPERCASE ( )
UPPERCASE_WITH_UNDERSCORES ( )
CapitalizedWords ( , CapWords, CamelCase). -
: , -
HTTPServerError , HttpServerError.
mixedCase ( CapitalizedWords , -
)
25.5. 92
Python, 0.2
Capitalized_Words_With_Underscores ( -
!)
, , , -
. python,
. , os.stat() , -
st_mode, st_size, st_mtime . ( ,
POSIX,
).
X11 public-. python
, ,
.
, -
:
_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__.
, , -
.
l ( ), O ( -
) I ( ) -
.
. -
l, L.
, . -
, .
25.6. 93
Python, 0.2
,
.
,
,
Unix, ,
, Windows, Mac, DOS.
, C++, python-
( ), /++
, , _socket.
CapWords.
, -
.
, : -
- ( ), -
CapWords .
, -
. Error (, , -
).
, -
. , .
, , from M
import *, __all__, -
. , , -
( -
, ).
,
, .
mixedCase , , -
.
25.6. 94
Python, 0.2
self .
cls .
python, -
,
. , class_ , clss. (, -
).
, : -
, .
-
.
, -
.
Python : Foo __a,
Foo.__a. ( , -
Foo._Foo__a.) ,
, ,
.
: __ (. ).
, . : MAX_OVERFLOW,
TOTAL.
, ( - -
) . ,
. , .
, ,
. -
, , ,
, .
, python -
.
25.6. 95
Python, 0.2
API (
protected). ,
,
. , , -
, API ,
.
:
.
,
. , -
(, -
, , (class
method) cls).
(accessor/mutator, get/set, . .) ,
python , . -
(properties),
.
1: (properties) (
Python 3 ).
2: , -
; , , , -
.
3: , -
- , -
() .
, -
, , ,
, . -
python , -
, .
1: :
, .
2:
__getattr__(), .
3: , -
-
.
25.6. 96
Python, 0.2
, (PyPy,
Jython, IronPython, Pyrex, Psyco .).
, CPython
a+=b a=a+b. -
Jython.
.join() -
python.
None
is is not, . , if x,
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, - .
:
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
).
25.7. 97
Python, 0.2
, raise ValueError(message)
raise ValueError, message.
python 3.
, - -
,
.
,
except:.
, :
try:
import platform_specific_module
except ImportError:
platform_specific_module = None
try:
process_data()
except Exception as exc:
raise DataProcessingFailedError(str(exc))
, Python 3, -
,
.
,
, Python 3.3, errno.
try...except ,
. ,
.
:
25.7. 98
Python, 0.2
try:
value = collection[key]
except KeyError:
return key_not_found(key)
else:
return handle_value(value)
try:
# !
return handle_value(collection[key])
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'):
25.7. 99
Python, 0.2
if foo[:3] == 'bar':
isinstance(), -
:
:
if isinstance(obj, int):
if type(obj) is type(1):
, , , -
unicode-. python 2 str unicode ,
:
if isinstance(obj, basestring):
if not seq:
if seq:
if len(seq)
if not len(seq)
,
, ( reindent.py) .
True False ==:
:
if greeting:
if greeting == True:
25.7. 100
Python, 0.2
if greeting is True:
25.7. 101
26
python - , -
, ,
.
PEP 257 , python, -
, python .
PEP - :
, ( ).
PEP , .
, , -
. (, docutils), -
, .
- , -
, , .
__doc__ .
, , , ,
. -
( __init__) .
__init__.py.
, triple double quotes -
. rraw triple double quotes,
.
102
Python, 0.2
: .
.
. :
def kos_root():
"""Return the pathname of the KOS root directory."""
global _kos_root
if _kos_root: return _kos_root
, . -
.
. .
.
/
( ). :
C (,
), . ,
.
- :
(, Do X !)
, . -
, , -
. , ,
. ,
(. ).
( -
), - ,
,
26.2. 103
Python, 0.2
; , -
. , ,
.
( )
, ,
(, , -h,
).
, . -
( )
, -
.
, , , ,
( ), , -
( ) . ( , , -
, ).
(.. __init__.py) .
-
, , , , -
, , .
-
. , -
, (
). -
__init__. .
- ,
, .
override, ,
; extend, ,
( ).
, , :
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).
26.3. 104
27
: , import
from
Python (-, , -
, ). ,
, , .
, -
. , Python,
, C C++.
import. , -
os :
>>> import os
>>> os.getcwd()
'C:\\Python33'
import .
, ,
. time random.
105
Python, 0.2
,
. ,
e, math:
, , -
AttributeError. ,
ImportError.
, -
, , as.
math -
m, math (, ,
import math, m,
math).
from
from.
:
from < > import < 1> [ as < 1> ], [< 2> [ as
< 2> ] ...]
27.2. 106
Python, 0.2
.
, as.
, ,
:
from (, ) -
. sys:
, .
__all__ ( , ), -
. __all__ , -
, . ,
,
, , -
, .
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))
Hello, world!
55
! ! , -
:
, ( )
. , (
). .
, - . , , ,
.
, .
sys.path. ( -
), , python.
, sys.path ,
(,
sys.path).
. ,
, , - ,
. , , ,
. __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__":
hello()
for i in range(10):
print(fib(i))
- .
- -
python.
- () -
, .
, . .
, .
Python - .
python - , , , .
python .
(), .
- .
,
.
python. -
:
>>> #
... class A:
... pass
>>> a = A()
>>> b = A()
>>> a.arg = 1 # a arg, 1
110
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'
111
29
, ,
-
python, , -
, .
(
). -
.
Python
, , .
,
,
.
class A:
def _private(self):
print(" !")
>>> a = A()
>>> a._private()
!
: -
.
112
Python, 0.2
>>> class B:
... def __private(self):
... print(" !")
...
>>> b = B()
>>> b.__private()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'B' object has no attribute '__private'
,
___:
>>> b._B__private()
!
, -
,
. , , :
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
- . ,
, .
, .
29.2. 113
Python, 0.2
>>> 1 + 1
2
>>> "1" + "1"
'11'
29.3. 114
30
,
- .
, :
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
, .
115
Python, 0.2
__new__(cls[, ...]) .
( ).
__init__.
__init__(self[, ...]) - , .
__del__(self) - .
__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).
116
Python, 0.2
30.1. 117
Python, 0.2
.
__iadd__(self, other) - +=.
__isub__(self, other) - -=.
__imul__(self, other) - *=.
__itruediv__(self, other) - /=.
__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)
30.1. 118
Python, 0.2
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
30.1. 119
Python, 0.2
Vector2D(0, 0)
, - ,
. ,
, .
30.1. 120
31
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
...
>>> # , ,
.
121
Python, 0.2
>>> # , ,
,
>>> # :
>>> stand_alone_function_decorated = my_shiny_new_decorator(stand_alone_function)
>>> stand_alone_function_decorated()
- ,
, ?
- ,
, , , 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
122
Python, 0.2
...
>>> def sandwich(food="----"):
... print(food)
...
>>> sandwich()
----
>>> sandwich = bread(ingredients(sandwich))
>>> sandwich()
##
----
~~
<\______/>
>>> @bread
... @ingredients
... def sandwich(food="----"):
... print(food)
...
>>> sandwich()
##
----
~~
<\______/>
, .
:
>>> @ingredients
... @bread
... def sandwich(food="----"):
... print(food)
...
>>> sandwich()
##
----
<\______/>
~~
, , , -
. ,
.
31.1. 123
Python, 0.2
>>> #
>>> @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
, , ,
Python , , -
(self). ,
, ,
self.
, ,
, -
:
31.2. 124
Python, 0.2
31.2. 125
Python, 0.2
, :
>>> def decorator_maker():
... print(" ! :
.")
.
>>>
>>> #
>>> def decorated_function():
... print(" - .")
...
>>> decorated_function = new_decorator(decorated_function)
- ! : .
.
>>> # :
>>> decorated_function()
- .
, .
.
- .
:
>>> @decorator_maker()
... def decorated_function():
... print(" - .")
...
! :
.
.
- ! : .
31.3. 126
Python, 0.2
.
>>> decorated_function()
- .
.
.
- .
, , , -
, , ?
, , -
. *args **kwargs -
.
31.3. 127
Python, 0.2
, .
. , , -
, ,
. ,
.
, .
functools
functools.wraps, ( ,
, ..) -.
, functools.wraps .
31.4. 128
Python, 0.2
-
( ),
( , ).
, , :
>>> 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))
31.5. 129
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 , ...
31.5. 130
32
python- pip
pip - , -
, Python.
pip
pip python-,
pip.
Python 3.4+
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
131
Python, 0.2
pip - , , numpy:
Linux:
Windows:
, : python ,
(, ,
pip , ).
:
C:\Python34\Tools\Scripts\ PATH (
, stackoverow. - ).
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 - , , -
.
32.2. 132
33
, -
Python.
UnboundLocalError, -
?
UnboundLocalError -
, - .
:
>>> x = 10
>>> def bar():
... print(x)
>>> bar()
10
, :
>>> x = 10
>>> def foo():
... print(x)
... x += 1
UnboundLocalError:
>>> foo()
Traceback (most recent call last):
133
Python, 0.2
...
UnboundLocalError: local variable 'x' referenced before assignment
, , -
,
.
foo x, -
, . , print
, .
, :
>>> x = 10
>>> def foobar():
... global x
... print(x)
... x += 1
>>> foobar()
10
, , (
), ,
:
>>> print(x)
11
nonlocal:
Python?
Python, , , -
. - ,
, , , , -
.
, . ,
global
bar. , global -
, global .
.
(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
, .
-
?
- (-
cong cfg). import config -
. . -
, , -
. :
cong.py:
x = 0
mod.py:
import config
config.x = 1
main.py:
import config
import mod
print(config.x)
,
.
33.4.
136
?
Python, 0.2
-
?
. , :
def foo(mydict={}): # :
... compute something ...
mydict[key] = value
return mydict
, , mydict . ,
mydict 2 , , foo() , mydict
.
33.6. ? 137
Python, 0.2
, -
. . ,
. , ,
.
, (, , None),
. , , ,
.
,
. , None ,
None /. , :
def foo(mydict={}):
...
def foo(mydict=None):
if mydict is None:
mydict = {} # create a new dict for local namespace
, . , -
, -
:
#
result = ... expensive computation ...
_cache[(arg1, arg2)] = result #
return result
* ** -
;
. , -
* **:
33.7. 138
?
Python, 0.2
y x?
>>> x = []
>>> y = x
>>> y.append(10)
>>> y
[10]
>>> x
[10]
, , , y x.
:
- . y = x -
y, , x.
.
append, [] [10]. x y
, [10].
:
>>> x = 5 #
>>> y = x
>>> x = x + 1 # 5 .
>>> x
6
>>> y
5
, 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,
.
, , -
: . , +=
33.8. y x? 139
Python, 0.2
: . ,
:
class linear:
taxes = linear(0.3, 2)
class exponential(linear):
# __init__
def __call__(self, x):
return self.a * (x ** self.b)
class counter:
value = 0
33.9. ? 140
Python, 0.2
def up(self):
self.value = self.value + 1
def down(self):
self.value = self.value - 1
count = counter()
inc, dec, reset = count.up, count.down, count.set
Python?
, copy.
. copy:
newdict = olddict.copy()
:
new_l = l[:]
dir(x) .
, , . :
. 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,
.
Python.
- , , -
:
(=, += ). -
, -
.
Python ?: C?
. :
x, y = 50, 25
small = x if x < y else y
# < 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)))))
33.13. ? 142
Python, 0.2
# 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))))
#
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
-22 // 10 -3?
i % j , j.
i == (i // j) * j + (i % j)
, . ,
. , , 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!'
>>> a = array.array('u', s)
>>> print(a)
array('u', 'Hello, world')
>>> a[0] = 'y'
>>> print(a)
array('u', 'yello, world')
>>> a.tounicode()
'yello, world'
/?
.
- , . -
- .
def a():
pass
def b():
pass
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()
33.18. /? 144
Python, 0.2
S.rstrip("\r\n") , -
:
>>> lines = ("line 1 \r\n"
... "\r\n"
... "\r\n")
>>> lines.rstrip("\r\n")
'line 1 '
: http://code.activestate.com/recipes/52560/
, :
>>> 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.
33.19. ? 145
Python, 0.2
a_tuple[i] += [item] , -
?
- , - , -
- Python.
, -
, ,
+=, .
:
: 1 a_tuple[0], -
, 2, ,
, .
, :
- :
, , ,
, !
>>> a_tuple[0]
['foo', 'item']
, , , :
__iadd__, , +=, -
, __iadd__ extend
,
>>> a_list = []
>>> a_list += [1]
>>> a_list
[1]
, :
__iadd__ , , -
.
Python
Python .
( ( )
).
.
(
).
-
.
, , :
(1)
arithmetic, 3 : 2 - , -
, . +,
; --, ; * ; / ( ).
.
(2)
is_year_leap, 1 ,
True, , False .
148
Python, 0.2
(3)
square, 1 , -
3 ( ): , -
.
(4)
season, 1 ( 1 12), -
, (, , ).
(5)
a years 10% (-
10%. -
, ).
bank, a years, ,
.
(6)
is_prime, 1 0 1000, -
True, , False - .
(7)
date, 3 , . True,
, False .
XOR- (8)
XOR_cipher, 2 : , -
, , ,
XOR (^) . -
XOR_uncipher, -
.