Taspython Python
Python
:
: TasPython
2008 / & , , . , , , . , , , , , . , , . TasPython , , . , .
iii
iv
.
vi
1 1.1 . . . . . . . . . . . . . . . . . 1.1.1 . . . . . . . 1.1.2 . . . . . . . . . . . 1.1.3 . . . . . . 1.1.4 . . . . . . . . . . . . . . . . . . . . . . 1.1.5 . . . . . . . . . . . . . 1.1.6 . . . . . . . . . . . . . . . . . . . . . 1.1.7 . . . . . . . . . . . . . . . . . . . . 1.1.8 . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.9 . . . . . . . . . . . . . . 1.2 Python . . . . . . . . . . . . . . . . . . . . . . . . . 1.2.1 . . . . . . . . . . . . . . . . . . . 1.2.2 Python 3 . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2.3 . . . . . . . . . . . . . . . . . . . . . . . . . 1.2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2.5 Zen of Python . . . . . . . . . . . . . . . . . . . . . . . 1.2.6 Python . . . . . . . . . . 1.3 . . . . . . . . . . . . . . . . . . . . . . . . 2 2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
1 1 2 2 3 4 4 5 5 5 6 6 9 10 11 12 13 14 17 19 20 21
viii
22 24 27 27 28 29 30 32 34 34 36 36 37 38 39 41 42 42 42 43 44 45 47 . . . . . . . . . . . . . . . . . . . . . . . . . 48 49 50 51 52 55 56 56 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3 Boolean . . . . . . . . . . . . . . . . . . . . . . . . 2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 3.4 if 3.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.4.1 . . . . . . . . . . . . . . . . . . 3.5 . . . . . . . . . . . . . . . . . . . . . . . 3.5.1 for . . . . . . . . . . . . . . . . . . . . . . . . 3.5.2 while . . . . . . . . . . . . . . . . . . . . . . . 3.6 break . . . . . . . . . . . . . . . . . . . . . . . . . 3.7 with . . . . . . . . . . . . . . . . . . . . . . . . . . 3.7.1 with . . . . . . . . . . . . . . . . . . . . . . 3.7.2 . . . . . . . . . . . . . . . . . . . . . . . 4 4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 4.1.2 4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.3
4.4 . . . . . . . . . . . . . . . . . . . . . . . . 5 5.1 5.2 . . . . . . . 5.3 . . . . . . . . . . . . . . . . . . . . . 5.3.1 . . . . . . . . . . . . . . . . . . . . . . 5.4 (Decorators) . . . . . . . . . . . . . . . . . . . . 6 6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 6.1.1
6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2.1 . . . . . . . . . . . . . 6.2.2 . . . . . . . . . . . . . . . 6.2.3 . . . . . . . . . . . . . . 6.2.4 . . . . . . . . . . . . . . . 6.2.5 . . . . . . . . . . . . . . . . . . . 6.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.3.1 . . . . . . . . . . . . . . . . . . . . . 6.3.2 . . . . . . . . . . . . . . . 6.3.3 . . . . . . . . . . . . . . . . . 6.3.4 . . . . . . . . . . . . . . . . . . . . 6.3.5 (Lists comprehensions) . . . . . . . 6.3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.5.1 . . . . . . . . . . . . . . . . . . . . 6.5.2 . . . . . . . . . . . . . . . . . . . 6.5.3 . . . . . . . . . . . . . . . . . . . . . . . 6.5.4 . . . . . . . . . . . . . . . . 6.5.5 (Dict comprehension) . . . . . . . 6.5.6 . . . . . . . . . . . . . . . . . . . 6.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.6.1 . . . . . . . . . . . . . . . . . . . . . . . . 6.6.2 . . . . . . . . . . . . . . . . . 7 7.1 (immutable objects) . . . . . . . . . . . . . . . . 7.2 . . . . . . . . . . . . . . . . . . . . . . . 7.2.1 . . . . . . . . . . . . . . . . . . . . . . . . 7.2.2 None . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.3 . . . . . . . . . . . . . . . . . . . . . . . . . 7.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.5 . . . . . . . . . . . . . . . . . . . . .
ix 57 57 58 59 60 60 62 63 64 66 66 67 68 68 69 69 70 72 72 73 73 74 74 75 77 77 79 80 81 82 83 88
x 8
93 93 95 98
8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2 . . . . . . . . . . . . . . . . . . . . . . . . . 8.3 . . . . . . . . . . . . . . . . .
8.4 (attributes) . . . . . . . . . . . . . . 101 8.5 . . . . . . . . . . . . . . . . . . . . . . . 102 8.6 . . . . . . . . . . . . 103 8.6.1 . . . . . . . . . . . . . . . . . . . . 103 8.6.2 . . . . . . . . . . . . . . . . . . . . . 104 8.7 . . . . . . . . . . . . . . . . . . . . . . . . . 104 8.8 . . . . . . . . . . . . . . . . . . . . . . . . . 106 9 109
9.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 9.2 . . . . . . . . . . . . . . . . . . . . . . . 110 9.2.1 . . . . . . . . . . . . . . . . . . . 110 9.2.2 . . . . . . . . . . . . . . . . . . . . 111 9.2.3 . . . . . . . . . . . . . . . . . . . . 111 9.2.4 () . . . . . 112 9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 9.3.1 . . . . . . . . . . . . . . . . . 113 9.3.2 . . . . . . . . . . . . . . . . . . . 116 10 117
10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 10.2 . . . . . . . . . . . . . . . . . . . . . . . . . . 118 10.3 . . . . . . . . . . . . . . . . . . . . . 122 10.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 10.4.1try:. . . else: . . . . . . . . . . . . . . . . . . . . . . . . . 123 10.4.2nally . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 10.5 . . . . . . . . . . . . . . . . . . . . . 125 10.5.1 . . . . . . . . . . . . . . . . . . . 125 10.5.2 (raise) . . . . . . . . . . . . . . . 126 10.5.3 . . . . . . . . . 126 10.6 if . . . else . . . . . . . . . . . . . . . . . . . . . . 127
11
xi 133
11.1 (Iterators) . . . . . . . . . . . . . . . . . . . . . 133 11.1.1 for . . . . . . . . . . . . . . 134 11.2 . . . . . . . . . . . . . . . . . . . . . 134 . . . . . . . . 137 11.3
11.4 . . . . . . . . 138 12 141
12.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 12.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 12.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 142 13 GUI tkinter 145
13.1 . . . . . . . . . . . . . . . . . . . . . . . . . 146 13.2 . . . . . . . . . . . . . . . . . . . 146 13.3 . . . . . . . . . . . . . . . . 152 14 155
14.1 . . . . . . . . . . . . . . . . . . . . . . . . . 155 14.1.1 . . . . . . . . . . . . . . . . . . . 155 14.1.2 . . . . . . . . . . . . . . . 156 14.1.3 . . . . . . . . . . . . . . . . . . . . . 156 14.2 Python Debugger . . . . . . . . . . . . . . . . . . . . . . . . . 156 14.2.1 . . . . . . . . . . . . . . . . . . . . 157 14.2.2 . . . . . . . . . . . . . . . . . . . . . . . . 157 14.2.3 . . . . . . . . . . . . . . . . . 158 14.2.4 . . . . . . . . . . . . . . . . . . . . 158 15 161
15.1 . . . . . . . . . . . . . 162 15.2 . . . . . . . . . . . . 163 15.3 garbage collector . . . . . . . . . . . . . . . . . 165 15.4 . . . . . . . . . . . . . . . 165 15.5 . . . . . . . . . . . . . . . . . . . . 167
xii
1In times of change, learners will inherit the earth while the learned will nd themselves beautifully equipped to deal with a world that no longer exists. Eric Hoer
Python 3. . , . : Longum iter est per preaecepta, breve et ecax per exempla! , . , .
1.1
Python . 1
2
1.
Linux . , , . .
1.1.1
, . , , . . , . . , . . . , , 1 .
1.1.2
, . . , (compile)2 , , . , ! 2 1
1.1.
3
, , , . . . .
1.1.3
, , , . , . , . , , . , ( ), , . , , . , . , , .
4
1.
1.1.4
, . !, . , . , . , . , . . , ! , , . , , . , ! , !
1.1.5
. , . . . .
1.1.
5
1.1.6
-
,
, . . . . , Python . . , , . .
1.1.7
. . , . , .
1.1.8
(compiler) . . . , . , . , . , . , -
6
1.
, .
1.1.9
-
. . , , . Python . , . (bugs), .
1.2
Python
Python , (semantics). (standard library). :
( , )
1.2. Python segmentation faults
7
Python . , . . , . , - , . Python ( C, C++) Python 3 5 Java. , . ( ) . . (eciency), (productivity). , . (interpreters) (compilers).
8
1.
. (virtual machine) ( Python). , , (bytecode). (object code). . , . , . , (modules) , , ( 3 Python ). , ( Windows, Linux/Unix, OS/2, Mac, Amiga). , Java, Jython Java, .NET IronPython Microsoft. , C/C++ (modules) Python. , . 1980 . ,
1.2. Python
9
. , , Python segmentation faults. , Python ( throw) . . , Python . (reference counting).
1.2.1
,
Python, .
(generators), , . , , ( , ..). , , , , ( ) . Python , . , , , , , . -
10
1.
. (Python Enhancement Proposal (PEP)) ( PEP 8 PEP 257)
1.2.2 Python 3 Python , 1980. , ( 3 import this) . :
7 / 4 = 1 C. range ( ) print statement .
.
Unicode ( ) . ... .
, . Python 3 ( py3k 3000). , Linux python3 , Windows IDLE.3
1.2. Python
11
. :
7 / 4 = 1.75 ( // )
. range 4 .
print Unicode, .
...
Python.
1.2.3
:
2
2to3 3to2 python -3
4
11.2.
12
1. 2
3 , . Python (2.6+) 3 Python. , PEP 3003 (Python Enhancement Proposal) 2 Python . (CPython) ( Jython, Pypy, IronPython)
1.2.4
Python, :
Google ( Google App Engine) NASA Yahoo! MIT RedHat linux ... !
Python, : 1. (prototyping) 2. 3. Scripting 4.
1.2. Python 5. 6. 7. ... !
13
1.2.5 Zen of Python Zen of Python Python
Tim Peters. : import t h i s . . . . . . . . . . . , . . . . . , . , .
14
1. (namespaces)
!
1.2.6
Python
Python .py. . .py . : >>> a = 5 >>> b = 6 >>> a + b 11 (interpreter), ( Linux, > > cmd Windows) python ( python3 ). >>> , .
Windows -
python. 1. Python PATH. , -> -> -> (Control Panel -> System -> Advanced -> Environment Variables) (path) Python. (command line) python onoma.py.
1.2. Python
15
2. IDLE ( python ). (File > Open). , Run Module > Run .
Notepad Wordpad. , Notepad++ .
Linux 1. path . python3 onoma.py 5 . 2. , #!/ usr/bin/env python3
#!/ usr/bin/python3 . #/usr/bin/env python3 Python 3 ( /usr/bin/python3) . , . , , . python 3 python3 /usr/bin5
16
1.
PEP6 8 Python, tab , (indent) .7 "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
3. Mac TextWrangler
Tabs: Auto Expand Tabs. Defaults > Auto-Expand Tabs Defaults > Auto-indent.
: , Unix.
6 PEP: Python Enhancement Proposal. , , .. 7 PEPs http://python.org/dev/peps/.
1.3.
17
. Windows, IDLE ( ) , Eclipse pydev. Linux kate gedit, Eclipse. ( ). , .
1.3
: 1 Python. 2 . , . 3 , . 4 . 5 . 6 : . 7 Python . 8 : . .
18
1. 9
. , . 10 . 11 Python, . 12 . 13 (tkinter) Python. 14 . , 15 ( ).
2, , , : . ,
,
. . , , . , . , Structure and Interpretation of Computer Programs : 1. , . 19
20
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.
21
, . dynamic typing. , Python . . : a ='
asdf '
a = 2 a = pow ( a , 100000) print ( a ) a -
. 2.1.3. (dynamically typed), . , . , Python .
2.2
2.2.1. . . , .
num = 17 pi = 3.14 paei = paei =' '
Allou ' Molis g y r i s e'
22
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 and False () True or False ()
Boolean . . Boolean :
not or and
2.3. Boolean
23
.
2.1: not
a
b
2.2: and
a
b
2.3: or
( and), ( or) ( not and)1 . . De Morgan .1
24
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. (+) () () (/) () (modulo) (%)
25
. . Python .
(==) (! =) (>) (=) (= 0: x1 = (b + sqrt (D ) ) / (2 x2 = (b sqrt (D ) ) / (2 else : x1 = complex(b / (2 x2 = complex(b / (2* * * * *
31
a
*
c
a) a)* *
a ) , sqrt (D) / 2 a ) , sqrt (D) / 2
a) a)
s f = " x1 = { 0 } , x2 = { 1 } " print ( s f . format ( x1 , x2 ) )
. . : x1,2 =
( if 1 ( else).
+ , = 2 4 . 2
0 , .
1
32
3.
3.4.1
if...elif...else... Python, switch k , k switch. switch C/C++ Java. Python, if...elif...else.... : x = i n t ( input ( " Please enter an i n t e g e r : " ) ) i f x < 0: p r i n t ( ' Negative number, transforming i n t o p o s i t i v e ' ) x = x # make i t p o s i t i v e # Be careful , because the f o l l o w i n g statements w i l l be # examined only i f the f i r s t condition i s f a l s e , they # won ' t be executed e l i f x == 0: p r i n t ( ' Zero ' ) e l i f x == 1: p r i n t ( ' One ' ) else : p r i n t ( ' Great than 1 ' ) , elif , . switch, . Python . (key) . -
3.4. if
33
, , . # Sample functions def square ( x ) : return x **2 def double ( x ) : return x *2 opdict = { " a " : square , " b " : square , " c " : double } # Example ( random access O( 1 ) ) print ( opdict [ " b " ] ( 5 ) ) # Example 2 ( checking everything ) for operation in " abc " : prin t ( operation , opdict [ operation ] ( 3 ) ) if...elif...else.... , , . , , . # Sample functions def square ( x ) : return x **2 def double ( x ) : return x *2 def decrease ( x ) : return x1
34
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 ' )
# Example 2 ( checking everything ) for operation in " abc " : p r i n t ( operation , opdict [ operation ] ( 3 ) )
3.5
, . ( ) , . , for while .
3.5.1
for
for . -
range(). , range() , . 20 Fibonacci. n- Fibonacci Fn = Fn1 + Fn2 F0 = 0 F1 = 1. # the 2 f i r s t f i b o n a c c i numbers are always known a, b = 0, 1 # p r i n t the f i r s t f i b o n a c c i number ( a ) p r i n t ( a , end= ''
)
3.5. # find the next 18 f i b o n a c c i numbers and p r i n t them for i in range ( 1 8 ) : prin t ( b , end= ' a, b = b, a + b # print the l a s t fibonnaci number ( o f t o t a l l y 20) print ( b )'
35
)
i 0 17, 18 . 2 range() . range() , . >>> for i in range (100 , 120): ... ... 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 p r i n t ( i , end= ''
)
>>> for i in range (100 , 120, 2 ) : ... ... 100 102 104 106 108 110 112 114 116 118 p r i n t ( i , end= ''
)
[100, 120) [100, 120) 2, .
.2
, .
36
3.
3.5.2
while for, while
. def f i b ( a , b ) : sum = 0; while a < 4 sum += a a, b = b, a + b return sum a, b = 0, 1 print ( f i b ( a , b ) ) Fibonnaci 4 106 .*
(10
**
6):
3.6
break
break . , if . break . . , . Zn (modulo). 0, . def printSubgroups ( n ) : """ Prints a l l the subgroups o f Zn
3.7. with """ for i in range ( 0 , n ) : p r i n t ( ' < ' , end= ' ' ) p r i n t ( i , end= ' >: num = ( i * j )%n p r i n t (num, end = break print ( ' , print ( )' ' ' '
37
)
for j in range ( 1 , n + 1 ) : )
i f (num % n ) == 0: , end= ''
)
3.7
with
3 Python, with , . . with , with . , block with. with . filename = "CanadaSong . t x t " data = " " " \ F i r s t come the black f l i e s , Then the Horse f l i e s , Then the Deer f l i e s , Then the snow f l i e s ! """ with open ( filename , "w" ) as fout :
38 fout . write ( data )
3.
, with, lename, . , . , with .
3.7.1
with
with , with . . , . # every l i n e containing these words won ' t be written # at the output exclude_class = [ ' not ' , with open ( ' i n f i l e ' ,' '
negation ' ]'
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 f2 . write ( l i n e )
39
3.7.2
__enter__ __exit__, with __enter__ , , __exit__. . with __exit__, ( , ). with, __exit__, . .
40
3.
4And there was huge numbers of UFOs around my parents home in Kingston. Betty Hill)
Python . :
(scripts). scripts. . Python , , . , . (overow). . python , :
41
42 python
4.
. , ctrl+d Linux/BSD ctrl+z Windows.
4.1
(, , , ) (+, , , /) >>> 3+8 11 >>> 38
5>>> 3*8 24 >>> 3/8 0.375
4.1.1
. ( ) . >>> 7/2 3.5 >>> 7//2 3
4.1.2
, .
4.2.
43
>>> 2**10 1024 >>> 3**8 6561 n (mod n ), python (modular exponentiation) , . , . , 21024 , 1024 1000 . Python . >>> pow( 2 , 1024, 1000) 216
4.2
, : 1. d: 2. b: ( bin()) 3. o: ( oct()) 4. x: ( hex()) , .
44
4.
p r i n t ( ' value = { 0 : 2 d } ' . format ( 1 2 ) ) p r i n t ( ' value = { 0 : 2 b } ' . format ( 1 2 ) ) p r i n t ( ' value = {0:#2b } ' . format ( 1 2 ) ) p r i n t ( ' value = { 0 : 2 o } ' . format ( 1 2 ) ) p r i n t ( ' value = {0:#2 o } ' . format ( 1 2 ) ) p r i n t ( ' value = { 0 : 2 x } ' . format ( 1 2 ) ) p r i n t ( ' value = {0:#2 x } ' . format ( 1 2 ) )
# value = 12 # value = 1100 # value = 0b1100 # value = 14 # value = 0o14 # value = c # value = 0xc # value = 0b1100 # value = 0o14 # value = 0xc
p r i n t ( ' value = { 0 : 5 } ' . format ( bin ( 1 2 ) ) ) p r i n t ( ' value = { 0 : 5 } ' . format ( oct ( 1 2 ) ) ) p r i n t ( ' value = { 0 : 5 } ' . format ( hex ( 1 2 ) ) )
4.3
, (specier) f . . , +, . . p r i n t ( ' x = { 0 : 5 . 3 f } ' . format (1234.567)) p r i n t ( ' x = { 0 : 1 2 . 6 f } ' . format (1234.567)) p r i n t ( ' x = {0: 12.9 f } ' . format (1234.567)) p r i n t ( ' x = {0:+12.9 f } ' . format (1234.567)) p r i n t ( ' x = {0:012.3 f } ' . format (1234.567)) print ( ) p r i n t ( ' x = { 0 : 1 . 5 e } ' . format (1234.567)) # x = 1.23457e+03 p r i n t ( ' x = { 0 : 1 . 5 e } ' . format (0.000001234)) # x = 1.23400e06 p r i n t ( ' x = { 0 : 1 . 5 g } ' . format (0.000001234)) # x = 1.234e06 print ( ) p r i n t ( ' x = {0:2.3%} ' . format ( 0 . 3 3 7 ) ) print ( ) # x = 33.700% # x = 1234.567 # x = 1234.567000 # x = 1234.567000 # x = +1234.567000 # x = 00001234.567
p r i n t ( ' x = {0:+12.9 f } ' . format ( 1234.567)) # x = 1234.567000
4.4. print ( ' pi = { 0 : . 3 f } ' . format ( math . pi ) ) print ( ' pi = { 0 : . 8 f } ' . format ( math . pi ) ) # pi = 3.142 # pi = 3.14159265
45
4.4
(, , ). complex. , . a = complex ( 1 , 1) b = complex ( 1 , 2) print ( a+b ) print ( a *b )
46
4.
5 , ( ) . .
.
, , . -
, . , . , Python . , , . , , . , 47
48
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.
49
from math import c e i l 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) . , (modier functions) . (side eects), , .
50
5.
a =
'
Python '
p r i n t ( a . upper ( ) ) print ( a ) , upper() . a. , (mutable), , . , , count() b, reverse() . b = [ 'a ' , print ( b ) p r i n t ( b . reverse ( ) ) print ( b )'
,
string
b' ,
'
c',
'
d ' ,]
p r i n t ( b . count ( ' a ' ) )
5.3
. . , . def h e l l o ( message= ' Hello World ! ' ) : p r i n t ( message ) hello ( ) h e l l o ( message= ' Hello Brave New World ! ' )
5.3.
51
5.3.1
. . . , tuple . >>> a = ( 1 , 2 , 3 , 4) >>> def add ( a , b , c , d ) : ... ... >>> add ( * a ) 10 return a + b + c + d
. , . , ( ) . . b = { 'a ' :2 ,'
c ' : 3,
'
d ' : 5,
'
b ' :1}
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 ) ) print_variables (**b )
52
5.
5.4
(Decorators)
. , (randomized algorithm). Python . , . . , , . , . , . Python . , . , (decorators). def makebold ( fn ) : def wrapped ( ) : return " " + fn ( ) + " " return wrapped def message ( ) : return " TasPython Guide " message = makebold ( message ) p r i n t ( message ( ) )
5.4. (Decorators)
53
g f . g f . , makebold() wrapped(). wrapped() . . , f n wrapped() . wrapped() , makebold(). message makebold(message). , Python . , makebold(message) message. message , , . makebold(), wrapped(). wrapped() makebold() string fn . . , . , . def makebold ( fn ) : def wrapped ( ) : return " " + fn ( ) + " " return wrapped @makebold def message ( ) : return " TasPython Guide "
54 p r i n t ( message ( ) )
5.
, , message() , . , message(), makebold.
6There is no abstract art. You must always start with something. Afterward you can remove all traces of reality. Pablo Picasso
.
. . , , , Python . , . 55
56
6.
6.16.1.1
(Strings): (quotes). immutable .'
This i s a s t r i n g
'
(Tuples): , . . ( ' These ' , 3 , 5.711 , True ,'
Prime ' )
(Lists): [ ]. . (mutable). [ ' These ' , 3 , 5.711 , True ,'
Prime ' ]
(Dictionaries): { } . ( ) : key: . value: , . {1:'
alpha ' , 2:
'
beta ' , 3:
'
gamma ' , 4:
'
delta ' }
(Sets): , set . .
6.2.
57
( (union), (intersection), (dierence), (issuperset), (issubset)) (add), (remove) . 6.1 . (string) (tuple) (list) (dictionary) . . . . keys. .
6.1:
6.26.2.1
, , . , . UTF-8. # the v a r i a b l e myString points to an immutable s t r i n g myString ='
This i s a s t r i n g .
'
(sequence). , .
58
6.
myString =
'
This i s a s t r i n g .
'
# the f i r s t character o f myString p r i n t ( myString [ 0 ] ) # the second character o f myString p r i n t ( myString [ 1 ] ) p r i n t ( myString [ 2 ] ) p r i n t ( myString [ 3 ] ) # prints the l a s t character which i s p r i n t ( myString [ len ( myString ) 1 ] ) () (index). # the v a r i a b l e myString points to an immutable s t r i n g myString = # prints # prints # prints' ' '
.'
This i s a s t r i n g .
'
# the l a s t character o f myString .' g '. n '. p r i n t ( myString [ 1])'
p r i n t ( myString [ 2])'
p r i n t ( myString [ 3])
6.2.2
, . , . def reverse ( t e x t ) : return t e x t [ : : 1 ]
6.2. sentence = input ( ' Enter your t e x t : i n v e r t = reverse ( sentence ) print ( ' The inverted t e x t i s : ' , i n v e r t ) )
59
'
, . : 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] sentence = input ( ' Enter your t e x t : i n v e r t = r e v e r s e p a r t i a l l y ( sentence ) print ( ' The inverted t e x t i s : ' , i n v e r t ) 3, 2, . Python, , 0.'
)
6.2.3
string.format(). python, strings . , {x}, x . sf ='
the { } jumped over the { } !'
'
print ( s f . format ( ' mouse ' ,
moon ' ) )
60
6.
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(). >>> a = >>> b = [ ' asdf ' ] >>> b . s p l i t ( ' ' ) [ ' asdasdf ' ,' ' '
asdf ' asdasdfnbfds '
>>> a . s p l i t ( ' ' )
nbfds ' ]
split()
. , , .
6.2.5
,
6.2. .
61
# count l i n e s , sentences , and words o f a t e x t f i l e # set a l l the counters to zero lines , blanklines , sentences , words = 0 , 0 , 0 , 0 # t r y to open the f i l e try : filename ='
random_file ''
t e x t f = open ( filename , except IOError :
r')
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 ) # reads one l i n e at a time for l i n e in t e x t f : # increase l i n e counter l i n e s += 1 # 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
62
6. # so f o r instance double space counts as one space tempwords = l i n e . s p l i t ( None ) # 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 ( )
p r i n t ( " Lines p r i n t ( " Sentences p r i n t ( "Words
: " , lines ) : " , sentences ) : " , words )
p r i n t ( " Blank l i n e s : " , blanklines )
6.3
6.3.1. . . . , . Python . . . , . l i s t 1 = [ ' pick up g r o c e r i e s ' , 123,\'
do laundry ' , 3.14 ,
'
return l i b r a r y books ' ]
# an empty l i s t list2 = [ ]
6.3. # a l i s t may contain any type o f o b j e c t l i s t 3 = [ l i s t 1 , l i s t 2 , 1.234 , print ( l i s t 3 )'
63
This i s a diverse l i s t ' ]
, . , , , .
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]
64 b = list (a) c = a print ( b ) print ( c ) # b i s a copy o f a and any change # on i t doesn ' t a f f e c t a b[0] = 5 print ( a ) # c i s a reference to a and a l l # changes are r e f l e c t e d to a c [ 0 ] = 10 print ( a )
6.
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. [i, j): list1 [ i : j ]
65
, . 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]
k list1 [ : : k]
k ,
, ( ). def reverse ( l i s ) : return l i s [ : : 1 ]
66
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.
67
6.3.5
(Lists comprehensions)
(list comprehensions). , . . primes = [ 1 , 2 , 3 , 5 , 7] square_primes = [ i **2 for i in primes ] print ( square_primes ) 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) (lter), . . . , for, . . , , , sum(). , 100 3 7. nums = [ i for i in range ( 1 , 101) i f i % 3 == 0 or i % 7 == 0] sum(nums) #2208 .1
68
6.
6.3.6
, . . 6.3.2. . :
push ( append Python) pop
. a = [1 , print ( a ) b = a . pop ( ) print ( b )'
TasPython ' ,
'
geia ' ]
a . append ( ' xara ' )
6.4
6.4.1. . . :
. , . , , . a = (1 , print ( a )'
asdf ' , 3.14)
6.5.
69
, . , .
6.5
(dictionary) . 2 , , , ( ) .
6.5.1
. d = {' ' ' '
milk ' : 3.67 , butter ' : 1.95 , bread ' : 1.67 , cheese ' : 4.67
} . . d = {} d [ ' key ' ] = value dict(). hash .2
70
6.
d = dict ( [ ( ( ( (
' ' ' '
milk bread
'
,' '
3.67) , , 1.95) , 1.67) , , 4.67)]) ,'
butter cheese
6.5.2
: del. del d[milk] .
: ( /) len(d).
: ( ) d.keys().
: , d.values(). / : / d.items() , .
, . , , , . . . def increaseValue ( d , key , value ) : " " " Increase value o f d [ key ] . Precondition : We can add value to 0. """
6.5.
71
i f key not in d : d [ key ] = 0 d [ key ] += value
def increaseValue2 ( d , key , value ) : " " " Increase value o f d [ key ] . Precondition : We can add value to 0. """ # get the value o f d [ key ] i f i t e x i s t s , # or zero i f i t doesn ' t e x i s t . # Then add i t to value and set i t # as the new value o f d [ key ] d [ key ] = d . get ( key , 0) + value # testing d = {} increaseValue2 ( d , print ( d )'
d i m i t r i s ' , 5)
. , ( ). (value). . get . d[key] . value d[key] .
72
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() , . thoughts = { 'Omada ' :' '
TasPython ' ,\'
Ti e i n a i o Anthropos ' :
Command not found ' }
for k , v in thoughts . items ( ) : print ( k, v )
6.5.4
(mutable). . , copy(). d [ ' a ' ] = 123 c = d c [ ' a ' ] = 1821 print ( d [ 'a ' ] ) :
6.5.
73
d = {} d [ ' a ' ] = 123 c = d . copy ( ) c [ ' a ' ] = 1821 print ( d [ ' a ' ] )
6.5.5
(Dict comprehension)
, . , {} (iterable), . . d = { k : v for k , v in enumerate ( ' taspython ' ) i f v not in print ( d ) # {8:' '
tas ' }
n ' , 3:
'
p ' , 4:
'
y ' , 6:
'
h ' , 7:
'
o '} tas ' }
d = { k : v for k , v in z i p ( range ( 1 5 ) , print ( d ) # {8:'
' '
taspython ' ) i f v not in y ' , 6:'
'
n ' , 3:
'
p ' , 4:
h ' , 7:
'
o '}
, Python. . , .
6.5.6
, / . , . . . . ,
74 , .
6.
( ), . from c o l l e c t i o n s import OrderedDict d = OrderedDict ( ) d [ ' python ' ] = d [ ' guide ' ] =' '
TasPython '
Greek '
p r i n t ( d . items ( ) )
6.6
, , , . .
6.6.1
. Python , . s = { 'a ' , print ( s ) (iterable).'
a' ,
'
b' ,
'
c',
'
a'}
6.6.
75
s = set ( ' TasPython . . . because simplcity matters ! ' ) print ( s )
6.6.2
, :
. a = set ( ' abracadabra ' ) b = set ( ' alacazam ' ) print ( ' A = print ( 'B = a . add ( ' z ' ) b . remove ( ' z ' ) print ( ' A = print ( 'B =' ' ' '
, a) , b) # add element # remove element , a) , b)' ' ' '
print ( ' A B = print ( ' A | B = print ( ' A & B = print ( ' A ^ B =
, a b) , a | b) , a & b) , a ^ b)
# difference # union # intersection # symmetric d i f f e r e n c e
:
76
6.
a = [ ' apple ' , set1 = set ( a ) p r i n t ( set1 )
'
bread ' ,
'
carrot ' ,
'
carrot ' ]
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 ' , p r i n t ( set1 & set2 ) # prints { ' carrot ' , p r i n t ( set1 | set2 )' '
apple ' } apple ' ,'
delicious ' ,
'
bread ' }
7 , .
7.1
Python . ,
Python.
(immutable objects) -
Python
. . , .
bool int 77
78 oat string
7.
, . 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.
79
>>> a = 4 >>> b = 4 >>> a i s b True >>> a += 1 >>> a 5 >>> b 4
7.2
Python (container types). :
(tuple) (string) (list) (set) (dictionary)
. . (alias) , . >>> a = >>> b = False >>> a = 1' '
Python by example ' Python by example '
>>> a i s b
80 >>> b = 2 >>> a i s b False >>> b = 1 >>> a i s b True
7.
is ==. 2 == . >>> a = [ 1 , 2 , 3] >>> b = [ 1 , 2 , 3] >>> a i s b False >>> a == b True
7.2.1
(alias) , . , , , , . a = [ 1 , 2 , 3] b = a a . append ( 4 ) print ( b )
, .
2
7.2.
81
4 a, b, b a .
7.2.2 None None . Null. Null Python None. def helloWorld ( ) : prin t ( ' Hello World ' ) print ( 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 )
82
7.
7.3
( ) . . Python, , . , : from f i l e import*
python.py . , , . . , ( ) . 7.3.1. (module) (, ). .py. ( ) , ( ). ( python le.py) import . Python , "__name__" "__main__". "__name__" .
7.4.
83
from module import * , . from module import function ( ) import module, module, module.variable, ( ) / . . :
. . . .
namespace : List1 = [ 1 , 2 , 3] List2 = [ 1 , 2 , 3] List2 [ 2 ] = "new" List1 = { " a " : [ 1 ] , " b " : [ 2 ] }
7.4
. >>> def f ( a ) : ... ... a = 5
84
7.
1
2
3
aList
[0]
[1]
[2]
Namespace 7.1: (namespace) .
1
2
3
aList
[0]
[1]
[2]
bList
Namespace 7.2: .
1
2
"new"
aList
[0]
[1]
[2]
bList
Namespace 7.3: .
7.4.
85
a aDict bNamespace
[0]
1
[0]
2
7.4: .
>>> a = 4 >>> f ( a ) >>> a 4 a f , . , a = 5 . , . , L . , x L. ,
x . . , , L , . , , . ,
x . , L foo() . def foo ( x ) :
86 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 ) ) print ( L )' ' '
7. )
'
)
)
)
, L . L , . foo() , L, python L error . Python . def foo ( ) : p r i n t ( ' point 2: ' , end= ' p r i n t ( id ( L ) ) L = [ 1 , 2 , 3]'
)
# Error . L i s not declared in t h i s scope
7.4. 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 )' '
87 )
'
)
)
: . , , , , , , . def foo ( x ) : print ( ' point 2: ' , end= ' print ( id ( L ) ) x . append ( 0 ) print ( ' point 3: ' , end= ' print ( id ( x ) ) print ( x ) L = [ 3 , 2 , 1] print ( ' point 1: ' , end= ' print ( id ( L ) ) foo ( L ) print ( ' point 4: ' , end= ' print ( id ( L ) )' ' ' '
)
)
)
)
88 print ( L )
7.
7.5
, . , deepcopy. Python . from copy import deepcopy def a c c e s s _ t r i e ( d , sequence , p o s i t i o n =None ) : """ Access the d i c t i o n a r y which i s r e f e r r e d by applying consequently each term o f the sequence . terms , i f sequence i s if` '
In a more python
key ' , access : d [ ' k ' ] [ ' e ' ] [ ' y ' ] .`
Assume that the d i c t i o n a r y i s at the position ` i s an argument .
position ` o f a l i s t ,
>>> a = { ' k ' : [ 0 , { ' a ' : [ 0 , { ' l ' : [ 0 , { ' o ' : [ 1 , { } ] } ] } ] } ] } >>> a c c e s s _ t r i e ( a , { ' o ': [1 , { } ] } >>> a c c e s s _ t r i e ( a , {} >>> a = { ' p ' : { ' y ' : { ' t ' : { ' h ' : { ' o ' : { ' n ' : >>> a c c e s s _ t r i e ( a , { 'h ': { ' o ': { 'n ': >>> a c c e s s _ t r i e ( a , >>> a c c e s s _ t r i e ( a , {}' ' '
kal ' , 1) kalo ' , 1) {}}}}}}}
pyt ' ) ) {}}}}}}}
{}}}}' '
{ 'p ': { ' y ': { ' t ': { 'h ': { ' o ': { 'n ':'
python ' )
7.5. >>> b = a c c e s s _ t r i e ( a , >>> b [ ' O ' ] = >>> a { ' p ' : { ' y ' : { ' t ' : { ' h ' : { 'O ' : """ for c in sequence : d = d[ c ] i f p o s i t i o n i s not None : d = d [ position ] return d' '
89 pyth ' )
'
123 ' 123 ' ,'
o ': { 'n ':
{}}}}}}}
def pop u l a t e _ t r i e ( t r i e , sequence , p o s i t i o n =None ) : """ Populate a t r i e . Assume that the counter i s always at` `
position ` 0 while the
position ` o f the d i c t i o n a r y i s the l a s t one .
>>> t r i e = { } >>> p o p u l a t e _ t r i e ( t r i e , >>> t r i e = { } >>> p o p u l a t e _ t r i e ( t r i e , >>> t r i e = { } >>> p o p u l a t e _ t r i e ( t r i e , >>> t r i e = { } >>> t r i e = p o p u l a t e _ t r i e ( 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 ': kalo ' , 1)
{ 'k ': [1 , { ' a ': [1 , { ' l ': [1 , { ' o ': [1 , { } ] } ] } ] } ] } heh ' , 2)
{ 'h ': [1 , 0, { ' e ': [1 , 0, { 'h ': [1 , 0, { } ] } ] } ] } heh ' , 1)
ha ' , 1)
90 { 'h ': [2 , { ' a ': [1 , { } ] ,
7. e ': [1 , { 'h ': [1 , { } ] } ] } ] }
'
""" i f ( p o s i t i o n i s not None ) and ( p o s i t i o n >= 1 ) : embedded_obj = [ 0 ] else : embedded_obj = { } 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 . , *
position
embedded_obj . append ( { } )
7.5.
91
. . d (hides) . ,
d . . populate_trie , 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.
92
7.
8What can be said at all can be said clearly, and what we cannot talk about we must pass over in silence. Ludwig Wittgenstein
8.1 :
, Python.
Ludwig Wittgenstein , -
. ()
. ( ) . () 93
94
8. , , , . ( )
. ( ) . ( )
,
. ( ) . , , . , . ( ) , . . . , . :
: : Guido van Rossum : : Python
8.2.
95
:
(Class):
(attributes)
(methods) . .
(Object): , . .
(Instance): .
(Method): .
(Inheritance): , , . . . (elds) ((methods). . .
8.2
:
96
8.
class Snake ( ) : pass python = Snake ( ) class Snake(): Snake , 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.
97
, , , . 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 . """ # here we setup the a t t r i b u t e s o f our dog s e l f .name = name s e l f . color = color s e l f . height = height s e l f .mood = mood s e l f . age = age s e l f . hungry = False s e l f . t i r e d = False 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 " " " p r i n t ( 'Name i s ' , s e l f .name) p r i n t ( ' Color i s ' , s e l f . c o l o r ) p r i n t ( ' Height i s ' , s e l f . height ) p r i n t ( ' Mood i s ' , s e l f .mood) p r i n t ( ' Age i s ' , s e l f . age ) p r i n t ( ' Hungry i s ' , s e l f .name) p r i n t ( ' Tired i s ' , s e l f . t i r e d ) 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() -
98
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.
99
# one a d i c t i o n a r y which leads to the r e s t o f the nodes . s e l f . root = [ 0 , { } ]
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 , { } ] , """ # f i n d the node to append the new value . curr_node = s e l f . root for k in key : curr_node = curr_node [ 1 ] . s e t d e f a u l t ( k , [ 0 , { } ] ) curr_node [ 0 ] += 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 .
100
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 ) def __getitem__ ( s e l f , key ) : curr_node = s e l f . root for k in key : try : curr_node = curr_node [ 1 ] [ k ] except KeyError : yield None for k in curr_node [ 1 ] :
8.4. (attributes) yield k , curr_node [ 1 ] [ k ] [ 0 ] i f __name__ == a = Trie ( ) a . i n s e r t ( ' kalo ' ) a . i n s e r t ( ' kala ' ) a . i n s e r t ( ' kal ' ) a . i n s e r t ( ' kata ' ) prin t ( a . f i n d ( ' kala ' ) ) for b in a [ ' ka ' ] : print ( b ) prin t ( a )'
101
__main__ ' :
8.4
(attributes)
( ) (attributes) . ralph (instance) Dog, name, ralph.name. self . () . self.characteristic = . , print_attributes(). self . .
102
8.
8.5
(Member Functions). , . . . Python 3 : v a r i a b l e . member_function ( [ any arguments required ] ) , dir Python . a ='
Python by example '
p r i n t ( ' Member functions f o r s t r i n g ' ) print ( dir ( a ) ) 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.
103
Python . , Python. c = [ 1 , 2 , 3] print ( help ( c . s o r t ) )
8.68.6.1
8.6.1. ( ). . class Snake : noOfSnakes = 0 def _ _ i n i t _ _ ( s e l f , name = s e l f .name = name prin t ( ' I n i t i a l i z i n g { 0 } ' . format ( s e l f .name ) ) Snake . noOfSnakes += 1 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 ) python = Snake ( ' TasPython ' ) python . helloWorld ( ) Snake . numberOfSnakes ( ) cobra = Snake ( )'
unknown ' ) :
104 cobra . helloWorld ( ) Snake . numberOfSnakes ( )
8.
. , (__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). fun B a1.b1.fun(), a1 A. 2 a1.fun()1
8.7.
105
Python . . 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 ) ) class Professor ( UniversityMember ) : def _ _ i n i t _ _ ( s e l f , name, age , salary ) : UniversityMember . _ _ i n i t _ _ ( s e l f , name, age ) s e l f . salary = salary def who ( s e l f ) : UniversityMember .who ( s e l f ) p r i n t ( ' Salary : " { } " ' . format ( s e l f . salary ) ) class Student ( UniversityMember ) : def _ _ i n i t _ _ ( s e l f , name, age , marks ) : UniversityMember . _ _ i n i t _ _ ( s e l f , name, age ) s e l f . marks = marks def who ( s e l f ) :
106
8. UniversityMember .who ( s e l f ) p r i n t ( ' Marks : " { } " ' . format ( s e l f . marks ) )
p = Professor ( ' Mr. Sipser ' , 40, 3000000) s = Student ( ' Kosmadakis ' , 25, 9.99) 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.
107
__. . , Python operator overloading.
__init__(self, . . . ): . . (base class) __init__(), . , __init__()
__del__(self): . (destructor). , .
__repr__(self): repr() . , Python . debugging.
__str__(self): str() print(). __repr__() . .
__lt__(self, other), __le__(self, other), __eq__(self, other), __ne__(self, other), __ne__(self, other), __gt__(self, other), __ge__(self, other): (=). . , , .
108
8. __add__(self, other): (+) __sub__(self, other): () __mul__(self, other): () __truediv__(self, other): (/) __oordiv__(self, other): (//) __mod__(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() . , , . , , . 109
110
9.
open() 9.1. r w a b + ( ) ( ) r+ /
9.1:
r, w, a . , ( r.
9.29.2.1
read(). , bytes . f = open ( ' i n p u t _ f i l e . t x t ' ) # open , readonly ( d e f a u l t ) p r i n t ( f .name) # recover name from f i l e o b j e c t p r i n t ( f . readlines ( ) ) p r i n t ( f . readlines ( ) ) # already at end o f f i l e f . seek ( 0 ) # go back to byte 0 o f the f i l e p r i n t ( f . read ( ) ) # read to EOF, returning bytes in a s t r i n g f . close ( )
9.2.
111
readlines read, , , . , close() .
9.2.2
, , , open(). , . g = open ( ' n e w _ f i l e ' , 'w ' ) # open f o r w r i t i n g g . write ( ' A new f i l e begins ' ) # takes j u s t one argument g . write ( ' . . . today ! \n ' ) g . close ( ) , , . f = open ( ' f i l e . t x t ' , f . close ( )'
a')
f . write ( ' Append a new l i n e at the end o f the f i l e \n ' )
9.2.3
for (iterate), . f = open ( ' i n p u t _ f i l e . t x t ' ) # open , readonly ( d e f a u l t ) for l i n e in f : prin t ( l i n e )
112
9.
, . , , \n. , , . print , .
9.2.4
()
(serialization) , bits ( ) . . ( ) . , Python (module) pickle. pickle .
0:
1:
2: 2 Python
3:
( 3), . , .
9.3.
113
import p i c k l e write_data = [ 1 , 2.0 ,'
asdf ' , [ None , True , False ] ]'
with open ( ' data . p i c k l e ' ,
wb ' ) as f :
p i c k l e .dump( write_data , f ) with open ( ' data . p i c k l e ' ,'
rb ' ) as f :
read_data = p i c k l e . load ( f ) print ( read_data ) python . , (binary format), .
9.3
, . python , . os ( ) .
9.3.1
:
getcwd(): .
114
9. listdir(): . chdir(path): path.
(module) os. . . os.path.split() os.path.join() crossplatform , . import os abs_path = os . path . abspath ( os . path . curdir ) # os . path . j o i n i s used to append a r e l a t i v e path at the # end o f another path path2 = os . path . j o i n ( abs_path , " new_dir " ) p r i n t ( path2 ) # os . path . s p l i t " s p l i t s " the path in two pieces . # The path u n t i l the l a s t p r i n t ( path0 ) p r i n t ( path1 ) ( cross-platform) Python. import os p r i n t ( os . path . curdir ) # get current d i r e c t o r y ( Pythonic humor ) abs_path = os . path . abspath ( os . path . curdir ) # get i t s f u l l path p r i n t ( abs_path )'
cross-platform,
/ ' and whatever f o l l o w s
path0 , path1 = os . path . s p l i t ( path2 )
9.3. f u l l _ p a t h = os . getcwd ( ) print ( f u l l _ p a t h ) # get the t a i l end o f the path print ( os . path . basename ( f u l l _ p a t h ) ) # l i s t the contents o f the current d i r e c t o r y os . l i s t d i r ( f u l l _ p a t h ) # get information about f i l e . t x t
115
# the numbers below are : inode protection mode; inode number ; # device inode resides on ; number o f l i n k s to the inode ; # user id o f the owner ; group id o f the owner ; s i z e in bytes ; # time o f l a s t access ; time o f l a s t modification ; # " ctime " as reported by OS print ( os . s t a t ( ' f i l e . t x t ' ) )
s i z e = os . path . g e t s i z e ( ' f i l e . t x t ' ) print ( ' The f i l e s i z e i s :'
, size )'
i s d i r e c t o r y = os . path . i s d i r ( ' f i l e . t x t ' ) print ( ' I s f i l e . t x t a d i r e c t o r y : , isdirectory ) # time o f l a s t modification ( seconds since Epoch ) last_mod = os . path . getmtime ( ' f i l e . t x t ' ) print ( ' The l a s t time t h i s f i l e modified i s ' , last_mod ) , os.system(). import os os . system ( " l s " ) , -
116 .
9.
9.3.2
.
mkdir(path): path. makedirs(path): path , .
import os # remove new_dir i f already e x i s t s and i t i s empty i f os . path . i s d i r ( ' new_dir ' ) : os . rmdir ( ' new_dir ' ) os . makedirs ( ' new_dir ' ) p r i n t ( os . l i s t d i r ( ' . ' ) ) # change to subdirectory new_dir os . chdir ( ' new_dir ' )
10Success is not nal, failure is not fatal: it is the courage to continue that counts. Winston Churchill
10.1
( ) -
. , .
10.1.1. . , , . 117
118
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. . F i l e " " , l i n e 1 , in ZeroDivisionError : i n t d i v i s i o n or modulo by zero
119
(shell) Python, . , (, ), ( 1), (ZeroDivisionError, ) (int division or modulo by zero). , . >>> try : ... ... ... Could not make the d i v i s i o n , try , except. ( ZeroDivisionError), . . , : >>> a*
8/0 p r i n t ( ' Could not make the d i v i s i o n ' )
. . . except ZeroDivisionError :
5
Traceback ( most recent c a l l l a s t ) : F i l e " " , l i n e 1 , in NameError : name'
a ' i s not defined
120
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 " " , l i n e 1 , in TypeError : unsupported operand type ( s ) for' *
:
NoneType ' and
'
int
'
, , , . >>> with open ( ' 3BirdsAreSitting .mp3 ' , ... ... Traceback ( most recent c a l l l a s t ) : F i l e " " , l i n e 1 , in IOError : [ Errno 2] No such f i l e or d i r e c t o r y :' '
r ' ) as f :
f . read ( )
3BirdsAreSitting .mp3 ' with,
3BirdsAreSitting.mp3, with, , , . , except, , .
10.2. .
121
. . . except ( RuntimeError , TypeError , NameError ) : ... pass 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 . , myle.txt, . , . , , IOError err. . except , , except
122
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 , , try. . . except. . . .1
10.4.
123
. , int . , x while, break except ValueError, . break , . , print.
10.4
, Python. 1. try . 2. , except. 3. try , except. 4. except . 5. , . 6. , try . 7. , .
10.4.1 try:. . . else: . . ., . try . , Python else, if, .
124
10.
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 nally, nally, , . # how many times we have requested f o r input times = 0 while True : try : x = i n t ( input ( " Please enter a number : " ) ) break
10.5. except ValueError : p r i n t ( " Not a number . Try again . . . " ) finally : times += 1 print ( ' Requested input ' , times )
125
, , . , nally, , . .
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
126
10.
, Exception. Can you handle it?. as inst, . args , . __str__() .
10.5.2
(raise)
, BaseException. , , Exception. raise. >>> r a i s e NameError ( ' TesseraPoulakiaKa8ontai ' ) Traceback ( most recent c a l l l a s t ) : F i l e " " , l i n e 1 , in NameError : TesseraPoulakiaKa8ontai . >>> r a i s e NameError Traceback ( most recent c a l l l a s t ) : F i l e " " , l i n e 1 , in NameError
10.5.3
, Exception. >>> class MyError ( Exception ) :
10.6. if . . . else ... ... ... ... def _ _ i n i t _ _ ( s e l f , value ) : s e l f . value = value def _ _ s t r _ _ ( s e l f ) : return repr ( s e l f . value )
127
__init__, __str__ . , , . >>> try : ... ... ... My exception occurred : 4 >>> r a i s e MyError ( ' oops ! ' ) Traceback ( most recent c a l l l a s t ) : F i l e " " , l i n e 1 , in ? __main__ . MyError :'
r a i s e MyError ( 4 ) p r i n t ( 'My exception occurred : ' , e )
. . . except MyError as e :
oops !
'
10.6
if . . . else
. if . . . else. . 10.6.1. , . ,
128
10.
( ). , , . . from t i m e i t import Timer from random import randint VALUES = 10000 inverseprob = 2 d = d i c t ( [ ( x , y ) for x , y in z i p ( range (VALUES) , \ range (VALUES, 2*
VALUES ) ) ] )
class MyError ( Exception ) : def _ _ i n i t _ _ ( s e l f , value ) : s e l f . value = value def _ _ s t r _ _ ( s e l f ) : return repr ( s e l f . value ) def try_except ( d ) : try : d [ ' not ' ] except KeyError : pass
def i f _ e l s e ( d ) : if'
not ' in d : d [ ' not ' ]
else : pass
10.6. if . . . else
129
def try_exceptYES ( d ) : try : d[1] except KeyError : pass
def if_elseYES ( d ) : i f 1 in d : d[1] else : pass
def try_exceptMAYBE ( d , inverseprob ) : s = randint ( 0 , inverseprob ) try : i f s == 0: r a i s e MyError ( 2 ) d[1] except MyError : pass
def if_elseMAYBE ( d , inverseprob ) : s = randint ( 0 , inverseprob ) i f s == 0: return else : d [ 1 ]
def f a i l ( ) : prin t ( " Unsuccessful look up" )
130 t = Timer ( " try_except ( d ) " ,\
10.
" from __main__ import try_except , d " ) sf ='
Execution time with exceptions : { } seconds '
p r i n t ( s f . format ( t . t i m e i t ( ) / 10 * * 6)) t = Timer ( " i f _ e l s e ( d ) " ,\ " from __main__ import i f _ e l s e , d " ) sf ='
Execution time with i f / e l s e : { } seconds '
p r i n t ( s f . format ( t . t i m e i t ( ) / 10 * * 6))
def success ( ) : p r i n t ( " Successful look up" ) t = Timer ( " try_exceptYES ( d ) " ,\ " from __main__ import try_exceptYES , d " ) sf ='
Execution time with exceptions : { } seconds '
p r i n t ( s f . format ( t . t i m e i t ( ) / 10 * * 6)) t = Timer ( " if_elseYES ( d ) " ,\ " from __main__ import if_elseYES , d " ) sf ='
Execution time with i f / e l s e : { } 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 " ) sf ='
Execution time with exceptions : { } seconds '
p r i n t ( s f . format ( t . t i m e i t ( ) / 10 * * 6)) t = Timer ( " if_elseMAYBE ( d , inverseprob ) " ,\ " from __main__ import if_elseMAYBE , d , inverseprob " ) sf ='
Execution time with i f / e l s e : { } seconds '
10.6. if . . . else prin t ( s f . format ( t . t i m e i t ( ) / 10 * * 6)) def main ( ) : success ( ) fail () maybe ( )
131
i f __name__ == main ( )
'
__main__ ' :
132
10.
11A woodpecker can peck twenty times on a thousand trees and get nowhere, but stay busy. Or he can peck twenty-thousand times on one tree and get dinner. Seth Godin
, . ( , ), Python 3 .
, . ,
11.1
(Iterators)
, (iterators). , . mylist = [ 1 , 2 , 3]
133
134 for i in mylist : print ( i )
11.
(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.
135
11.2.1. iterators. , . , . .
range() (end) (start), modulo . def modulo_yield ( s t a r t , end , modulo ) : " " " Create a l i s t o f a l l the number from s t a r t _ { modulo } u n t i l end_ { modulo } i s reached . """ i f ( s t a r t > end ) : a = s t a r t % modulo b = ( end % modulo ) + modulo else : a = start b = end for num in range ( a , b ) : yield num % modulo start > end , . , yield for. ,
, , . Fibonacci . def f i b o n a c c i (num) : a = 0
136 yield a b = 1 yield b for i in range ( 2 , num) : b, a = a + b, b yield b for i in f i b o n a c c i ( 1 0 ) : print ( i )
11.
, lists comprehensions.
primes = [ 1 , 2 , 3 , 5 , 7] square_primes = ( i **2 for i in primes ) p r i n t ( next ( square_primes ) ) p r i n t ( next ( square_primes ) ) p r i n t ( next ( square_primes ) )
, , next(). next() StopIteraton . , . ( yield) . , yield.
11.3.
137
11.3
:
. , (on the y). , .
parsing . .
. Fibonacci.
, . , .. for, . : 1. len(). ( ) for . 2. ( ) .
138
11.
, : for i in range ( 0 , len ( l ) ) : e = l[i] ... : for i , e in enumerate ( l ) : ... .
11.4
, . , , ( , ). ( 1, 17). . 10 Fibonacci, 20, Fibonacci. . bonacci . 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. 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 # prints the element a f t e r 10 elements from the current print ( i t [ 1 0 ] ) # 10946
139
# prints the elements s t a r t i n g a f t e r where we had stopped print ( i t [ 2 : 1 2 : 2 ] ) # [46368 , 121393, 317811, 832040, 2178309]
140
11.
12I cant understand why people are frightened of new ideas. Im frightened of the old ones. Josh Cage
12.1
, , , -
.
object.
( )
(descriptors). (attributes) . , . . , 141
142
12.
x y . , getters setters . , . Python , . , .
12.212.2.1
. :
__get__(self, instance, owner) __set__(self, instance, value) __delete__(self, instance)
(attributes) :
: __get__(self, instance, owner). () AttributeError.
: __set__(self, instance, value).
: __delete__(self, instance).
12.2.
143
self () , .
owner: .
instance: ( ) . None .
value: .
144
12.
13 . : . .
GUI tkinter
. : 1. wxPython 2. pyQT 3. PyGTK 4. tkinter , Python. , tkinter (= Tk interface) Python, 145
GUI (Graphical User Interface) .
146
13. GUI tkinter
. Tcl/Tk. tkinter Tcl/Tk.
13.1
: from t k i n t e r import root = Tk ( ) w = Label ( root , t e x t = " Hello world ! " ) w. pack ( ) root . mainloop ( ) tkinter , , . (label) pack(). , . (mainloop) *
13.2
, . , , . , . , .
13.2.
147
from t k i n t e r import
* *
from t k i n t e r . messagebox import
class Calculator ( Frame ) : " " " Describes the main behaviour o f a c a l c u l a t o r """
def d_result ( s e l f , c ) : " " " Displays the r e s u l t o f an operation """ s e l f . label3 . c o n f i g ( t e x t = s e l f . label3 . pack ( )'
The r e s u l t i s
'
+ str ( c ) )
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 )
148 def d_mul ( s e l f ) :
13. GUI tkinter
" " " 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 """ c = a* *
b and return i t s r e s u l t
b
13.2. 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 ' , 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 ( ) ) # i f the f i e l d s were empty except ValueError : a, b = 0, 0 showinfo ( ' I n f o ' , return a , b' '
149
Cannot d i v i d e by 0. ' )
There are some empty f i e l d s ' )
def insertNum ( s e l f , l a b e l = " I n s e r t a number : " ) : " " " Draw the necessary elements f o r the i n s e r t i o n o f
150 two numbers """ # The f i r s t number
13. GUI tkinter
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 ( ) # the second number s e l f . label2 = Label ( s e l f , t e x t = l a b e l ) s e l f . label2 . pack ( ) # create the f i e l d f o r the new number s e l f . enter2 = Entry ( s e l f ) s e l f . enter2 . 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 . """ # draws the elements which are used to i n s e r t a number s e l f . insertNum ( ) # set the focus to enter1 s e l f . enter1 . focus ( ) # create the buttons s e l f . button1 = \ Button ( s e l f , t e x t = " add " , command = s e l f . d_add )
13.2. 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 ) # create the l a b e l where we display the r e s u l t s e l f . label3 = Label ( s e l f ) return root ;
151
def _ _ i n i t _ _ ( s e l f , master = None ) : """ The constructor i s c a l l e d with a parent widget . I t creates the GUI f o r the c a l c u l a t o r . """ Frame . _ _ i n i t _ _ ( s e l f , master ) s e l f . master . t i t l e ( " Calculator " ) s e l f . pack ( ) s e l f . drawGUI ( )
root = Tk ( ) calc = Calculator ( master = root ) calc . mainloop ( )
152
13. GUI tkinter
13.1: showinfo(Info, There are some empty elds.)
Entry Button .
13.3
pop-up , . print ( ). , tkinter.messagebox. , .
showinfo() askokcancel() showwarning() showerror() askquestion() askyesno() askretrycancel()
13.3.
153
13.2: askokcancel(Go on?, Would you like to quit?)
13.3: showwarning(Warning, A window detected!)
13.4: showerror (Error, Many windows have been detected!)
13.5: askquestion(Install, Would you like to install a door?)
13.6: askyesno(Taste, Would you like fries with that?)
154
13. GUI tkinter
13.7: askretrycancel(No media found, Would you like to try again?)
:
: : : . , .
, . from t k i n t e r import* *
from t k i n t e r . messagebox import showinfo ( ' I n f o ' ,'
There are some empty f i e l d s . ' )'
showwarning ( ' Warning ' , showerror ( ' Error ' ,'
A window detected ! ' ) Would you l i k e to i n s t a l l a door? ' )
Many windows have been detected ! ' )'
askquestion ( ' I n s t a l l ' ,
( , ), true false .
14All those who believe in psychokinesis raise my hand.
,
. , .
14.114.1.1
. . , . 155
156
14.
, .
14.1.2
(run time errors) ( , ).
14.1.3
, . . , !
14.2 Python Debugger debugger. Python debugger module, pdb1 . , debugger (print, log messages) . , Python
(debugger) . import pdb
. debugger,
debugger . :
1
Python DeBugger
14.2. Python Debugger (breakpoints)
157
Python.
14.2.1
, pdb.set_trace(). import pdb a = " taspython " b = " . eu\n" pdb . s e t _ t r a c e ( ) c = " Because s i m p l i c i t y matters " final = a + b + c print ( f i n a l ) pdb.set_trace(), n . n, enter . debugger q debugger c .
14.2.2
n, debugger , . s. n,
158
14.
, . s, r. , return ( ).
14.2.3
,
l p. . , Python . , , . , Python. , (!) debugger Python . p ,
14.2.4
14.1 debugger.
14.2. Python Debugger
159
import pdb pdb.set_trace() q p c l s r
debugger. (quit) (print) (continue) (listing) (step into) (return)
14.1:
160
14.
15The only reason for time is so that everything doesnt happen at once. Albert Einstein
.
, . . , , , . ; , . garbage collector , . , . Python, , 161
162
15.
, timeit. timeit, , . , , . , .
15.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
15.2.
163
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))
15.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 " ) sf ='
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