Professional Documents
Culture Documents
Tutorial Python PDF
Tutorial Python PDF
Python
Python
: :
TasPython
2008 / & -
,
, -
-
. ,
,
,
.
, ,
-
, , ,
.
,
,
.
TasPython , -
, .
,
.
iii
iv
.
vi
1 1
1.1 . . . . . . . . . . . . . . . . . . . . . 2
1.2 . . . . . . . . . . . . . . . . . 2
1.2.1 . . . . . . . . . . . 3
1.2.2 . . . . . . 3
1.2.3 . . . . . . . . . . . . . . . . . . . . . . 4
1.2.4 . . . . . . . . . . . . . 5
1.2.5 . . . . . . . . . . . . . . . . . . . . . 5
1.2.6 . . . . . . . . . . . . . . . . . . . . 5
1.2.7 . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.8 . . . . . . . . . . . . . . 6
1.3 Python . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.1 . . . . . . . . . . . . . . . . . . . 9
1.3.2 Python 3 . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3.5 Zen of Python . . . . . . . . . . . . . . . . . . . . . . . 13
1.4 Python . . . . . . . . . . . . . . . . . . . . . . . . 14
1.4.1 . . . . . . . . . . . . . . . . . . . . . . . 14
1.4.2 Python . . . . . . . . . . 15
1.5 . . . . . . . . . . . . . . . . . . . . . . . . 18
vii
viii
2 21
2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.3 Boolean . . . . . . . . . . . . . . . . . . . . . . . . 24
2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3 29
3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.2 . . . . . . . . . . . . . . . . . . . . . 30
3.3 . . . . . . . . . . . . . . . . . . . . . . . . 31
3.4 if . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.4.1 . . . . . . . . . . . . . . . . . . 34
3.5 . . . . . . . . . . . . . . . . . . . . . . . 36
3.5.1 for . . . . . . . . . . . . . . . . . . . . . . . . 36
3.5.2 while . . . . . . . . . . . . . . . . . . . . . . . 38
3.6 break . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.7 with . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.7.1 with . . . . . . . . . . . . . . . . . . . . . . 40
3.7.2 . . . . . . . . . . . . . . . . . . . . . . . 41
4 43
4.1 . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.1.2 . . . . . . . . . . . . . . . . . . . . 44
4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.3 . . . . . . . . . . . . . . . . . 46
4.4 . . . . . . . . . . . . . . . . . . . . . . . . 47
5 49
5.1 . . . . . . . . . . . . . . . . . . . . . . . . . 50
5.2 . . . . . . . 51
5.3 (Docstrings) . . . . . . . . . . . . 52
5.4 . . . . . . . . . . . . . . . . . . . . . 54
5.4.1 . . . . . . . . . . . . . . . . . . . . . . 54
5.5 . . . . . . . . . . . . . . . . . . . . . . 55
ix
5.6 (Decorators) . . . . . . . . . . . . . . . . . . . . 56
6 59
6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 60
6.1.1 . . . . . . . . . . . . . . . . . 60
6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . 61
6.2.1 . . . . . . . . . . . . . 61
6.2.2 . . . . . . . . . . . . . . . 62
6.2.3 . . . . . . . . . . . . . . 63
6.2.4 . . . . . . . . . . . . . . . 64
6.2.5 . . . . . . . . . . . . . . . . . . . 64
6.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.3.1 . . . . . . . . . . . . . . . . . . . . . 67
6.3.2 . . . . . . . . . . . . . . . 68
6.3.3 . . . . . . . . . . . . . . . . . 70
6.3.4 . . . . . . . . . . . . . . . . . . . . 70
6.3.5 (Lists comprehensions) . . . . . . . 71
6.3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.5.1 . . . . . . . . . . . . . . . . . . . . 73
6.5.2 . . . . . . . . . . . . . . . . . . . 74
6.5.3 . . . . . . . . . . . . . . . . . . . . . . . 76
6.5.4 . . . . . . . . . . . . . . . . 76
6.5.5 (Dict comprehension) . . . . . . . 77
6.5.6 . . . . . . . . . . . . . . . . . . . 77
6.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
6.6.1 . . . . . . . . . . . . . . . . . . . . . . . . 78
6.6.2 . . . . . . . . . . . . . . . . . 79
7 81
7.1 (immutable objects) . . . . . . . . . . . . . . . . 81
7.2 . . . . . . . . . . . . . . . . 83
7.3 . . . . . . . . . . . . . . . . . . . . . . . 86
7.3.1 . . . . . . . . . . . . . . . . . . . . . . . . 87
x
7.3.2 None . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
7.4 . . . . . . . . . . . . . . . . . . . . . . . . . 88
7.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
7.6 . . . . . . . . . . . . . . . . . . . . . 94
8 99
8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
8.2 . . . . . . . . . . . . . . . . . . . . . . . . . 101
8.3 . . . . . . . . . . . . . . . . . 104
8.4 (attributes) . . . . . . . . . . . . . . 107
8.5 . . . . . . . . . . . . . . . . . . . . . . . 108
8.6 . . . . . . . . . . . . 109
8.6.1 . . . . . . . . . . . . . . . . . . . . 109
8.6.2 . . . . . . . . . . . . . . . . . . . . . 110
8.7 . . . . . . . . . . . . . . . . . . . . . . . . . 110
8.8 . . . . . . . . . . . . . . . . . . . . . . . . . 112
9 115
9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
9.2 . . . . . . . . . . . . . . . . . . . . . . . 116
9.2.1 . . . . . . . . . . . . . . . . . . . 116
9.2.2 . . . . . . . . . . . . . . . . . . . . 117
9.2.3 . . . . . . . . . . . . . . . . . . . . 117
9.2.4 () . . . . . 118
9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
9.3.1 . . . . . . . . . . . . . . . . . 119
9.3.2 . . . . . . . . . . . . . . . . . . . 122
10 123
10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
10.2 . . . . . . . . . . . . . . . . . . . . . . . . . . 124
10.3 . . . . . . . . . . . . . . . . . . . . . 128
10.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
10.4.1try:. . . else: . . . . . . . . . . . . . . . . . . . . . . . . . 129
10.4.2finally . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
xi
10.5 . . . . . . . . . . . . . . . . . . . . . 131
10.5.1 . . . . . . . . . . . . . . . . . . . 131
10.5.2 (raise) . . . . . . . . . . . . . . . 132
10.5.3 . . . . . . . . . 132
10.6 if . . . else . . . . . . . . . . . . . . . . . . . . . . 133
11 139
11.1 (Iterators) . . . . . . . . . . . . . . . . . . . . . 139
11.1.1 for . . . . . . . . . . . . . . 140
11.2 . . . . . . . . . . . . . . . . . . . . . 140
11.3 . . . . . . . . 143
11.4 . . . . . . . . 144
12 147
12.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
13 149
13.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
13.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
13.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 150
15 163
15.1 . . . . . . . . . . . . . . . . . . . . . . . . . 163
15.1.1 . . . . . . . . . . . . . . . . . . . 163
15.1.2 . . . . . . . . . . . . . . . 164
15.1.3 . . . . . . . . . . . . . . . . . . . . . 164
15.2 Python Debugger . . . . . . . . . . . . . . . . . . . . . . . . . 164
15.2.1 . . . . . . . . . . . . . . . . . . . . 165
15.2.2 . . . . . . . . . . . . . . . . . . . . . . . . 165
15.2.3 . . . . . . . . . . . . . . . . . 166
15.2.4 . . . . . . . . . . . . . . . . . . . . 166
xii
16 169
16.1 . . . . . . . . . . . . . 170
16.2 . . . . . . . . . . . . 171
16.3 garbage collector . . . . . . . . . . . . . . . . . 173
16.4 . . . . . . . . . . . . . . . 173
16.5 . . . . . . . . . . . . . . . . . . . . 175
16.6 (Profiling) . . . . . . . . . . . . . . . . . . 175
1
Eric Hoffer
Python 3. -
. -
.
, -
. :
,
.
, .
, -
.
1
2 1.
1.1
-
, , -
. -
.
, -
.
.
,
,
.
1. .
2. .
3. _..
4. , _..
,
. ,
, -
.
1.2
Python
.
Linux
web applications (
Django). ,
1.2. 3
,
.
.
1.2.1
,
.
. -
, (compile)1
, ,
.
,
,
,
.
-
.
. .
1.2.2
, , -
, . -
, -
.
, -
.
,
, -
1
4 1.
. ,
( ),
,
.
, ,
.
,
. ,
,
.
1.2.3
,
. !,
.
, .
,
. ,
. ,
.
. ,
!
, ,
. , -
,
. ,
!
, !
1.2. 5
1.2.4
. -
, -
.
.
. -
-
.
1.2.5
, -
, . .
. -
.
, Python -
.
. , ,
.
.
1.2.6
.
.
,
.
,
.
6 1.
1.2.7
(compiler) -
. .
.
,
.
,
.
, -
. ,
. , -
,
.
1.2.8
.
-
. , ,
. Python
. -
,
. -
(bugs),
.
1.3 Python
Python ,
(semantics).
(standard library).
:
1.3. Python 7
( , )
segmentation faults
-
Python .
, -
.
.
, -
. ,
- ,
.
Python
-
( C, C++)
8 1.
Python 3 5 Ja-
va. ,
.
( -
) .
-
.
(efficiency),
(productivity).
-
, . (interpreters)
(compilers).
-
.
-
(virtual machine) (
Python). ,
, (bytecode).
-
(object code).
.
,
. -
, -
.
, (modules)
,
,
( 3 Python
1.3. Python 9
).
, -
( Windows, Linux/U-
nix, OS/2, Mac, Amiga). -
, Java, Jython -
Java, .NET
IronPython Microsoft. , -
C/C++ (modules)
Python.
, . -
1980
. ,
.
, ,
Python segmentation faults. ,
Python (
throw)
.
-
. , Python -
.
(reference counting).
1.3.1
Python, . ,
(generators), , .
,
,
( , ..).
10 1.
, , , , ( -
)
. -
Python
, -
.
, ,
, ,
. ,
-
-
.
(Python Enhancement Proposal (PEP))
(
PEP 8 PEP 257)
1.3.2 Python 3
Python ,
1980.
,
(
2 import this)
. :
7 / 4 = 1 C.
range ( )
2
Linux python3
, Windows IDLE.
1.3. Python 11
print statement
.
Unicode ( ) .
... .
,
. Python -
3 ( py3k 3000).
,
-
.
:
7 / 4 = 1.75 ( // -
)
. -
range
3
.
Unicode, -
.
...
Python.
3
11.2.
12 1.
1.3.3
2
:
2to3
3to2
python -3
2
3 , . -
Python (2.6+)
3 Python.
-
, PEP 3003 (Python Enhancement Proposal) -
2
Python (CPython)
( Jython, Pypy, IronPython)
.
1.3.4
Python,
:
NASA
Yahoo!
(MIT, Stanford ).
linux.
... !
1.3. Python 13
-
Python, :
1. (prototyping)
2.
3. Scripting
4.
5.
6.
7. ... !
,
. -
Python
.
import t h i s
.
.
.
.
.
.
.
-
.
14 1.
.
.
.
, .
.
.
.
.
, .
, .
(namespaces)
!
1.4 Python
1.4.1
Python
. ,
(
). .
Linux
,
. , ,
( IDLE).
Mac, Python . , -
, -
.
. , -
Applications / Utilities / Terminal Python.
, , 3 .
1.4.2 Python
Python .py.
-
.
.py .
:
>>> a = 5
>>> b = 6
>>> a + b
11
(interpre-
ter), (
Linux, > > cmd Windows) python ( python3 -
).
>>> ,
.
16 1.
Windows
-
python.
1. Python PATH. ,
-> -> ->
(Control Panel -> System -> Advanced ->
Environment Variables) (path) -
Python. -
(command line) python o-
noma.py.
2. IDLE ( py-
thon ).
(File > Open). , Run Module
> Run .
Notepad Wordpad. , Note-
pad++ .
Linux
1. path
. python3 onoma.py
4 .
2. ,
#! / usr/bin/env python3
4
python 3 python3
/usr/bin
1.4. Python 17
#!/ usr/bin/python3
-
. #/usr/bin/env python3
Python 3
( /usr/bin/python3) -
. ,
. , ,
.
PEP5 8 -
Python, tab ,
(indent) .6
"Unknown option: -",
-
. Unix .
-
.
1. Notepad++
Tabs: Settings > Preferences > Edit Components > Tab settings.
Settings > Preferences > MISC > auto-indent.
: Format > Convert, Unix.
2. JEdit
: U W M , -
U
5
PEP: Python Enhancement Proposal. -
, ,
..
6
PEPs
http://python.org/dev/peps/.
18 1.
3. Mac TextWrangler
Tabs:
Auto Expand Tabs. -
Defaults > Auto-Expand Tabs Defaults >
Auto-indent.
: , -
Unix.
-
. Windows, IDLE (
) , Eclipse
pydev. Linux kate gedit,
Eclipse.
( ).
,
.
1.5
:
1
Python.
2 -
.
,
.
3 , -
.
4 -
.
5
-
.
1.5. 19
6 :
.
7 Python -
.
8 -
: .
.
9
. ,
.
10
.
11
Python, .
13
.
14
(tkinter)
Python.
15 -
.
, 16
( -
).
20 1.
2
, , ,
: .
. ,
.
-
. -
,
, . ,
-
. ,
Structure and Interpretation of Computer Programs :
1. , -
.
21
22 2.
2. -
.
3. -
.
-
.
2.1
, -
. , Python .
2.1.1. bit -
. bits
-
.
2.1.2.
.
.
print . -
,
. ,
. , ,
, .
print ( 1 )
p r i n t ( ' asdf ' )
primeNumbers = 1 , 2 , 3 , 5 , 7
p r i n t ( primeNumbers )
Python .
,
2.2. 23
, .
dynamic typing. ,
Python
.
. :
a -
.
2.1.3. (dynamically
typed),
.
,
. , -
Python
.
2.2
2.2.1. -
.
. , .
num = 17
pi = 3.14
paei = ' Allou '
paei = ' Molis g y r i s e '
24 2.
-
. , ,
. , -
. , ,
.
, -
. -
pi
3.14 .
pi = 3.14
p r i n t ( pi 2)
2.3 Boolean
2.3.1. Boolean
.
5 == 5 ()
5 == 6 ()
True or False ()
Boolean -
. -
.
Boolean :
not
or
and
2.3. Boolean 25
2.1: not
a b
2.2: and
a b
2.3: or
(
and), (-
or) ( not
and)1 . .
1
De Morgan
.
26 2.
>>> a = 5
>>> b = 4
>>> a > b
True
>>> c = 6
>>> a > b and a > c
False
>>> a > b or a > c
True
>>> a > b and not a > c
True
>>> a > b or not a > c
True
>>> not a > b or not a > c
True
>>> not ( a > b ) or a > c
False
>>> not a > b or a > c
False
2.4
Boolean (
) -
.
2.4.1. -
.
.
,
5.
:
2.4. 27
(+)
()
()
(/)
()
(modulo) (%)
. -
. Python
.
(==)
(! =)
(>)
(<)
(>=)
(<=)
28 2.
3
W. Edwards Deming
3.1
.
.
3.1.1. -
( ).
-
.
:
: -
.
:
( , , ).
: .
29
30 3.
! Python !
:
.
tabs
.
tabs .
, PEP
8 .
. ,
.
,
. , Python
.
3.2
3.2.1.
, .
, -
,
. -
-
.
. -
.
sequential, .
:
p r i n t (123)
3.3. 31
print ( )
print ( ' Hello ' , end= ' ' )
print ( ' World ' )
print() , -
, .
end
.
, -
(program counter).
.
3.3
3.3.1. :
-
.
(, ).
,
.
32 3.
3.4 if
-
, if
.
, -
if ,
if.
i f ( answer == 1 0 ) :
p r i n t ( ' Correct ! ' )
, -
.
:
g
int(), ,
ValueError.
.
.
-
,
if...else....
i f a == 0:
print ( " This i s not a 2nd degree equation " )
import sys
exit ( )
D = b2 4 a c
i f D >= 0:
x1 = (b + sqrt (D ) ) / (2 a )
x2 = (b sqrt (D ) ) / (2 a )
else :
x1 = complex(b / (2 a ) , sqrt (D) / 2 a )
x2 = complex(b / (2 a ) , sqrt (D) / 2 a )
s f = " x1 = { 0 } , x2 = { 1 } "
print ( s f . format ( x1 , x2 ) )
-
.
-
.
+
: x1,2 = , = 2 4 . -
2
(
if 1 ( else).
1
0 ,
.
34 3.
3.4.1
if...elif...else...
Python, switch -
k , k
switch.
switch C/C++ Java. Py-
thon, if...elif...else....
:
, elif
, .
switch,
.
Python
.
(key)
. -
3.4. if 35
,
, .
# Sample functions
def square ( x ) :
return x 2
def double ( x ) :
return x 2
opdict = { " a " : square , " b " : square , " c " : double }
if...elif...else....
, ,
.
, ,
.
# Sample functions
def square ( x ) :
return x 2
def double ( x ) :
return x 2
def decrease ( x ) :
return x1
36 3.
opdict = { " a " : square , " b " : double , " c " : decrease }
try :
p r i n t ( opdict [ " d " ] ( 5 ) )
except KeyError :
p r i n t ( ' I n v a l i d use o f index ' )
3.5
,
.
( )
, . ,
for while .
3.5.1 for
for . -
range(). ,
range() , -
.
20 Fibo-
nacci. n-
Fibonacci Fn = Fn1 + Fn2 F0 = 0 F1 = 1.
i 0 17,
18 . 2
range() .
range() ,
.
[100, 120) -
[100, 120) 2,
.
.
2
, .
38 3.
3.5.2 while
for, while
.
def f i b ( a , b ) :
sum = 0;
while a < 4 (10 6 ) :
sum += a
a, b = b, a + b
return sum
a, b = 0, 1
print ( f i b ( a , b ) )
Fibonnaci 4 106 .
3.6 break
break -
.
, if
.
break
.
. ,
.
-
Zn (modulo).
0,
.
def printSubgroups ( n ) :
"""
Prints a l l the subgroups o f Zn
3.7. with 39
"""
for i in range ( 0 , n ) :
p r i n t ( ' < ' , end= ' ' )
p r i n t ( i , end= ' >: ' )
for j in range ( 1 , n + 1 ) :
num = ( i j )%n
p r i n t (num, end = ' ' )
i f (num % n ) == 0:
break
p r i n t ( ' , ' , end= ' ' )
print ( )
3.7 with
3 Python, with ,
.
.
with , with
.
, block with. with
.
, with, filename,
.
,
. , with
.
3.7.1 with
with
, with -
.
. -
,
.
with open ( ' i n f i l e ' , ' r ' ) as f1 , open ( ' o u t f i l e ' , 'w ' ) as f2 :
# f o r each l i n e in the input f i l e
for l i n e in f1 . readlines ( ) :
# by d e f a u l t write a l i n e to the o u t f i l e unless
# i t doesn ' t contain one o f the excluded words
w r i t e _ t o _ f i l e = True
# f o r each word in a l i n e o f the input f i l e
for word in l i n e . s p l i t ( ) :
# i f t h i s word doesn ' t belong to closed_class
i f word . r s t r i p ( ) in exclude_class :
w r i t e _ t o _ f i l e = False
break
if write_to_file :
3.7. with 41
f2 . write ( l i n e )
3.7.2
__en-
ter__ __exit__, with
__enter__ , -
,
__exit__.
.
with __exit__,
( ,
).
with, -
__exit__, .
.
42 3.
4
Betty Hill)
Python -
. -
:
(scripts). scripts.
.
Python , -
,
. , -
. -
(overflow). -
.
python
,
:
43
44 4.
python
. -
, ctrl+d Linux/BSD ctrl+z Windows.
4.1
(, , , ) -
(+, , , /)
>>> 3+8
11
>>> 38
5
>>> 38
24
>>> 3/8
0.375
4.1.1
.
( )
.
>>> 7/2
3.5
>>> 7//2
3
4.1.2
,
.
4.2. 45
>>> 210
1024
>>> 38
6561
-
n (mod n ),
python (modular exponentiation)
, .
,
.
,
21024 , 1024
1000 . Python
.
4.2
,
:
1. d:
2. b: ( bin())
3. o: ( oct())
4. x: ( hex())
, -
.
46 4.
4.3
,
(specifier) f .
. , +,
.
.
4.4
(, -
, ). -
complex. ,
.
a = complex ( 1 , 1)
b = complex ( 1 , 2)
print ( a+b )
print ( a b )
48 4.
5
, (
)
.
.
, ,
-
. -
,
. -
, -
. ,
.
Python -
.
, ,
. ,
, -
. ,
49
50 5.
,
, .
5.1
5.1.1. -
.
.
, .
5.1.2.
.
.
5.1.3.
return.
return,
.
. ,
.
def add ( a , b ) :
c = a + b
return c
p r i n t ( add ( 2 , 3 ) )
.
5.2. 51
def fun2 ( c ) :
a = c // 2
b = c a
return a , b
d , e = fun2 ( 7 )
print ( d , e )
1. , .
def .
2. (:). -
,
.
3.
() ( ).
-
.
5.2 -
(Pure Functions)
. ,
(modifier functions) -
. -
(side effects),
,
.
52 5.
, upper()
. ,
string
a.
, (mutable),
, . ,
, count() b, reverse()
.
5.3 (Docstrings)
, .
,
.
Python, , -
.
def f i b o n a c c i ( n ) :
" " " Return the nth Fibonacci number counting from 0. " " "
i f n <= 1:
return n
return f i b o n a c c i ( n 1) + f i b o n a c c i ( n 2)
print ( f i b o n a c c i ( 1 0 ) )
,
-
.
. -
. ,
, ()
. -
PEP 257,
,
-
.
, .
-
Python.
.
,
__doc__
Python.
, Python
.
54 5.
5.4
.
-
.
,
.
hello ( )
h e l l o ( message= ' Hello Brave New World ! ' )
5.4.1
. -
.
.
, tuple -
.
>>> a = ( 1 , 2 , 3 , 4)
>>> def add ( a , b , c , d ) :
... return a + b + c + d
...
>>> add ( a )
10
-
.
, .
,
( )
5.5. 55
.
.
def p r i n t _ v a r i a b l e s ( a , b , c , d ) :
prin t ( ' a : { } ' . format ( a ) )
prin t ( ' b : { } ' . format ( b ) )
prin t ( ' c : { } ' . format ( c ) )
prin t ( ' d : { } ' . format ( d ) )
p r i n t _ v a r i a b l e s ( b )
varargs
default arguments ( ) Python.
5.5
-
. -
-
. , .
.
lambda
.
. , lambda -
def. -
1 . ,
,
return. -
.
def double ( x ) :
return x x
1
.
56 5.
def p r i n t _ r e s u l t s ( f , args ) :
p r i n t ( f ( args ) )
p r i n t _ r e s u l t s ( double , 5) # prints 25
p r i n t _ r e s u l t s ( lambda x : x x , 5) # prints 25
5.6 (Decorators)
-
. -
,
-
(randomized algorithm).
Python
. , -
.
. , -
, .
, -
. ,
.
Python
-
. , -
.
,
(decorators).
def makebold ( fn ) :
def wrapped ( ) :
return " <b> " + fn ( ) + " </b> "
5.6. (Decorators) 57
return wrapped
def message ( ) :
return " TasPython Guide "
g -
f . g f .
, makebold() -
wrapped().
wrapped() . -
. ,
f n wrapped()
. wrapped()
,
makebold().
message make-
bold(message). , Python .
, makebold(message)
message. message
-
, , .
makebold(), -
wrapped(). wrapped() makebold()
string fn . -
.
,
.
, -
.
def makebold ( fn ) :
def wrapped ( ) :
58 5.
@makebold
def message ( ) :
return " Python Guide "
p r i n t ( message ( ) )
, ,
message()
-
,
. , message(),
makebold.
6
Pablo Picasso
.
.
-
. , ,
-
,
Python . ,
.
59
60 6.
6.1
6.1.1
(Strings): (quotes). -
immutable
.
(Tuples): ,
. .
(Lists): [ ].
. -
(mutable).
(Dictionaries): { }
. ( )
:
key: .
value: ,
.
{ 1 : ' alpha ' , 2: ' beta ' , 3: 'gamma ' , 4: ' d e l t a ' }
(Sets): ,
set .
.
6.2. 61
( (union), (in-
tersection), (difference), (issuperset), -
(issubset)) (add), (remove) .
6.1
.
(string)
.
(tuple) .
.
(list) .
keys.
(dictionary)
.
6.1:
6.2
6.2.1
, ,
.
,
.
UTF-8.
(sequence).
,
.
62 6.
() (index).
6.2.2
,
-
. ,
.
def reverse ( t e x t ) :
return t e x t [ : : 1 ]
6.2. 63
i n v e r t = reverse ( sentence )
,
.
:
def r e v e r s e p a r t i a l l y ( t e x t ) :
return t e x t [3:1: 1]
i n v e r t = r e v e r s e p a r t i a l l y ( sentence )
3,
2, -
. Python,
, 0.
6.2.3
string.format(). python, strings -
.
,
{x}, x
.
6.2.4
repr() ,
-
.
rjust() string, -
, .
for x in range ( 1 , 1 1 ) :
p r i n t ( repr ( x ) . r j u s t ( 2 ) , repr ( x x ) . r j u s t ( 3 ) , \
repr ( x x x ) . r j u s t ( 4 ) )
, ,
, -
format().
for x in range ( 1 , 1 1 ) :
p r i n t ( ' { 0 : 2 d } { 1 : 3 d } { 2 : 4 d } ' . format ( x , x x , x x x ) )
split().
split()
.
,
, .
6.2.5
,
6.2. 65
# t r y to open the f i l e
try :
filename = ' random_file '
t e x t f = open ( filename , ' r ' )
except IOError :
print ( ' Cannot open f i l e { 1 } f o r reading ' , filename )
# import sys only i f needed
import sys
# e x i t the program
sys . e x i t ( 0 )
# i f i t i s an empty l i n e
i f l i n e . startswith ( ' \n ' ) :
blanklines += 1
else :
# assume that each sentence ends with . or ! or ?
# so simply count these characters
sentences += l i n e . count ( ' . ' ) + l i n e . count ( ' ! ' ) + \
l i n e . count ( ' ? ' )
# create a l i s t o f words
# use None to s p l i t at any whitespace regardless o f length
66 6.
# word t o t a l count
words += len ( tempwords )
# close t e x t f i l e
t e x t f . close ( )
6.3
6.3.1.
.
.
.
,
. Python
. -
. .
,
.
,
. , ,
, .
6.3.1
.
list1 = [ ]
,
. list() ,
.
,
.
a = [1 ,2 ,3 ,4]
b = list (a)
c = [a]
print ( b )
print ( c )
list() . list()
, Python
.
a = [1 ,2 ,3 ,4]
68 6.
b = list (a)
c = a
print ( b )
print ( c )
6.3.2
, -
, ,
. -
.
,
list1[j] list1[j 1].
, n ,
list1[n] list1[n 1]
.
n = len ( l i s t 1 )
list1 [0]
6.3. 69
[i, j):
list1 [ i : j ]
,
.
10
( -
) ,
:
a = [ x for x in range ( 1 0 ) ]
# or a = l i s t ( range ( 1 0 ) )
print ( a [ 2 : 8 : 2 ] )
[i, j) k
list1 [ i : j :k]
list1 [ : : k]
k ,
,
(
).
def reverse ( l i s ) :
return l i s [ : : 1 ]
70 6.
6.3.3
-
for.
a = [ 1 , 1 , 2 , 3 , 5 , 8]
for i in a :
print ( i )
, -
,
.
a = [ 1 , 1 , 2 , 3 , 5 , 8]
b = iter (a)
p r i n t ( next ( b ) )
p r i n t ( next ( b ) )
p r i n t ( next ( b ) )
6.3.4
,
del
.
.
a = [ 0 , 1 , 2 , 3 , 4 , 5]
del a [ 2 : 4 ]
print ( a )
6.3. 71
primes = [ 1 , 2 , 3 , 5 , 7]
list comprehension
. .
:
r e s u l t = [ transform i t e r a t i o n f i l t e r ]
(transform)
1 (iteration) -
(filter), .
.
-
. ,
for, -
.
. , ,
, -
sum(). , 100
3 7.
1
-
.
72 6.
6.3.6
,
. .
6.3.2. . :
pop
6.4
6.4.1. . -
.
.
,
. , ,
.
, -
.
,
.
6.5
(dictionary)
. 2 ,
,
,
( ) .
6.5.1
d = {
' milk ' : 3.67 ,
' butter ' : 1.95 ,
' bread ' : 1.67 ,
' cheese ' : 4.67
}
.
.
d = {}
d [ ' key ' ] = value
di-
ct().
2
hash
.
74 6.
6.5.2
: del. del d[milk]
.
: (
/) len(d).
: ( )
d.keys().
: , d.values().
/ : /
d.items()
,
.
, -
.
,
,
, -
.
.
.
i f key not in d :
d [ key ] = 0
d [ key ] += value
# testing
d = {}
increaseValue2 ( d , ' d i m i t r i s ' , 5)
print ( d )
.
, (
).
(value).
. get .
d[key]
.
value
d[key] .
76 6.
6.5.3
.
,
.
d = {
' milk ' : 3.67 ,
' butter ' : 1.95 ,
' bread ' : 1.67 ,
' cheese ' : 4.67
}
for food in d :
p r i n t ( ' { } costs { } ' . format ( food , d [ food ] ) )
items() ,
.
6.5.4
(mutable).
.
, copy().
:
6.5. 77
d = {}
d [ ' a ' ] = 123
c = d . copy ( )
c [ ' a ' ] = 1821
print ( d [ ' a ' ] )
,
Python.
. , -
.
6.5.6
,
/ . , -
.
-
.
. -
. ,
78 6.
, .
(
),
.
d = OrderedDict ( )
d [ ' python ' ] = ' TasPython '
d [ ' guide ' ] = ' Greek '
p r i n t ( d . items ( ) )
6.6
, ,
, .
.
6.6.1
.
Python ,
.
s = { 'a ' , 'a ' , 'b ' , ' c ' , 'a ' }
print ( s )
(iterable).
6.6. 79
6.6.2
, :
:
80 6.
a = [ ' apple ' , ' bread ' , ' carrot ' , ' carrot ' ]
set1 = set ( a )
p r i n t ( set1 )
p r i n t ( ' apple ' in set1 )
set2 = set1 . copy ( )
set2 . add ( ' d e l i c i o u s ' )
p r i n t ( set1 < set1 )
set1 . remove ( ' bread ' )
# prints { ' carrot ' , ' apple ' }
p r i n t ( set1 & set2 )
# prints { ' carrot ' , ' apple ' , ' d e l i c i o u s ' , ' bread ' }
p r i n t ( set1 | set2 )
7
,
.
Python . -
,
Python.
bool
int
81
82 7.
float
string
-
, .
id() 1
. is
True .
>>> a = 5
>>> b = 5
>>> c = 5.0
>>> d = ' 5 '
>>> id ( a )
137061184
>>> id ( d )
3073418688
>>> a i s b
True
>>> c i s d
False
, -
, a
is b .
.
-
,
-
.
1
,
, , .
7.2. 83
>>> a = 4
>>> b = 4
>>> a i s b
True
>>> a += 1
>>> a
5
>>> b
4
7.2
, , .
7.1. .
7.2. (sco-
pe).
. , -
, ,
.
7.3. (scope)
. (scope).
Python, -
. ,
(
) .
.
g = " I am a g l o b a l v a r i a b l e "
a = " I am a l o c a l v a r i a b l e "
print ( g )
# g += ' modified ' # produces an e r r o r
p r i n t ( arg )
#p r i n t ( a ) # produces an e r r o r
, , g -
.
function1 . , -
a ,
. -
a function1
.
.
, Python
.
global.
g = " I am a g l o b a l v a r i a b l e "
-
7.2. 85
global,
.
g = " I am a g l o b a l v a r i a b l e "
print ( g )
,
. ,
nonlocal global
. ,
.
def function1 ( ) :
a = " Scope1 v a r i a b l e "
def function2 ( ) :
nonlocal a
a += " modified "
print ( a )
function2 ( )
function1 ( )
nonlocal
.
86 7.
7.3
Python
(container types). :
(tuple)
(string)
(list)
(set)
(dictionary)
.
.
(alias) , .
is -
==.
2 ==
.
2
,
.
7.3. 87
>>> a = [ 1 , 2 , 3]
>>> b = [ 1 , 2 , 3]
>>> a i s b
False
>>> a == b
True
7.3.1
(alias) -
, -
. , , ,
,
.
a = [ 1 , 2 , 3]
b = a
a . append ( 4 )
print ( b )
4 -
a, b, b
a .
7.3.2 None
None -
. Null.
Null Python
None.
def helloWorld ( ) :
prin t ( ' Hello World ' )
88 7.
p r i n t ( helloWorld ( ) == None )
None
. None
,
.
: None.
,
. ,
, None
.
p = [ 1 , 2 , 3 , 4]
print ( p )
# i l l e g a l statement because the returned value i s None
#p = p . pop ( )
p . pop ( )
print ( p )
7.4
-
(
) .
.
Python, , -
. ,
:
from f i l e import
python.py .
,
, -
7.4. 89
.
. ,
( )
.
7.4.1. (module) -
(, ). -
.py.
(
)
, -
( ). (
python file.py) import
. Python ,
"__name__" "__main__".
"__name__"
.
.
90 7.
-
namespace :
List1 = [ 1 , 2 , 3]
List2 = [ 1 , 2 , 3]
List2 [ 2 ] = "new"
List1 = { " a " : [ 1 ] , " b " : [ 2 ] }
1 2 3
Namespace
7.1: (namespace) .
7.5
.
>>> def f ( a ) :
... a = 5
...
>>> a = 4
>>> f ( a )
>>> a
4
7.5. 91
1 2 3
bList
Namespace
7.2:
.
1 2 "new"
bList
Namespace
7.3: .
a [0] 1
aDict
b [0] 2
Namespace
7.4: .
92 7.
a f
, . ,
a = 5 .
,
.
, L -
. , x
L. ,
x .
. , , L
, .
, , -
.
,
x . , L
foo()
.
def foo ( x ) :
p r i n t ( ' point 2: ' , end= ' ' )
p r i n t ( id ( x ) )
x = [ 1 , 2 , 3]
p r i n t ( ' point 3: ' , end= ' ' )
p r i n t ( id ( x ) )
print ( x )
L = [ 3 , 2 , 1]
p r i n t ( ' point 1: ' , end= ' ' )
p r i n t ( id ( L ) )
foo ( L )
p r i n t ( ' point 4: ' , end= ' ' )
p r i n t ( id ( L ) )
7.5. 93
print ( L )
, L .
L -
,
.
foo() , -
L, python
L error
.
Python
.
def foo ( ) :
print ( ' point 2: ' , end= ' ' )
# Error . L i s not declared in t h i s scope
print ( id ( L ) )
L = [ 1 , 2 , 3]
print ( ' point 3: ' , end= ' ' )
print ( id ( L ) )
print ( L )
L = [ 3 , 2 , 1]
print ( ' point 1: ' , end= ' ' )
print ( id ( L ) )
foo ( )
print ( ' point 4: ' , end= ' ' )
print ( id ( L ) )
print ( L )
94 7.
:
.
, , -
-
, ,
, -
, .
def foo ( x ) :
p r i n t ( ' point 2: ' , end= ' ' )
p r i n t ( id ( L ) )
x . append ( 0 )
p r i n t ( ' point 3: ' , end= ' ' )
p r i n t ( id ( x ) )
print ( x )
L = [ 3 , 2 , 1]
p r i n t ( ' point 1: ' , end= ' ' )
p r i n t ( id ( L ) )
foo ( L )
p r i n t ( ' point 4: ' , end= ' ' )
p r i n t ( id ( L ) )
print ( L )
7.6
,
-
.
, deepcopy.
Python -
.
7.6. 95
"""
for c in sequence :
d = d[ c ]
i f p o s i t i o n i s not None :
d = d [ position ]
96 7.
return d
>>> t r i e = { }
>>> p o p u l a t e _ t r i e ( t r i e , ' python ' )
{ 'p ': { ' y ': { ' t ': { 'h ': { ' o ': { 'n ': {}}}}}}}
>>> t r i e = { }
>>> p o p u l a t e _ t r i e ( t r i e , ' kalo ' , 1)
{ 'k ': [1 , { ' a ': [1 , { ' l ': [1 , { ' o ': [1 , { } ] } ] } ] } ] }
>>> t r i e = { }
>>> p o p u l a t e _ t r i e ( t r i e , ' heh ' , 2)
{ 'h ': [1 , 0, { ' e ': [1 , 0, { 'h ': [1 , 0, { } ] } ] } ] }
>>> t r i e = { }
>>> t r i e = p o p u la t e _ t r i e ( t r i e , ' heh ' , 1)
>>> p o p u l a t e _ t r i e ( t r i e , ' ha ' , 1)
{ 'h ': [2 , { ' a ': [1 , { } ] , 'e ': [1 , { 'h ': [1 , { } ] } ] } ] }
"""
d2 = t r i e
for i , character in enumerate ( sequence ) :
d2 = a c c e s s _ t r i e ( t r i e , sequence [ : i ] , p o s i t i o n )
i f character not in d2 :
i f p o s i t i o n i s None :
d2 [ character ] = deepcopy ( embedded_obj )
else :
d2 [ character ] = d2 . get ( character ,\
deepcopy ( embedded_obj ) )
d2 [ character ] [ 0 ] += 1
e l i f p o s i t i o n i s not None :
d2 [ character ] [ 0 ] += 1
return t r i e
access_trie() -
-
. ,
position None, if
,
.
sequence
. ,
.
.
d (hides)
. ,
d
.
.
populate_trie -
, -
98 7.
deepcopy.
.
.
embedded_obj ,
.
embedded_obj
embedded_obj. .
, (
) .
:
>>> L = l i s t ( range ( 5 ) )
>>> L . append ( L )
>>> L
[0 , 1, 2, 3, 4, [ . . . ] ]
, 8.8,
8.3.
8
Ludwig Wittgenstein
, -
Python.
8.1
Ludwig Wittgenstein ,
-
:
. (-
)
. ( )
. ()
99
100 8.
, -
, -
, -
. (
)
. ( )
.
( )
,
. ( )
.
, ,
. -
,
-
. ( )
,
.
-
.
-
.
, .
:
: : Python
8.2. 101
(Class): (attributes)
(methods) -
. .
(Object): ,
.
.
(Instance): -
.
(Method): -
.
(Inheritance): -
,
,
. -
.
. (fields)
((methods). -
.
.
8.2
:
102 8.
class Snake ( ) :
pass
python = Snake ( )
class Snake ( ) :
def helloWorld ( s e l f ) :
p r i n t ( ' Hello World ! ' )
python = Snake ( )
python . helloWorld ( )
, , -
def. ,
self .
self,
.
, -
. -
.
(
)
.
, , . -
( , ),
. ,
, .
, . , -
8.2. 103
, , ,
.
class Dog ( ) :
def _ _ i n i t _ _ ( s e l f , name, color , height , mood, age ) :
"""
This method i s c a l l e d when an new objected i s
initiallized .
"""
def p r i n t _ a t t r i b u t e s ( s e l f ) :
" " " P r i n t a l l the a t t r i b u t e s o f the dog " " "
ralph = Dog ( ' Ralph ' , ' blue ' , 1.80 , ' good ' , 15)
ralph . p r i n t _ a t t r i b u t e s ( )
,
Dog() -
104 8.
. -
__init__().
. __init__()
self -
,
. -
.
8.2.1. -
, self this
. self
. , self
, . -
, ,
.
8.3
.
-
Trie
.
class T r i e :
"""
A T r i e i s l i k e a d i c t i o n a r y in that i t maps keys to values .
However , because o f the way keys are stored , i t allows
look up based on the longest p r e f i x that matches .
"""
def _ _ i n i t _ _ ( s e l f ) :
# Every node consists o f a l i s t with two p o s i t i o n . In
# the f i r s t one , there i s the value while on the second
8.3. 105
def i n s e r t ( s e l f , key ) :
"""
Add the given value f o r the given key .
>>> a = T r i e ( )
>>> a . i n s e r t ( ' kalo ' )
>>> p r i n t ( a )
[0 , { 'k ': [1 , { ' a ': [1 , { ' l ': [1 , { ' o ': [1 , { } ] } ] } ] } ] } ]
>>> a . i n s e r t ( ' kalo ' )
>>> p r i n t ( a )
[0 , { 'k ': [2 , { ' a ': [2 , { ' l ': [2 , { ' o ': [2 , { } ] } ] } ] } ] } ]
>>> b = T r i e ( )
>>> b . i n s e r t ( ' heh ' )
>>> b . i n s e r t ( ' ha ' )
>>> p r i n t ( b )
[0 , { 'h ': [2 , { ' a ': [1 , { } ] , 'e ': [1 , { 'h ': [1 , { } ] } ] } ] } ]
"""
def f i n d ( s e l f , key ) :
"""
Return the value f o r the given key or None i f key not
found .
106 8.
>>> a = T r i e ( )
>>> a . i n s e r t ( ' ha ' )
>>> a . i n s e r t ( ' ha ' )
>>> a . i n s e r t ( ' he ' )
>>> a . i n s e r t ( ' ho ' )
>>> p r i n t ( a . f i n d ( ' h ' ) )
4
>>> p r i n t ( a . f i n d ( ' ha ' ) )
2
>>> p r i n t ( a . f i n d ( ' he ' ) )
1
"""
curr_node = s e l f . root
for k in key :
try :
curr_node = curr_node [ 1 ] [ k ]
except KeyError :
return 0
return curr_node [ 0 ]
def _ _ s t r _ _ ( s e l f ) :
return s t r ( s e l f . root )
yield k , curr_node [ 1 ] [ k ] [ 0 ]
8.4 (attributes)
-
( ) (attributes) .
ralph (instance)
Dog,
name, ralph.name.
self .
() -
.
self.characteristic = .
, print_attributes(). -
self
.
.
108 8.
8.5
(member functions)
-
.
, , ,
(Member Functions). -
,
.
.
.
Python :
, -
dir Python
.
b = ( 1 , 2 , 3)
p r i n t ( ' Member functions f o r tuple ' )
print ( dir ( b ) )
c = [ 1 , 2 , 3]
p r i n t ( ' Member functions f o r l i s t ' )
print ( dir ( c ) )
__functionname__
Python
.
, -
8.6. 109
Python.
c = [ 1 , 2 , 3]
print ( help ( c . s o r t ) )
8.6
8.6.1
8.6.1.
( ).
.
class Snake :
noOfSnakes = 0
def helloWorld ( s e l f ) :
prin t ( ' Hello World from { 0 } ! ' . format ( s e l f .name ) )
@staticmethod
def numberOfSnakes ( ) :
prin t ( Snake . noOfSnakes )
. , -
(__init__,
noOfSnakes.
8.6.2
8.6.2. ,
. ,
( self).
,
(decorator) @staticmethod
. , ,
,
,
.
8.7
A b1 B . , -
B A, -
b1 1 . -
B 2 .
: -
(part-of) (has-a) - (is-a).
Python
.
1
fun
B a1.b1.fun(), a1 A.
2
a1.fun()
8.7. 111
8.7.1. -
. -
. (-
) -
().
class UniversityMember :
def _ _ i n i t _ _ ( s e l f , name, age ) :
s e l f .name = name
s e l f . age = age
def who ( s e l f ) :
p r i n t ( 'Name : " { } " Age : " { } " ' . format ( s e l f .name, s e l f . age ) )
def who ( s e l f ) :
UniversityMember .who ( s e l f )
p r i n t ( ' Salary : " { } " ' . format ( s e l f . salary ) )
def who ( s e l f ) :
UniversityMember .who ( s e l f )
p r i n t ( ' Marks : " { } " ' . format ( s e l f . marks ) )
112 8.
for member in ( p , s ) :
p r i n t ( '' )
member.who ( )
, Professor
UniversityMember.
, Professor
(UniversityMember). ,
Professor
.
-
-
. ,
, , -
DRY Dont Repeat Yourself
,
( -
).
8.8
,
( , ,
..).
__. .
,
8.8. 113
__init__(self, . . . ): . -
. (base class) __init__(),
.
, __init__()
__del__(self): .
(destructor). ,
.
__repr__(self): repr() -
-
. ,
Python .
debugging.
__str__(self): str()
print().
__repr__() .
.
, -
, .
__sub__(self, other): ()
114 8.
__mul__(self, other): ()
,
(descriptors)
.
__, ,
.
:
class EmbeddedDict ( d i c t ) :
def __missing__ ( s e l f , key ) :
value = EmbeddedDict ( )
s e l f [ key ] = value
return value
d = {}
d2 = EmbeddedDict ( d )
d2 [ ' a ' ] [ ' b ' ] [ ' c ' ] = 1
p r i n t ( d2 )
, .
9
. -
,
.
9.1
, ,
. ,
open() . ,
,
. , -
, .
115
116 9.
open()
9.1.
r
w
( )
a
( )
b
+
r+ /
9.1:
r, w, a .
,
( r.
9.2
9.2.1
read().
, bytes
.
readlines read,
,
,
. , close()
.
9.2.2
, ,
,
open().
,
.
, -
,
.
9.2.3
for
(iterate), .
for l i n e in f :
prin t ( l i n e )
118 9.
, -
.
, , -
\n. , ,
. -
print ,
.
9.2.4 ()
(serialization) , -
bits
( ) -
.
.
( -
) .
, Python (module) pickle.
pickle
.
0:
1:
2: 2
Python
3:
( 3),
.
, .
9.3. 119
import p i c k l e
print ( read_data )
-
python
. ,
(binary for-
mat),
.
9.3
,
. python
,
.
os
( )
.
9.3.1
:
getcwd(): .
120 9.
listdir(): .
chdir(path): path.
(module)
os.
cross-platform,
.
-
. os.path.split()
os.path.join() cross-
platform ,
.
import os
-
( cross-platform) Python.
import os
f u l l _ p a t h = os . getcwd ( )
print ( f u l l _ p a t h )
, -
os.system().
import os
,
-
122 9.
9.3.2
.
mkdir(path): path.
makedirs(path): path
-
, .
import os
Winston Churchill
-
( ) -
. -
,
.
10.1
10.1.1.
.
, -
, -
.
123
124 10.
. ,
(
).
:
1. Python .
2. ( NameError, TypeError,
IndexError).
3. .
4. ,
.
5. , traceback,
.
-
,
, if. . . else . . . ,
. ,
,
else. ,
,
except.
10.2 .
,
.
.
>>> 8/0
Traceback ( most recent c a l l l a s t ) :
10.2. . 125
(shell) Py-
thon, -
. ,
(<stdin>, -
), ( 1), (ZeroDivisionError,
) (int
division or modulo by zero).
,
.
>>> try :
... 8/0
. . . except ZeroDivisionError :
... p r i n t ( ' Could not make the d i v i s i o n ' )
...
Could not make the d i v i s i o n
, -
try -
,
except.
(
ZeroDivisionError),
.
.
, -
:
>>> a 5
Traceback ( most recent c a l l l a s t ) :
F i l e " <stdin > " , l i n e 1 , in <module>
NameError : name ' a ' i s not defined
126 10.
a .
NameError.
, a,
try. . . except. . . ,
(NameError).
( )
.
>>> b = None
>>> b 7
Traceback ( most recent c a l l l a s t ) :
F i l e " <stdin > " , l i n e 1 , in <module>
TypeError : unsupported operand type ( s ) for :
' NoneType ' and ' i n t '
, ,
, .
with,
3BirdsAreSitting.mp3, with,
, ,
.
,
except,
,
.
10.2. . 127
-
except:, , -
.
import sys
try :
f = open ( ' myfile . t x t ' )
s = f . readline ( )
i = int ( s . strip ( ) )
except IOError as e r r :
prin t ( " I /O e r r o r : { } " . format ( e r r ) )
except ValueError :
prin t ( " Could not convert data to an i n t e g e r . " )
except :
prin t ( " Unexpected e r r o r : " , sys . exc_info ( ) [ 0 ] )
raise
, -
, , -
except . ,
myfile.txt,
.
, .
,
, IOError -
err.
. -
except
,
, except
128 10.
try, .
ValueError
.
, ,
raise,
.1 ,
, (
) .
raise .
10.3
, ( -
web )
, ,
.
.
while True :
try :
x = i n t ( input ( " Please enter a number : " ) )
break
except ValueError :
p r i n t ( " Not a number . Try again . . . " )
print ( x )
, -
. ,
, . ,
input -
1
, ,
try. . . except. . .
.
10.4. 129
. , int
.
, x -
while, break
except ValueError,
. break ,
. ,
print.
10.4
,
Python.
1. try .
2. , except.
3. try ,
except.
4. except .
5. , .
6. , try .
7. , -
.
try :
f = open ( ' myfile . t x t ' )
except IOError as e r r :
p r i n t ( " I /O e r r o r : { } " . format ( e r r ) )
else :
s = f . readline ( )
p r i n t ( ' The f i r s t l i n e o f f i s : ' , s )
f . close ( )
else
. , ,
.
:
1. try.
2. except.
3. ( ) else.
else
except .
10.4.2 finally
, finally,
, .
while True :
try :
x = i n t ( input ( " Please enter a number : " ) )
break
10.5. 131
except ValueError :
p r i n t ( " Not a number . Try again . . . " )
finally :
times += 1
print ( ' Requested input ' , times )
,
, -
. , finally,
,
.
.
10.5
.
10.5.1
2 Exception.
.
args
.
.
try :
r a i s e Exception ( ' Can you handle i t ? ' )
except Exception as i n s t :
prin t ( i n s t . args )
prin t ( i n s t )
2
132 10.
, Exception. -
Can you handle it?.
as
inst,
. args -
, .
__str__() .
10.5.2 (raise)
,
BaseException. ,
, -
Exception. -
raise.
-
.
>>> r a i s e NameError
Traceback ( most recent c a l l l a s t ) :
F i l e " <stdin > " , l i n e 1 , in <module>
NameError
10.5.3
-
, -
Exception.
__init__, -
__str__
.
, -
,
.
>>> try :
... r a i s e MyError ( 4 )
. . . except MyError as e :
... p r i n t ( 'My exception occurred : ' , e )
...
My exception occurred : 4
10.6 if . . . else
.
if
. . . else. .
10.6.1. -
,
. ,
134 10.
( ). , -
,
.
VALUES = 10000
inverseprob = 2
d = d i c t ( [ ( x , y ) for x , y in z i p ( range (VALUES) , \
range (VALUES, 2 VALUES ) ) ] )
def try_except ( d ) :
try :
d [ ' not ' ]
except KeyError :
pass
def i f _ e l s e ( d ) :
i f ' not ' in d :
d [ ' not ' ]
else :
pass
10.6. if . . . else 135
def try_exceptYES ( d ) :
try :
d[1]
except KeyError :
pass
def if_elseYES ( d ) :
i f 1 in d :
d[1]
else :
pass
def f a i l ( ) :
prin t ( " Unsuccessful look up" )
136 10.
def success ( ) :
p r i n t ( " Successful look up" )
t = Timer ( " try_exceptYES ( d ) " ,\
" from __main__ import try_exceptYES , d " )
s f = ' Execution time with exceptions : { } seconds '
p r i n t ( s f . format ( t . t i m e i t ( ) / 10 6))
def maybe ( ) :
p r i n t ( " Successful under a p r o b a b i l i t y " )
t = Timer ( " try_exceptMAYBE ( d , inverseprob ) " ,\
" from __main__ import try_exceptMAYBE , d , inverseprob " )
s f = ' Execution time with exceptions : { } seconds '
p r i n t ( s f . format ( t . t i m e i t ( ) / 10 6))
def main ( ) :
success ( )
fail ()
maybe ( )
Seth Godin
, . -
,
, .
( -
, ),
Python 3 .
11.1 (Iterators)
, -
(iterators).
, .
mylist = [ 1 , 2 , 3]
for i in mylist :
139
140 11.
print ( i )
(iterator) -
next() .
11.1.1 for
:
for i in mylist :
. . . loop body . . .
Python :
1. next(). iter(mylist)
next().
2.
. i
mylist. ,
next() i . -
i .
StopIteration next()
mylist
.
11.2
(generators)
yield return. -
. ,
yield. ,
yield, yield. ,
,
,
.
11.2. 141
11.2.1. -
iterators. ,
. , . -
.
range() (end)
(start), modulo
.
def f i b o n a c c i (num) :
a = 0
142 11.
yield a
b = 1
yield b
for i in f i b o n a c c i ( 1 0 ) :
print ( i )
, -
lists comprehensions.
primes = [ 1 , 2 , 3 , 5 , 7]
, ,
next(). -
next()
StopIteraton
.
,
.
( yield)
. ,
yield.
11.3. 143
11.3 -
:
. -
,
-
(on the fly). ,
.
parsing
.
.
-
.
Fibonacci.
,
.
,
.. for,
.
:
1. len(). -
(
) for .
2. ( ) -
.
144 11.
,
:
for i , e in enumerate ( l ) :
...
11.4 -
,
.
,
,
( ,
).
( 1, 17).
-
.
10
Fibonacci, 20,
Fibonacci.
. fibonacci
.
import i t e r t o o l s
class Indexable ( o b j e c t ) :
def _ _ i n i t _ _ ( s e l f , i t ) :
11.4. 145
self . it = it
def _ _ i t e r _ _ ( s e l f ) :
for e l t in s e l f . i t :
yield e l t
def __getitem__ ( s e l f , index ) :
try :
return next ( i t e r t o o l s . i s l i c e ( s e l f . i t , index ,\
index + 1 ) )
# support f o r [ s t a r t : end : step ] notation
except TypeError :
return l i s t ( i t e r t o o l s . i s l i c e ( s e l f . i t ,\
index . s t a r t , index . stop , index . step ) )
i t = Indexable ( f i b o n a c c i ( 4 5 ) )
# prints the 10th element
print ( i t [ 1 0 ] )
# 55
, .
-
,
, (
).
(pattern).
Python.
. ,
. ,
.
12.1
1 . -
1
.
147
148 12.
-
.
,
. ,
4.
import re
def num_start4 ( t e x t ) :
" " " Check whether any number which s t a r t s with 4. " " "
pattern = re . compile ( r ' \b4[0 9] ' )
-
\. .
,
4 4321 4 3421.
. ,
.
import re
Josh Cage
, ,
,
-
.
13.1
( ) object.
-
(descriptors).
-
(attributes) .
, -
. -
. ,
149
150 13.
x -
y .
,
getters set-
ters
. , -
.
Python ,
-
. ,
.
13.2
13.2.1
. -
:
__delete__(self, instance)
(attributes) :
: -
__get__(self, instance, owner). ()
AttributeError.
:
__set__(self, instance, value).
:
__delete__(self, instance).
13.2. 151
self
() ,
.
owner:
.
instance: ( )
. None
.
value: -
.
152 13.
14
GUI tkinter
. :
. .
GUI (Graphical
User Interface) .
.
:
1. wxPython
2. pyQT
3. PyGTK
4. tkinter
,
-
Python. , tkinter (= Tk interface) Python,
153
154 14. GUI tkinter
.
Tcl/Tk. tkinter
Tcl/Tk.
14.1
:
from t k i n t e r import
root = Tk ( )
root . mainloop ( )
tkinter , -
,
. (label)
pack(). ,
(mainloop)
.
14.2
,
. ,
, -
. , -
.
,
.
14.2. 155
from t k i n t e r import
from t k i n t e r . messagebox import
def d_result ( s e l f , c ) :
" " " Displays the r e s u l t o f an operation
"""
def d_add ( s e l f ) :
" " " Handles the addition in the GUI
"""
a , b = s e l f . getNum ( )
c = s e l f . addition ( a , b )
s e l f . d_result ( c )
def d_sub ( s e l f ) :
" " " Handles the substraction in the GUI
"""
a , b = s e l f . getNum ( )
c = s e l f . substraction ( a , b )
s e l f . d_result ( c )
156 14. GUI tkinter
def d_mul ( s e l f ) :
" " " Handles the m u l t i p l i c a t i o n in the GUI
"""
a , b = s e l f . getNum ( )
c = s e l f . multiplication ( a , b )
s e l f . d_result ( c )
def d_div ( s e l f ) :
" " " Handles the d i v i s i o n in the GUI
"""
a , b = s e l f . getNum ( )
c = s e l f . division ( a , b)
s e l f . d_result ( c )
def addition ( s e l f , a , b ) :
" " " Add numbers a , b and return t h e i r r e s u l t
"""
c = a + b
return c
def substraction ( s e l f , a , b ) :
" " " Substract a b and return the r e s u l t
"""
c = a b
return c
def m u l t i p l i c a t i o n ( s e l f , a , b ) :
" " " Multiply a b and return i t s r e s u l t
"""
c = a b
14.2. 157
return c
def d i v i s i o n ( s e l f , a , b ) :
" " " Divide a / b and return i t s r e s u l t
"""
try :
# i f b != 0
c = a / b
except ZeroDivisionError :
# i f b == 0
showinfo ( ' Warning ' , ' Cannot d i v i d e by 0. ' )
c = 0
return c
def getNum ( s e l f ) :
" " " Gets the two numbers on which the operation
w i l l be applied .
In case o f error , i t returns both o f them as zero
and warns the user .
"""
try :
a = f l o a t ( s e l f . enter1 . get ( ) )
b = f l o a t ( s e l f . enter2 . get ( ) )
return a , b
two numbers
"""
# The f i r s t number
s e l f . label1 = Label ( s e l f , t e x t = l a b e l )
s e l f . label1 . pack ( )
# create the f i e l d f o r that number
s e l f . enter1 = Entry ( s e l f )
s e l f . enter1 . pack ( )
def drawGUI ( s e l f ) :
"""
I t draws the GUI within the container from which i s
c a l l e d . In t h i s case , within the frame where the
c a l c u l a t o r belongs .
"""
s e l f . button2 = \
Button ( s e l f , t e x t = " sub " , command = s e l f . d_sub )
s e l f . button3 = \
Button ( s e l f , t e x t = "mul" , command = s e l f . d_mul )
s e l f . button4 = \
Button ( s e l f , t e x t = " div " , command = s e l f . d_div )
# display them
s e l f . button1 . pack ( side=LEFT )
s e l f . button2 . pack ( side=LEFT )
s e l f . button3 . pack ( side=LEFT )
s e l f . button4 . pack ( side=LEFT )
return root ;
root = Tk ( )
calc = Calculator ( master = root )
calc . mainloop ( )
160 14. GUI tkinter
Entry -
Button .
14.3
pop-up -
,
. print
(
).
-
,
tkinter.messagebox. ,
.
showinfo()
askokcancel()
showwarning()
showerror()
askquestion()
askyesno()
askretrycancel()
14.3. 161
-
:
: . ,
.
, -
.
from t k i n t e r import
from t k i n t e r . messagebox import
( , ),
true false .
15
,
. ,
.
15.1
15.1.1
. -
.
, -
.
163
164 15.
,
.
15.1.2
(run time errors)
(
, ).
15.1.3
,
.
. ,
!
import pdb
debugger .
:
1
Python DeBugger
15.2. Python Debugger 165
(breakpoints)
Python.
15.2.1
, -
pdb.set_trace().
import pdb
pdb.set_trace(),
n -
.
n,
enter
. debugger
q debugger c
.
15.2.2
n,
debugger ,
. -
s.
n,
166 15.
, -
.
s, r. , -
return
( -
).
15.2.3
l p.
,
p ,
.
,
Python . , -
-
,
.
-
,
Python. ,
(!)
debugger Python
.
15.2.4
15.1 -
debugger.
15.2. Python Debugger 167
import pdb debugger.
pdb.set_trace()
<Enter>
q (quit)
p (print)
c (continue)
l (listing)
s (step into)
r (return)
15.1:
168 15.
16
Albert Einstein
.
, .
-
-
. , ,
, -
. -
; ,
. garbage collector
,
. ,
.
Python,
,
169
170 16.
, timeit. timeit,
,
. , -
,
.
, .
16.1
. -
1 -
.
def measure_time ( ) :
from t i m e i t import Timer
s = """\
x = 5
i f x > 5:
p = 4
else :
p = 0
"""
t = Timer ( s )
print ( t . timeit ( ) )
timeit()
1.000.000 , , -
.
,
1
.
16.2. 171
number
timeit().
def measure_time ( ) :
from t i m e i t import Timer
s = """\
x = 5
i f x > 5:
p = 4
else :
p = 0
"""
t = Timer ( s )
prin t ( t . t i m e i t ( number=100000))
16.2
,
timeit.
Timer.
. -
(statements)2
.
def measure_time ( ) :
from t i m e i t import Timer
t = Timer ( " f a s t _ f u n c t i o n ( ) " ,\
" from __main__ import f a s t _ f u n c t i o n " )
s f = ' Execution time ( f o r each c a l l ) : { } seconds '
prin t ( s f . format ( t . t i m e i t ( ) / 10 6))
def f a s t _ f u n c t i o n ( ) :
2
(;)
172 16.
def main ( ) :
measure_time ( )
fast_function(),
.
.
, -
fast_function Timer -
106 ,
. ,
, t.timeit()
fast_function. ,
1000 .
,
106 ,
.
16.3. garbage collector 173
def measure_time ( ) :
from t i m e i t import Timer
s = """\
x = 5
i f x > 5:
p = 4
else :
p = 0
"""
t = Timer ( s , ' gc . enable ( ) ' )
prin t ( t . t i m e i t ( number=100000))
16.4
. ,
. Ti-
mer() .
-
3 .
, -
.
3
, pass
174 16.
,
.
def measure_time ( ) :
from t i m e i t import Timer
def f a s t _ f u n c t i o n ( a , b ) :
" " " A f a s t function or at l e a s t we hope so " " "
if a > b:
l = []
else :
d = {}
def setup_function ( ) :
" " " A function which must be c a l l e d f i r s t " " "
a = 5
#b = 4
b = i n t ( input ( " I n s e r t b : " ) )
return a , b
def main ( ) :
measure_time ( )
, -
,
.
16.5
-
; !
,
, ,
.
, (
)
:
, -
. (Garbage Collector)
16.6 (Profiling)
, -
,
. , -
(Law of diminishing
returns).
,
. -
.
176 16.
, -
profiling Python cPro-
file.
. -
.
:
python m c P r o f i l e filename . py
, ,
, .