python tutorial greek
DESCRIPTION
tutorial by exampleTRANSCRIPT
-
Taspython
Python
Python
:
:
TasPython
-
pi pi pipi pi 2008 pi / & -, pi pi pipi , pi pipi -pi pi pi pi - pi . pipi , , pipi pi , pi .
, , pi pi pi - , , pi, pi pi pi pi. pi , pi pi, pi pi pi.
pi pi TasPython pi , -pi, pi.
pi, pi pi.
iii
-
iv
-
.
-
vi
-
1 1
1.1 . . . . . . . . . . . . . . . . . . . . . 21.2 pi . . . . . . . . . . . . . . . . . 2
1.2.1 pi pi . . . . . . . . . . . 31.2.2 pi . . . . . . 31.2.3 . . . . . . . . . . . . . . . . . . . . . . 41.2.4 pi pi . . . . . . . . . . . . . 51.2.5 . . . . . . . . . . . . . . . . . . . . . 51.2.6 . . . . . . . . . . . . . . . . . . . . 51.2.7 pi . . . . . . . . . . . . . . . . . . . . . . . . . . 61.2.8 pipi . . . . . . . . . . . . . . 6
1.3 Python . . . . . . . . . . . . . . . . . . . . . . . . . 61.3.1 . . . . . . . . . . . . . . . . . . . 91.3.2 Python 3 . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3.3 . . . . . . . . . . . . . . . . . . . . . . . . . 121.3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3.5 Zen of Python . . . . . . . . . . . . . . . . . . . . . . . 13
1.4 Python . . . . . . . . . . . . . . . . . . . . . . . . 141.4.1 . . . . . . . . . . . . . . . . . . . . . . . 141.4.2 pi Python . . . . . . . . . . 15
1.5 . . . . . . . . . . . . . . . . . . . . . . . . 18
vii
-
viii
2 21
2.1 pi . . . . . . . . . . . . . . . . . . . . . . . . . . 222.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.3 Boolean . . . . . . . . . . . . . . . . . . . . . . . . 242.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3 29
3.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293.2 . . . . . . . . . . . . . . . . . . . . . 303.3 . . . . . . . . . . . . . . . . . . . . . . . . 313.4 if . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.4.1 pi pipi . . . . . . . . . . . . . . . . . . 343.5 pi . . . . . . . . . . . . . . . . . . . . . . . 36
3.5.1 for . . . . . . . . . . . . . . . . . . . . . . . . 363.5.2 while . . . . . . . . . . . . . . . . . . . . . . . 38
3.6 break . . . . . . . . . . . . . . . . . . . . . . . . . 383.7 with . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.7.1 pi with . . . . . . . . . . . . . . . . . . . . . . 403.7.2 . . . . . . . . . . . . . . . . . . . . . . . 41
4 43
4.1 pi . . . . . . . . . . . . . . . . . . . . . . . . . 444.1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 444.1.2 . . . . . . . . . . . . . . . . . . . . 44
4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454.3 pi . . . . . . . . . . . . . . . . . 464.4 . . . . . . . . . . . . . . . . . . . . . . . . 47
5 49
5.1 . . . . . . . . . . . . . . . . . . . . . . . . . 505.2 pipi . . . . . . . 515.3 (Docstrings) . . . . . . . . . . . . 525.4 pi . . . . . . . . . . . . . . . . . . . . . 54
5.4.1 . . . . . . . . . . . . . . . . . . . . . . 545.5 . . . . . . . . . . . . . . . . . . . . . . 55
-
ix
5.6 (Decorators) . . . . . . . . . . . . . . . . . . . . 56
6 59
6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 606.1.1 . . . . . . . . . . . . . . . . . 60
6.2 . . . . . . . . . . . . . . . . . . . . . . . . . . 616.2.1 . . . . . . . . . . . . . 616.2.2 . . . . . . . . . . . . . . . 626.2.3 pi . . . . . . . . . . . . . . 636.2.4 . . . . . . . . . . . . . . . 646.2.5 . . . . . . . . . . . . . . . . . . . 64
6.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666.3.1 . . . . . . . . . . . . . . . . . . . . . 676.3.2 . . . . . . . . . . . . . . . 686.3.3 . . . . . . . . . . . . . . . . . 706.3.4 . . . . . . . . . . . . . . . . . . . . 706.3.5 (Lists comprehensions) . . . . . . . 716.3.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
6.5.1 . . . . . . . . . . . . . . . . . . . . 736.5.2 . . . . . . . . . . . . . . . . . . . 746.5.3 . . . . . . . . . . . . . . . . . . . . . . . 766.5.4 pipi . . . . . . . . . . . . . . . . 766.5.5 (Dict comprehension) . . . . . . . 776.5.6 . . . . . . . . . . . . . . . . . . . 77
6.6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786.6.1 . . . . . . . . . . . . . . . . . . . . . . . . 786.6.2 . . . . . . . . . . . . . . . . . 79
7 81
7.1 pi pi (immutable objects) . . . . . . . . . . . . . . . . 817.2 pi . . . . . . . . . . . . . . . . 837.3 . . . . . . . . . . . . . . . . . . . . . . . 86
7.3.1 . . . . . . . . . . . . . . . . . . . . . . . . 87
-
x
7.3.2 None . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877.4 . . . . . . . . . . . . . . . . . . . . . . . . . 887.5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 907.6 . . . . . . . . . . . . . . . . . . . . . 94
8 99
8.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 998.2 . . . . . . . . . . . . . . . . . . . . . . . . . 1018.3 . . . . . . . . . . . . . . . . . 1048.4 (attributes) . . . . . . . . . . . . . . 1078.5 . . . . . . . . . . . . . . . . . . . . . . . 1088.6 . . . . . . . . . . . . 109
8.6.1 . . . . . . . . . . . . . . . . . . . . 1098.6.2 . . . . . . . . . . . . . . . . . . . . . 110
8.7 . . . . . . . . . . . . . . . . . . . . . . . . . 1108.8 . . . . . . . . . . . . . . . . . . . . . . . . . 112
9 115
9.1 pi . . . . . . . . . . . . . . . . . . . . . . . . . . . 1159.2 . . . . . . . . . . . . . . . . . . . . . . . 116
9.2.1 pi . . . . . . . . . . . . . . . . . . . 1169.2.2 . . . . . . . . . . . . . . . . . . . . 1179.2.3 . . . . . . . . . . . . . . . . . . . . 1179.2.4 (pi) . . . . . 118
9.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1199.3.1 . . . . . . . . . . . . . . . . . 1199.3.2 . . . . . . . . . . . . . . . . . . . 122
10 123
10.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12310.2 . . . . . . . . . . . . . . . . . . . . . . . . . . 12410.3 pi . . . . . . . . . . . . . . . . . . . . . 12810.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
10.4.1try:. . . else: . . . . . . . . . . . . . . . . . . . . . . . . . 12910.4.2finally . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
-
xi
10.5 . . . . . . . . . . . . . . . . . . . . . 13110.5.1 . . . . . . . . . . . . . . . . . . . 13110.5.2 (raise) . . . . . . . . . . . . . . . 13210.5.3 pi . . . . . . . . . 132
10.6 if . . . else . . . . . . . . . . . . . . . . . . . . . . 133
11 139
11.1pipi (Iterators) . . . . . . . . . . . . . . . . . . . . . 13911.1.1 for . . . . . . . . . . . . . . 140
11.2 . . . . . . . . . . . . . . . . . . . . . 14011.3 pi . . . . . . . . 14311.4pi . . . . . . . . 144
12 147
12.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
13 149
13.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14913.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
13.2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . 150
14pi GUI tkinter 153
14.1 . . . . . . . . . . . . . . . . . . . . . . . . . 15414.2 . . . . . . . . . . . . . . . . . . . 15414.3 pi . . . . . . . . . . . . . . . . 160
15pi 163
15.1 . . . . . . . . . . . . . . . . . . . . . . . . . 16315.1.1 . . . . . . . . . . . . . . . . . . . 16315.1.2 . . . . . . . . . . . . . . . 16415.1.3 . . . . . . . . . . . . . . . . . . . . . 164
15.2Python Debugger . . . . . . . . . . . . . . . . . . . . . . . . . 16415.2.1 . . . . . . . . . . . . . . . . . . . . 16515.2.2 . . . . . . . . . . . . . . . . . . . . . . . . 16515.2.3 . . . . . . . . . . . . . . . . . 16615.2.4 . . . . . . . . . . . . . . . . . . . . 166
-
xii
16 169
16.1 . . . . . . . . . . . . . 17016.2 . . . . . . . . . . . . 17116.3pi garbage collector . . . . . . . . . . . . . . . . . 17316.4 . . . . . . . . . . . . . . . 17316.5pi . . . . . . . . . . . . . . . . . . . . 17516.6 (Profiling) . . . . . . . . . . . . . . . . . . 175
-
1
In times of change, learners will inherit theearth while the learned will find themselvesbeautifully equipped to deal with a world thatno longer exists.
Eric Hoffer
pi pi pi Python 3. - . pi pi- pi . pi pipi , -. pi :
Longum iter est per preaecepta, breve et efficax per exempla!
, pi pi. pi pi , pipi pi .
, pipi - pi .
1
-
2 1.
1.1
pi pi pi-, pi , pi pi - pi . pi- pi pi pipi . pi pi pi, pi - pi . pi pipi pi pi pi. pi pipi , pi pi , pi pi pi.
1. .
2. .
print ( 'Hello , World ! ' )
3. pi _.pi.
4. , pi _.pi.
pi, pi pi pi . pipi ,pi pipi pi , pi -.
1.2 pi
Python pi pi pi pi pi. pi pi Linux pi web applications ( pi Django). pi , pi pi pi
-
1.2. pi 3
pi pi pi, pi . pi pi .
1.2.1 pi pi
pi, pi . pi pi pi. pi pi pi-, (compile)1 pi pi pi, pi, pi . pi pi, pi pi pi pi, , pi pi pi pi pi pi pi .
pi pi pi- pi . pi pi pi . pi pi .
1.2.2 pi
pi , , -pi, . pi pi-, pipi pi pi pi- pi . pi pi pi pi , - pi pi pi pi. pi pipi , pi pi pi pi, pi-
1 pi
-
4 1.
. , pi pipi (pi pi ), pi , pi pipi.
pi , pi, pi pi . pi , pi pi pi pi pi . pi , pi pi pi, pi pi pi pipipi.
1.2.3
pipi pi , . !, pipi pi . pi pi, . pi pi , pi pi . pi pi, pipi pipi . pi , pi pi . pi pi . , pi pi pi !
pi pi , pi , pipi pi pi . , - pi pi , pi pi pi pi pi . , pipi pi ! pipi , pi pi !
-
1.2. pi 5
1.2.4 pi pi
pi pi pi pi pi. pi pi- pi pi pi, - pi pi pipi. pi pi pi pi pi pi . pi pi pi . - pipi pi pi pi pi pi pi pi - pi pi pi pi pi.
1.2.5
, -, pi . pi . pi . pi pi pi -. pi pi pi , Python - pi pi pi pi . pi . pi, pi, pi . pi .
1.2.6
pi . pi pi pi . pipi pi, pi pi . pi , pi pi pi pi pi.
-
6 1.
1.2.7 pi
pi (compiler) - pi pi . . . pi pi pi , pi pi .
pi, pipi . pi pi pi , pi pi pi-pi. pi, pi pi pi pi . pi , -pi pi , pi pi pi pi pi .
1.2.8 pipi
pi pi . pi pi - pi . , , pi . Python pi . -pi pi , pi pi pi . pi- pi pi (bugs), pi pi .
1.3 Python
Python , pipi (semantics). (standard library). :
-
1.3. Python 7
(pi , )
pi
pipi
pi
pi
pi segmentation faults
pi pi pi - Python pi pi . , pi pipi pi- pi pi . pi pipi pi . pi , pi - pi pi . pi, pi pi- pi, pi pi pi.
pipi Python pipi pi - pipi (pi C, C++) pi
-
8 1.
Python 3 5 Ja-va. pi pipi pi , pi pi . pi pi pipi ( -pipi ) pi pi. pi pi-. pi pi pi pi pi pi (efficiency), pi pi pi (productivity).
pi pi pi pi pi pi pi pi -pi, . (interpreters) (compilers). pi pi pi pi - pipi pi pi . pi pipi pi pi pi pi - (virtual machine) pi (pi Python). pi , pi pi, pi (bytecode). pi pi pi - (object code).
pi pi pi pi pi . pi pi pipi pi, pi pi pi pi. pi pi pi pi - pi pi pi pi pi pi , pi pi pi-pi pi .
pi pi pi , pipi (modules)pi pi , pi , pi pi (pi 3 Python pi
-
1.3. Python 9
pi pi ). pi pi, -
pi pi pi (pi Windows, Linux/U-nix, OS/2, Mac, Amiga). pi-, pi Java, pi Jython pi pi- Java, .NET pi pi pipi IronPython pi Microsoft. , pi - C/C++ (modules) pi pipi Python.
pipi, pi . pi pi - 1980 pi pi pi . pi, pipi pi pi pi pi pi .
, pi pi pi pi, Python segmentation faults. pipi, Python pi pi (throw) pi pi pi pi pi.
pi - pi pi pi . pi, Python pi - pi pi pi . (reference counting).
1.3.1
Python, pi . , (generators), , pi ., pi pi pi pi , pi pi pi pi pi (pi , ..).
-
10 1.
, pi, , , ( pipi -) pi pi pi pi. pi- pi pi Python pipi pi pi pi , pipi- pi pi pi pi pi.
, , pi pi, , pi pi . pi,pi pi pipi pi pi pipi pi - pipi pi pi -pi . pi pi (Python Enhancement Proposal (PEP)) pi pipi (pi pi PEP 8 PEP 257)
1.3.2 Python 3
Python pi pi, pi pi 1980. pi pi pi pi pi , pi pi pi pi pi pi pi pipi pi pi ( pi 2 import this) pi . pi pi :
7 / 4 = 1 pi pi C.
range (pi )
2 Linux pi python3 pi , Windows IDLE.
-
1.3. Python 11
pi print statement pi pipi pi pi pi pipi.
pi pi pi pi pi pi pi pi pi.
pi Unicode pi ( ) pipi.
... .
pi pi pi pipi, pipi pi pi. pi Python - 3 ( py3k 3000). , pi pi pi pi pi pi-.
pi pi :
7 / 4 = 1.75 ( // pi -)
. - pi range pi pi 3 pi.
print
pi Unicode, pi pi-pi.
...
pi Python.
3pi 11.2.
-
12 1.
1.3.3
pi pi pi pi 2 :
2to3
3to2
python -3
pi pi pi 2 3 , . pi pi- Python (2.6+) pi pi pi 3 Python.
pi pi -, pi PEP 3003 (Python Enhancement Proposal) pi- pi 2 pi pi Python pi pi (CPython)(pi pi Jython, Pypy, IronPython) pi pi .
1.3.4
pi pi Python, pi pi :
Google (pi Google App Engine)
NASA
Yahoo!
pipi (MIT, Stanford ).
linux.
... pi !
-
1.3. Python 13
pi pi -pi Python, pi :
1. pipipi (prototyping)
2.
3. Scripting
4. pi
5. pi
6. pi
7. ... pi !
, pi pi pi pi . pi- pi pi Python pi.
1.3.5 Zen of Python
Zen of Python Python pi Tim Peters. pipi pi pi :
import this
pi . pi .pi pi . pi pipi.pipi pi . pi pi. . pipi pi -
.
-
14 1.
pi pi . pipi pi pipi. pipi . pi , pi . pipi pi pi pi pi
. pi pi pi
. pi pi. pi pi . pi , . pi , . (namespaces)
pi pi !
1.4 Python
1.4.1
Python pi pi pipi pi. , pi pi ( pi pi). pi pi pi .
Linux
Linux pi package manager pi -pi, ( pi pi). , pi, pi - , pipi pi pi pi pi. , Python 3. - pi .
-
1.4. Python 15
, pipi pi pi . , , pi ( IDLE).
Mac, Python . , - pipi , pi- pi . pi pi. , pi- Applications / Utilities / Terminal Python., , 3 pipi .
1.4.2 pi Python
pi Python .py. pipi pi pi pi pi- . pi pipi pi .py pi . pi pi pi pi pi:
>>> a = 5>>> b = 6>>> a + b11
pi pi (interpre-ter), pi pi ( Linux, > > cmd Windows) python ( python3 - pi ). pi >>> pi pi pi , pipi pi pi .
-
16 1.
Windows
pi pi pi pi - pi pi python.
1. Python PATH. ,pi -> -> pi -> (Control Panel -> System -> Advanced ->Environment Variables) (path) pi - Python. pi pi- pi (command line) python o-noma.py.
2. IDLE ( pi pi py-thon pi ). pi (File > Open). pi, pi Run Module> Run pi pi .
pi pi pi Notepad Wordpad. , pi Note-pad++ pi .
Linux
1. pi path pi pi . pi python3 onoma.py 4.
2. pi pi pi ,
#!/usr/bin/env python3
pi 4 python 3 python3 pi
/usr/bin
-
1.4. Python 17
#!/usr/bin/python3
pi pi pi pi- . pi pi #/usr/bin/env python3 pipi pi Python 3 pi ( /usr/bin/python3) pi- pi . , pi . , , pi pi .
pi
PEP5 8 pi pi pi pi- pi Python, pi tab pi , pi pi pi (indent) .6
"Unknown option: -", pi pi -. Unix . pi pi pi - .
1. Notepad++
Tabs: Settings > Preferences > Edit Components > Tab settings.
Settings > Preferences > MISC > auto-indent.
: Format > Convert, Unix.
2. JEdit
: pi U W M , pi- U
5PEP: Python Enhancement Proposal. pi - , pi, pi ..
6 pi pi PEPs pi http://python.org/dev/peps/.
-
18 1.
3. Mac TextWrangler
Tabs: pi pi pi pi pipi Auto Expand Tabs. pi pi-pi pi Defaults > Auto-Expand Tabs Defaults >Auto-indent.
: pi, pi- Unix.
pi pi pi pi -. Windows, pi IDLE ( ) pi pi, pi Eclipse pydev. Linux pi kate gedit, pi pi pi Eclipse. pi pi pi (pi ). pi , pi pi pi .
1.5
: 1 pi pi
pi pi Python. 2 pi pi pi -
pi pi. , pipi .
3 , pi- pi pi pipi pi.
4 pi - pi pi pi.
5 pi pi pi pipi - pi.
-
1.5. 19
6 pi : pi pi pi pi pi.
7 Python - pi pi pi pi.
8 - pi pi: . pi pi .
9 pi . pi, pipi pi pi pi .
10 pi pi pi pi pi pi pi pi pi .
11 pi pi Python, pi .
13 pi pi pi .
14 pi pi pi pi pi pi pi (tkinter) pi pipi Python.
15 pi pi- pi pi .
, 16 pi pi pi pi ( pi-).
-
20 1.
-
2
pi, , , pi : pi pi.
pi ,
pi pi -pi pi. , pi pi pi pi .
pi pi - pi pi pi . pi - , pi pi, . pi,pipi pi pi pi pipi pi - pi pipi pi. , Structure and Interpretation of Computer Programs :
1. , pi pi pi - pi .
21
-
22 2.
2. pi pi - pi pi.
3. pi pi - .
pi pi pi pi -.
2.1 pi
pi pi, pi -. , pi Python .
2.1.1. pi bit pi - pi pi . pi bits pi -pi .
2.1.2. pi pi .
pi pi pi pi pi. print pi pipi pi . pi- , pi pi pi pi . pi pi pi pi, pipi . pi , pi, pipi, pi pi.
print (1 )print ( 'asdf ' )primeNumbers = 1, 2 , 3 , 5 , 7print (primeNumbers )
Python pi pi.pi pi pi,
-
2.2. 23
, . pi dynamic typing. pi, pi pi Python pi pi. pi. pi pi pi :
a = 'asdf 'a = 2a = pow(a , 100000)print ( a )
pi pi pi a pi - pi pi pi pi pi .
2.1.3. pi pi (dynamicallytyped), pi pi pi . pi pi, pi pi pi pi pi . , pi - pi Python pi .
2.2
2.2.1. pi pi -. pi pi . pi pi , .
num = 17pi = 3.14paei = 'Allou 'paei = 'Molis gyrise '
-
24 2.
pi pi -. , pi pi , pi . , - pipi pi . , ,pi pi pipi pi pi.
pi , pi - . pi pi- pi pi 3.14 pi pi .
pi = 3.14print ( pi 2)
2.3 Boolean
2.3.1. Boolean pi pi .
5 == 5 ()
5 == 6 ()
True and False ()
True or False ()
pi Boolean pi - pi . pi- pi pi pi pi pi. Boolean :
not
or
and
-
2.3. Boolean 25
pi pi pi pi pipi pi.
2.1: not
a b
2.2: and
a b
2.3: or
pi pi pi pipi pi ( pi and), pi (pi- or) (pi not pi pi and)1. pi.
1 De Morgan pi pi .
-
26 2.
>>> a = 5>>> b = 4>>> a > bTrue>>> c = 6>>> a > b and a > cFalse>>> a > b or a > cTrue>>> a > b and not a > cTrue>>> a > b or not a > cTrue>>> not a > b or not a > cTrue>>> not ( a > b ) or a > cFalse>>> not a > b or a > cFalse
2.4
pi Boolean ( ) pi pi pi pi- .
2.4.1. pi pi pi- pi pi pipi. pi .
, pi pi pi 5. pi pi :
-
2.4. 27
(+)
()
pi ()
(/)
()
pipi (modulo) (%)
. pi - . Python pipi .
(==)
pi (! =)
pi (>)
pi (=)
(
-
28 2.
-
3
It is not enough to do your best; you mustknow what to do, and then do your best.
W. Edwards Deming
3.1
pi pi . pipi pi. 3.1.1. pi pi- pi pi ( ). pi pi pi pi -pi pi. pi :
: pi pi pi pi- pi pi .
pi : pi pi pi ( , , pi).
: pi.
29
-
30 3.
! Python ! pi pi :
IndentationError : expected an indented block
pi . pi pi tabs
pi pi . pi pi tabs pi pipi. pi pipi pi, PEP8 .
pi pi pi pi . pi, pi pipi . pi pi , pi . pi, Python pipi pi pi .
3.2
3.2.1. pi , pi.
, - pi pi, pi pi . pi- pi - pi. pi . pi pi pi- . pi pi sequential, pi . pi pi:
print (123)
-
3.3. 31
print ( )print ( 'Hello ' , end= ' ' )print ( 'World ' )
print() pi pi, pi pi-pi, pi . pi end pi pipi pi pi pi .
pi pi pi , - pi pi pi pi pi (program counter). pi pi pi pi pi pi .
3.3
3.3.1. :
(statement) (unconditional branchor jump).
pi pi -.
pi pi pi.
pi pi pi (, ).
pi, pipi pipi pi.
-
32 3.
3.4 if
pi pi- , pi if pi . pi , pi pi - if , pi pi if.
answer = int ( input ( 'What is the product of 2 5: ' ) )
i f ( answer == 10):print ( 'Correct ! ' )
print ( 'Exiting program ' )
pipi , pi-pi pi pi pi . pipi pi :
What is the product of 2 5: gTraceback (most recent ca l l last ) :
F i le "" , l ine 1, in ValueError : inval id l i t e r a l for int ( ) with base 10: 'g '
pipi g int(), pi pi , pi ValueError. pi pi pipi . .
pi - , pi pi if...else....
from math import sqrt
-
3.4. if 33
a = f l oa t ( input ( " Coef f ic ient of the x^2: " ) )b = f l oa t ( input ( " Coef f ic ient of the x : " ) )c = f l oa t ( input ( "Constant : " ) )
i f a == 0:print ( " This is not a 2nd degree equation " )import sysex i t ( )
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 )
sf = "x1 = {0 } , x2 = {1 } "print ( s f . format ( x1 , x2 ) )
pi pipi pi pi - . pi pi -pi. pi pi pi pi
: x1,2 = +
2, pi = 24. -
pi (pipi pi pi if 1 (pipi pi else).
1 pipi pi 0 pi pi , pipi pi pi .
-
34 3.
3.4.1 pi pipi
if...elif...else...
Python, pi switch pi pi- pi k , pi k pi pipi pi pi switch. switch pi pi C/C++ Java. Py-thon, pi pi if...elif...else.... pi :
x = int ( input ( " Please enter an integer : " ) )i f x < 0:
print ( 'Negative number, transforming into posit ive ' )x = x # make i t posi t ive
# Be careful , because the fol lowing statements w i l l be# examined only i f the f i r s t condition is false , they# won ' t be executede l i f x == 0:
print ( 'Zero ' )e l i f x == 1:
print ( 'One ' )else :
print ( 'Great than 1 ' )
pi pi, elif pi pi , .
pi switch, . Python pi pi pi pi pi pi pi .
pipi (key) . pi pi pi pi -
-
3.4. if 35
, pi pi, pi pi.
# Sample functionsdef square ( x ) :
return x2
def double ( x ) :return x2
opdict = { "a" : square , "b" : square , " c " : double }
# Example (random access O( 1 ) )print ( opdict [ "b" ] ( 5 ) )
# Example 2 ( checking everything )for operation in "abc" :
print ( operation , opdict [ operation ] ( 3 ) )
pi pipi if...elif...else.... pipi pi, pi pipi, pi pi pi .
pi, pi pipi , pi pipi pi pi pi pi.
# Sample functionsdef square ( x ) :
return x2
def double ( x ) :return x2
def decrease ( x ) :return x1
-
36 3.
opdict = { "a" : square , "b" : double , " c " : decrease }
try :print ( opdict [ "d" ] ( 5 ) )
except KeyError :print ( ' Inval id use of index ' )
# Example 2 ( checking everything )for operation in "abc" :
print ( operation , opdict [ operation ] ( 3 ) )
3.5 pi
pi , pi pi . ( ) pi, . pi, for while pi.
3.5.1 for
for pi . - pi range(). , range() pi , - .
pi pi pi 20 pi Fibo-nacci. pi pi pi pi n- Fibonacci Fn = Fn1 + Fn2 pi F0 = 0 F1 = 1.
# the 2 f i r s t f ibonacci numbers are always knowna , b = 0, 1# print the f i r s t f ibonacci number ( a )print ( a , end= ' ' )
-
3.5. pi 37
# find the next 18 fibonacci numbers and print themfor i in range (18 ) :
print (b , end= ' ' )a , b = b, a + b
# print the last fibonnaci number ( of t o ta l l y 20)print (b )
pi i pi pi 0 17, pi 18 . 2
range() . pi pi range() , pi pipi.
>>> for i in range(100 , 120):. . . print ( i , end= ' ' ). . .100 101 102 103 104 105 106 107 108 109 110111 112 113 114 115 116 117 118 119
>>> for i in range(100 , 120, 2 ) :. . . print ( i , end= ' ' ). . .100 102 104 106 108 110 112 114 116 118
pi pipi pi [100, 120) pipi pi - [100, 120) 2, pi pi .
pipi pi pi .
2 , pi .
-
38 3.
3.5.2 while
for, while pi .
def f i b ( a , b ) :sum = 0;while a < 4 (10 6 ) :
sum += aa , b = b, a + b
return sum
a , b = 0, 1print ( f ib ( a ,b ) )
pipi pi pi Fibonnaci pi pi 4 106.
3.6 break
break pi pi pi - . pipi pi pipi, pi if pi pi .
pi break pi . pi . pi , pi pi pipi.
pi pi pi pi- Zn pipi (modulo). 0, pi pi pi pi .
def printSubgroups (n ) :" " "Prints a l l the subgroups of Zn
-
3.7. with 39
" " "for i in range (0 , n ) :
print ( '< ' , end= ' ' )print ( i , end= ' >: ' )for j in range (1 , n + 1 ) :
num = ( i j )%nprint (num, end = ' ' )i f (num % n) == 0:
break
print ( ' , ' , end= ' ' )print ( )
3.7 with
3 Python, with pi , pi .
pi pi pi.pi with , pi with pi . pipi, block with. with pi pi pi pi pi .
filename = "CanadaSong. txt "
data = " " " \First 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 :
-
40 3.
fout . write ( data )
, pi with, filename, . pi pi , . , pi with pi pi.
3.7.1 pi with
with pi pi pi pi pipi, pi with -. pi pi pi . pi - pi , pi pi pi pi.
# every l ine containing these words won ' t be written# at the outputexclude_class = [ 'not ' , 'negation ' ]
with open ( ' i n f i l e ' , ' r ' ) as f1 , open ( ' out f i l e ' , 'w ' ) as f2 :# for each l ine in the input f i l efor l ine in f1 . readlines ( ) :
# by default write a l ine to the out f i l e unless# i t doesn ' t contain one of the excluded wordswr i t e_ to_ f i l e = True# for each word in a l ine of the input f i l efor word in l ine . sp l i t ( ) :
# i f this word doesn ' t belong to closed_classi f word . rstr ip ( ) in exclude_class :
wr i t e_ to_ f i l e = Falsebreak
i f wr i t e_ to_ f i l e :
-
3.7. with 41
f2 . write ( l ine )
3.7.2
pi pi pi __en-ter__ __exit__, with pi pi __enter__ pi, - pi pi pi pi , __exit__.
pipi pipi. pipi pi pi pi pi with __exit__, pi pi pipi pi ( , pi). pi pi pi with, pi pi pi - __exit__, pi. pipi pi pi pi .
-
42 3.
-
4
And there was huge numbers of UFOs aroundmy parents home in Kingston.
Betty Hill)
Python pi - pi . pi pi pi- : pi (scripts). pi scripts. pi.
Python pi pi pi, pi- , pi pi pi pi. , - pi . - pi pi (overflow). pi pi pi - .
python pi pi pi pi, pi:
43
-
44 4.
python
. pi pi- , pi ctrl+d Linux/BSD ctrl+z Windows.
4.1 pi
pi (pi, , pipi, ) -pi (+,, , /)
>>> 3+811>>> 385>>> 3824>>> 3/80.375
4.1.1
pi . pi pi pi ( ) pi pi pi .
>>> 7/23.5>>> 7//23
4.1.2
pi , pi pi pi .
-
4.2. 45
>>> 2101024>>> 386561
pi pi -pipi n (modn ), python pi (modular exponentiation) , pi pi . , pi pipi. pi, pi pi 21024, pi 1024 pi 1000 pipi. Python pi pi pi.
>>> pow(2 , 1024, 1000)216
4.2
pi pi , :
1. d:
2. b: ( bin())
3. o: ( oct())
4. x: ( hex())
, pi pipi pi- pi pi pi .
-
46 4.
print ( ' value = {0:2d } ' . format (12 ) ) # value = 12print ( ' value = {0:2b } ' . format (12 ) ) # value = 1100print ( ' value = {0:#2b } ' . format (12 ) ) # value = 0b1100print ( ' value = {0:2o } ' . format (12 ) ) # value = 14print ( ' value = {0:#2o } ' . format (12 ) ) # value = 0o14print ( ' value = {0:2x } ' . format (12 ) ) # value = cprint ( ' value = {0:#2x } ' . format (12 ) ) # value = 0xc
print ( ' value = {0 :5 } ' . format ( bin ( 1 2 ) ) ) # value = 0b1100print ( ' value = {0 :5 } ' . format ( oct ( 1 2 ) ) ) # value = 0o14print ( ' value = {0 :5 } ' . format ( hex ( 1 2 ) ) ) # value = 0xc
4.3 pi
pi pi, pi pi (specifier) f . pi pi pi pi pi pi . pi, +, pi pipi .
pi.
print ( 'x = {0:5.3 f } ' . format (1234.567)) # x = 1234.567print ( 'x = {0:12.6 f } ' . format (1234.567)) # x = 1234.567000print ( 'x = {0:12.9 f } ' . format (1234.567)) # x = 1234.567000print ( 'x = {0:+12.9 f } ' . format (1234.567)) # x = +1234.567000print ( 'x = {0:+12.9 f } ' . format(1234.567)) # x = 1234.567000print ( 'x = {0:012.3 f } ' . format (1234.567)) # x = 00001234.567print ( )print ( 'x = {0:1.5 e } ' . format (1234.567)) # x = 1.23457e+03print ( 'x = {0:1.5 e } ' . format(0.000001234)) # x = 1.23400e06print ( 'x = {0:1.5g } ' . format(0.000001234)) # x = 1.234e06print ( )print ( 'x = {0:2.3%} ' . format (0.337) ) # x = 33.700%print ( )
-
4.4. 47
print ( ' pi = {0 : .3 f } ' . format (math. pi ) ) # pi = 3.142print ( ' pi = {0 : .8 f } ' . format (math. pi ) ) # pi = 3.14159265
4.4
pi pi pi pi (pi, -, pipi). pi - complex. , pi pi pi pi .
a = complex (1 , 1)b = complex (1 , 2)print ( a+b )print ( ab )
-
48 4.
-
5
pi , ( pi) pi pi pi. pi pi .
pi , , pi -. pi - pi pi, pi pi pipi . -, pipi pi pi - . pipi, .
pi pi Python pi -. pipi pi pipi , pi, pipi . pipi, pipi pipi , pi - pi . , pi
49
-
50 5.
pi , pi pi pi, pi pi .
5.1
5.1.1. -pi pipi pi. pi pi pi pi .
, .
5.1.2. pi pi pi pi . pi pi pi pi pi .
pi pi pi .
5.1.3. pi pi pi pi pi pi return. return, pi pi pi pi .
pi pi pi pi. ,pi pi pi .
def add ( a , b ) :c = a + b
return c
print ( add (2 ,3 ) )
pi pi pi pi pi.
-
5.2. pipi 51
from math import c e i l
def fun2 ( c ) :a = c // 2b = c a
return a , b
d, e = fun2 (7 )print (d , e )
pi :
1. pi , . pi def .
2. pi (:). - , pi pi pi .
3. pi (pi) ( ). pi pi pi -.
5.2 pi-
pi
(Pure Functions) pi pi pi . , pipi (modifier functions) pi pi- pi . - pi (side effects), pi pi pi pi, pi .
-
52 5.
a = 'Python 'print ( a .upper ( ) )print ( a )
pi , upper() pi pi . , pi string pi pi a.
, pi (mutable), pi , pipi. pi, pi pi, count() pi b, reverse()pi pi pi .
b = [ 'a ' , 'b ' , 'c ' , 'd ' , ]print (b . count ( 'a ' ) )print (b )print (b . reverse ( ) )print (b )
5.3 (Docstrings)
, pi . pi, pi pi pi pi pi . Python, pi , - pi pi pi pi pipi pi .
def f ibonacci (n ) :" " " Return the nth Fibonacci number counting from 0. " " "
# we should have used the closed formula for fibonacci# TODO: throw an error for negative numbers
-
5.3. (Docstrings) 53
i f n >> help ( fibonnaci )>>> print ( f ibonacci . __doc__ )
pi pi pi pi pi pi pipi . pi , pi __doc__ pi pi pi Python. , pi Python .
-
54 5.
5.4 pi
pi pi pipi. pi pi pipi pi pi - . pi pipi , pi pi pi.
def hello (message= 'Hello World ! ' ) :print (message )
hel lo ( )hel lo (message= 'Hello Brave New World ! ' )
5.4.1
pi pi . pi- pi. pi pipi pi pi pi .
, pi pi tuple - .
>>> a = (1 , 2 , 3 , 4)>>> def add ( a , b , c , d ) :. . . return a + b + c + d. . .>>> add(a )10
pi pi -. pi , .
pi pi ,pi pi ( )
-
5.5. 55
pi . pipi pi .
b = { 'a ' :2 , 'c ' : 3 , 'd ' : 5 , 'b ' : 1 }
def print_variables ( a , b , c , d ) :print ( 'a : { } ' . format ( a ) )print ( 'b: { } ' . format (b ) )print ( 'c : { } ' . format ( c ) )print ( 'd: { } ' . format (d ) )
print_variables (b )
pipi varargs default arguments (pi ) Python.
5.5
pi pi pi- pi . pi - pi pi pi - . , pi . pi pi pi .
pi lambda pi . pi pi . , lambda - def. pipi -1 pi pi . , pi , pi return. pi pi pi-.
def double ( x ) :return x x
1 .
-
56 5.
def print_results ( f , args ) :print ( f ( args ) )
print_results ( double , 5) # prints 25print_results ( lambda x : x x , 5) # prints 25
5.6 (Decorators)
pi pi -pi pipi pi . pi pi - pi , pi - pi (randomized algorithm).
pi pi Python pi . pi, pi pi- . pipi pi pi . , - , . pi pi, pi pi pi- . pi, pi pipi pipi pi pi .
Python pi pipi pi pi pipi pi - pi . pi , pi- pi pi. pi pi pi pipi , pi (decorators).
def makebold ( fn ) :def wrapped ( ) :
return "" + fn ( ) + ""
-
5.6. (Decorators) 57
return wrapped
def message ( ) :return "TasPython Guide"
message = makebold (message )print (message ( ) )
pi g pi-pi f . g f . pi , pi makebold() - wrapped(). pipi wrapped() . pi - pi . pi, pi fn wrapped() pi pi . wrapped() pi pi pi pi ,pi pi makebold().
pi message make-bold(message). pi pi pi, Python .pi, makebold(message) pi message. pi message pi pi pipi pi-, pi pi pi , pi.
pi makebold(), pi - wrapped(). wrapped() pi makebold() string pi pi fn pi . - pi pi. pi , pi pi .
, pi pi pi - pi pi .
def makebold ( fn ) :def wrapped ( ) :
-
58 5.
return "" + fn ( ) + ""return wrapped
@makebolddef message ( ) :
return "Python Guide"
print (message ( ) )
pi , pi pipi,pi message() pi pi pi pi pi pi pi- , pi . pi pi, pi message(), pi pi pi pi makebold.
-
6
There is no abstract art. You must alwaysstart with something. Afterward you canremove all traces of reality.
Pablo Picasso
pi pi pi - pi. pi pi pi pi pi pi. pi pi pi pi -pi. , , pi pi pi pi pi pi - pi , pi pi Python pi . pi, pi pi pi pi pi.
59
-
60 6.
6.1
6.1.1
(Strings): pi (quotes). - immutable pi .
'This is a string '
(Tuples): pi , pi pi pi pi pi pi pipipi . .
( 'These ' , 3 , 5.711, True , 'Prime ' )
(Lists): [ ]. pipi pi pi. - pipi (mutable).
[ 'These ' , 3 , 5.711, True , 'Prime ' ]
(Dictionaries): { } pipi . ( ) pi pi :
key: pi . value: pi , pi
pipi pi pi .
{ 1 : 'alpha ' , 2: 'beta ' , 3: 'gamma ' , 4: ' delta ' }
(Sets): , pi set . pi pipi pi. pi pi pi
-
6.2. 61
pi pi pi ( (union), (in-tersection), (difference), pi (issuperset), pi-(issubset)) pi (add), (remove) .
pi 6.1 pi pi pi pi pipi.
(string)
(tuple) pi .pi pi pi .
pi . (list) pi pi .
(dictionary) keys. pipi . pi
6.1: pi
6.2
6.2.1
, pi pi , pi pi pi pi . , pi pi pi pi. pipi pi UTF-8.
# the variable myString points to an immutable stringmyString = 'This is a string . '
pi (sequence). pi , pi pi pipi.
-
62 6.
myString = 'This is a string . '# the f i r s t character of myStringprint ( myString [ 0 ] )# the second character of myStringprint ( myString [ 1 ] )print ( myString [ 2 ] )print ( myString [ 3 ] )# prints the last character which is ' . 'print ( myString [ len ( myString ) 1 ] )
pi pipi pi pi pi () pi pi (index).
# the variable myString points to an immutable stringmyString = 'This is a string . '# the last character of myString# prints ' . 'print ( myString [1])# prints 'g ' .print ( myString [2])# prints 'n ' .print ( myString [3])
6.2.2
pi pipi ,pi pi pi pi- pi pi . , pi pi pi .
def reverse ( text ) :return text [ : :1]
-
6.2. 63
sentence = input ( 'Enter your text : ' )
invert = reverse ( sentence )
print ( 'The inverted text is : ' , invert )
pi pi, pi pi . pi :
def reversepart ia l ly ( text ) :return text [3:1:1]
sentence = input ( 'Enter your text : ' )
invert = reversepart ia l ly ( sentence )
print ( 'The inverted text is : ' , invert )
pi pi pi 3, pi 2, pi -. pi pi Python, pi pi pi, pi 0.
6.2.3 pi
pi pi string.format(). python, strings pipi- pi pi .
pi pi pi pi ,pi {x}, pi x pi pi pi pi .
sf = ' the { } jumped over the { } ! 'print ( s f . format ( 'mouse ' , 'moon ' ) )
-
64 6.
6.2.4
repr() pi , pi pi pi pi pipi pi - pi.
rjust() string, pi -, pi .
for x in range (1 , 11):print ( repr ( x ) . r just (2 ) , repr ( xx ) . r just (3 ) ,\
repr ( xxx ) . r just ( 4 ) )
, pi pipi pi, pi, - format().
for x in range (1 , 11):print ( ' {0:2d } {1:3d } {2:4d } ' . format ( x , xx , xxx ) )
split().
>>> a = 'asdf '>>> b = 'asdasdfnbfds '>>> a . sp l i t ( ' ' )[ 'asdf ' ]>>> b. sp l i t ( ' ' )[ 'asdasdf ' , 'nbfds ' ]
split() pi . pi , pi pi pi pi , pi .
6.2.5
pi , pi pi pi
-
6.2. 65
pi .
# count lines , sentences , and words of a text f i l e
# set a l l the counters to zerol ines , blanklines , sentences , words = 0, 0 , 0 , 0
# try to open the f i l etry :
filename = ' random_file 't ex t f = open ( filename , ' r ' )
except IOError :print ( 'Cannot open f i l e { 1 } for reading ' , filename )# import sys only i f neededimport sys# exi t the programsys . ex i t (0 )
# reads one l ine at a timefor l ine in t ex t f :# increase l ine counterl ines += 1
# i f i t is an empty l inei f l ine . startswith ( '\n ' ) :
blanklines += 1else :# assume that each sentence ends with . or ! or ?# so simply count these characterssentences += l ine . count ( ' . ' ) + l ine . count ( ' ! ' ) + \
l ine . count ( '? ' )
# create a l i s t of words# use None to sp l i t at any whitespace regardless of length
-
66 6.
# so for instance double space counts as one spacetempwords = l ine . sp l i t (None )
# word tota l countwords += len ( tempwords )
# close text f i l et ex t f . close ( )
print ( " Lines : " , l ines )print ( "Blank l ines : " , blanklines )print ( "Sentences : " , sentences )print ( "Words : " , words )
6.3
6.3.1. pi pi . pi pipi pi .
pi pi. pi , pipi . Python pi pi. pi- pipi pi . pi pi.
, pi pi pi.
l i s t1 = [ 'pick up groceries ' , 123,\'do laundry ' , 3.14 , ' return l ibrary books ' ]
# an empty l i s tl i s t2 = [ ]
-
6.3. 67
# a l i s t may contain any type of objectl i s t3 = [ l is t1 , l is t2 , 1.234, 'This is a diverse l i s t ' ]print ( l i s t3 )
pi pi pipi, pi pi pipipi . , pi pi , , pi pi .
6.3.1
pi pi pi .
l i s t1 = [ ]
, pi pi pi . pi list() , pi . pi pi , pi pi .
a = [1 ,2 ,3 ,4]
b = l i s t ( a )c = [ a ]
print (b )print ( c )
pi pi pi list() . list() pi pipi, Python pi pi pi pi pi pipi pi.
a = [1 ,2 ,3 ,4]
-
68 6.
b = l i s t ( a )c = a
print (b )print ( c )
# b is a copy of a and any change# on i t doesn ' t a f f ec t ab[0 ] = 5print ( a )# c is a reference to a and a l l# changes are re f lected to ac [0 ] = 10print ( a )
6.3.2
pi , - pi , pi pi, pi pi . pi pi - pi . pi pipi pipi pi pi, pi list1[j] list1[j 1]. , n , list1[n] list1[n 1] pi .
n = len ( l i s t1 )
l i s t1 [0 ]
-
6.3. 69
[i, j):
l i s t1 [ i : j ]
pi pi pi pi pi , pi pi pi .
10 pi ( pi-) pi , pi :
a = [ x for x in range (10 ) ]# or a = l i s t ( range (10 ) )print ( a [ 2 : 8 :2 ] )
[i, j) k
l i s t1 [ i : j :k ]
k pi pi
l i s t1 [ : : k ]
pi k, pi pi pi pi , pi pi pi (pi ).
def reverse ( l i s ) :return l i s [ : :1]
-
70 6.
6.3.3
pi pi -pi pi for.
a = [1 , 1 , 2 , 3 , 5 , 8]
for i in a :print ( i )
, pi pi pipi - , pi pi pi .
a = [1 , 1 , 2 , 3 , 5 , 8]
b = i t e r ( a )print ( next (b ) )print ( next (b ) )print ( next (b ) )
6.3.4
pi pi , pi pi del pi . pi pi pi pipi .
a = [0 , 1 , 2 , 3 , 4 , 5]
del a [2 :4 ]print ( a )
-
6.3. 71
6.3.5 (Lists comprehensions)
pi pi (list comprehensions). pi pi pi- pi pi , . pi .
primes = [1 , 2 , 3 , 5 , 7]
square_primes = [ i 2 for i in primes ]print ( square_primes )
list comprehension . pi . :
result = [ transform iterat ion f i l t e r ]
(transform) pipipi pi 1 (iteration) - (filter), pi. pi pi .
pi pi pi pi-. , pi pi pi for, pi pi - . pi pi pi pi . pi, pi, pi pi , - sum(). , 100pi pipi 3 7.
nums = [ i for i in range (1 , 101) i f i % 3 == 0 or i % 7 == 0]sum(nums) #2208
1 pi pi -.
-
72 6.
6.3.6
, pi . pi .
6.3.2. . :
push ( append Python)
pop
pi pi pi pi.
a = [1 , 'TasPython ' , ' geia ' ]a .append ( 'xara ' )print ( a )b = a .pop ( )print (b )
6.4
6.4.1. pi . - .
pi :
pi pi
pi pi pi. pi , pi. , pi , pi pi .
a = (1 , 'asdf ' , 3.14)print ( a )
-
6.5. 73
pi pi, - pi . pi pi pi , pi pi pi pi.
6.5
(dictionary) pi pi . pi 2,pi , pi pipi , ( ) .
6.5.1
pi pi .
d = {'milk ' : 3.67 ,'butter ' : 1.95 ,'bread ' : 1.67 ,'cheese ' : 4.67}
pi . pi pi pi .
d = { }d [ 'key ' ] = value
pi pi di-ct().
2 pi hash pi pi.
-
74 6.
d = dict ( [ ( ' milk ' , 3.67) ,( ' butter ' , 1.95) ,( ' bread ' , 1.67) ,( ' cheese ' , 4 .67 ) ] )
6.5.2
: pi del. pi del d[milk] pi pipi .
: ( /) len(d).
: ( )pi d.keys().
: , d.values().
/ : / pi d.items() pi pi pipi , pi pi pi .
pi pi, - pi . pi , pi , pi , pi- pi . pi pi pi . pi pi.
def increaseValue (d , key , value ) :" " " Increase value of d [ key ] .Precondition : We can add value to 0." " "
-
6.5. 75
i f key not in d:d [ key ] = 0
d [ key ] += value
def increaseValue2 (d, key , value ) :" " " Increase value of d [ key ] .Precondition : We can add value to 0." " "
# get the value of d [ key ] i f i t exists ,# or zero i f i t doesn ' t exist .# Then add i t to value and set i t# as the new value of d [ key ]d [ key ] = d. get ( key , 0) + value
# test ingd = { }increaseValue2 (d, ' dimitris ' , 5)print (d )
pi pi . pi, ( pipi). pi pi pi pi (value).
pi pi pi pi. pi get pi . pi d[key] pi pi pi . pi value pi d[key] pi pi.
-
76 6.
6.5.3
pi . pi pipi pi pi , pipi .
d = {'milk ' : 3.67 ,'butter ' : 1.95 ,'bread ' : 1.67 ,'cheese ' : 4.67}for food in d:
print ( ' { } costs { } ' . format ( food , d [ food ] ) )
items() pi pi , .
thoughts = { 'Omada ' : 'TasPython ' ,\' Ti einai o Anthropos ' : 'Command not found ' }
for k, v in thoughts . items ( ) :print (k , v )
6.5.4 pipi
pipi (mutable). pi pi pipi pipi pi. pi pi pi, pipi pi copy().
d [ 'a ' ] = 123c = dc [ 'a ' ] = 1821print (d [ 'a ' ] )
:
-
6.5. 77
d = { }d [ 'a ' ] = 123c = d. copy ( )c [ 'a ' ] = 1821print (d [ 'a ' ] )
6.5.5 (Dict comprehension)
, pi . , pi pi pi {} pipi pi (ite-rable), pi. pi pi pi.
d = {k : v for k, v in enumerate ( ' taspython ' ) i f v not in ' tas ' }print (d ) # {8 : 'n ' , 3: 'p ' , 4: 'y ' , 6: 'h ' , 7: 'o ' }
d = {k : v for k, v in zip ( range (15) , ' taspython ' ) i f v not in ' tas ' }print (d ) # {8 : 'n ' , 3: 'p ' , 4: 'y ' , 6: 'h ' , 7: 'o ' }
pi pi pi pi, pi Python. pi . pi, pi pi - pi pi .
6.5.6
pi , pi / pi pi. , - pi pipi. pi - pipi . pi pi . pi- . , pi
-
78 6.
, . (
pi ), pi pi pi pipi.
from col lect ions import OrderedDict
d = OrderedDict ( )d [ 'python ' ] = 'TasPython 'd [ 'guide ' ] = 'Greek 'print (d . items ( ) )
6.6
pi pi pi pi pipi, pi , pi pi pi , pi. pi pi .
6.6.1
pi pi . Python pi , pi pi pi pi pi .
s = { 'a ' , 'a ' , 'b ' , 'c ' , 'a ' }print ( s )
pi pi pi pipi pi pi pi(iterable).
-
6.6. 79
s = set ( 'TasPython . . . because simplcity matters ! ' )print ( s )
6.6.2
pi pi , pi :
pi
pi pi pi pi.
a = set ( 'abracadabra ' )b = set ( 'alacazam ' )print ( 'A = ' , a )print ( 'B = ' , b )a .add ( ' z ' ) # add elementb. remove ( ' z ' ) # remove elementprint ( 'A = ' , a )print ( 'B = ' , b )print ( 'A B = ' , a b ) # dif ferenceprint ( 'A | B = ' , a | b ) # unionprint ( 'A & B = ' , a & b ) # intersectionprint ( 'A ^ B = ' , a ^ b ) # symmetric di f ference
pi pi pi pipi :
-
80 6.
a = [ 'apple ' , 'bread ' , ' carrot ' , ' carrot ' ]set1 = set ( a )print ( set1 )print ( 'apple ' in set1 )set2 = set1 . copy ( )set2 .add ( ' delicious ' )print ( set1 < set1 )set1 . remove ( 'bread ' )# prints { ' carrot ' , 'apple ' }print ( set1 & set2 )# prints { ' carrot ' , 'apple ' , ' delicious ' , 'bread ' }print ( set1 | set2 )
-
7
pipi , pi.
pi pi pi Python . pi- , pi pi pi pi pi pi pi pi pi Python.
7.1 pi pi (immutable objects)
Python pi pi pi pi pi - . . pi pi - , pi pi pipi - .
bool
int
81
-
82 7.
float
string
pi pi- pi pi, pi . id() pi 1
pi pi . is pi True .
>>> a = 5>>> b = 5>>> c = 5.0>>> d = '5 '>>> id ( a )137061184>>> id (d )3073418688>>> a is bTrue>>> c is dFalse
, pi pi pi pi-, pi pipi ais b pi .
pi pipi pi pipi pi pipi. pi - pi , pi pipi pi pipi- pi .
1 pi , pi pi , pi pi, pi .
-
7.2. pi 83
>>> a = 4>>> b = 4>>> a is bTrue>>> a += 1>>> a5>>> b4
7.2 pi
, , pi .
7.1. pi pi pi .
7.2. pi (sco-
pe).
. , - , , pi pi pipi pi pi.
7.3. (scope) pi pi pi
pi pi. (scope).
Python, pi pipi pi - pi pipi. , pi pi pi pi ( pi ) pi . pi pi .
g = " I am a global variable "
def function1 ( arg ) :
-
84 7.
a = " I am a local variable "print ( g )# g += ' modified ' # produces an errorprint ( arg )
#print ( a ) # produces an error
function1 ( "A reference to me is passed . " )
, pipi pi, g -. pi pipi pi function1 . , - a pi , pi pipi . pipi pipi- a function1 .
pi pi pipi . pi pi pipi , Python pipi pipi pi . pi global.
g = " I am a global variable "
def function1 ( arg ) :global ga = " I am a local variable "print ( g )g += ' modified 'print ( g )print ( arg )
function1 ( "A reference to me is passed . " )
pi pipi pi pipi -
-
7.2. pi 85
pi global, pi pi pi .
g = " I am a global variable "
def function1 ( arg ) :g = " I thought I was global "print ( g )
function1 ( "A reference to me is passed . " )
print ( g )
, pipi pi . pipi, pipi pi nonlocal global pi pi pipi pi . , pi pi.
def function1 ( ) :a = "Scope1 variable "def function2 ( ) :
nonlocal aa += " modified "print ( a )function2 ( )
function1 ( )
nonlocal pi pi pi pi .
-
86 7.
7.3
pipi Pythonpi pi (container types). pi :
(tuple)
(string)
(list)
(set)
(dictionary)
pi pi pi .
pi . pi (alias) , pi pi.
>>> a = 'Python by example '>>> b = 'Python by example '>>> a is bFalse>>> a = 1>>> b = 2>>> a is bFalse>>> b = 1>>> a is bTrue
pi is pi - ==. pi 2 == pi .
2 pi , pipi .
-
7.3. 87
>>> a = [1 , 2 , 3]>>> b = [1 , 2 , 3]>>> a is bFalse>>> a == bTrue
7.3.1
(alias) - , pi - . , , , pi pi , pi pi .
a = [1 , 2 , 3]b = aa .append (4 )print (b )
pi 4 pi - a, pi b, b a .
7.3.2 None
None pi pi pi -pi . pi pi Null. Null Python pi pi None.
def helloWorld ( ) :print ( 'Hello World ' )
-
88 7.
print ( helloWorld ( ) == None )
None pi pi pi pi . pi pi None pipi pi , pi pi pipi pi.
: pi pi None. pipi pi pi pi , . pi , pi , pi None pi pi pi pi .
p = [1 , 2 , 3 , 4]print (p )# i l l e g a l statement because the returned value is None#p = p.pop ( )p.pop ( )print (p )
7.4
pi - pi pi pipi ( pi) pi . pi pi pi .
Python, pipi pi, pi - pi . , :
from f i l e import
pi python.py .pipi pi pi, pi
pi pi , -
-
7.4. 89
. pi pi . pi , pi pi pipi pi( pi ) pipi.
7.4.1. (module) pi pi - (, ). - .py. pi pi pi (pi pi pi pi ) pi pi pi pi pi pi, pi - (pi ). pi pi (pipython file.py) import pi pi pi . Python pi, pi "__name__" pi "__main__". "__name__" pi pi pi pi pi pi pi.
pi from module import * pi pi, pipi pipi pi . pi pi from moduleimport function pi ( pi) - import module, pi module, module.variable, - (pi pi pi pi) pi /pi .
pi pi pi - . :
.
-
90 7.
.
.
pi .
pi pi - namespace pi pi pi :
List1 = [1 , 2 , 3]List2 = [1 , 2 , 3]List2 [2 ] = "new"List1 = { "a" : [1 ] , "b" : [ 2 ] }
Namespace
[0] [1] [2]
1 2 3
aList
7.1: (namespace) .
7.5
pi pi pi pi pipi pi .
>>> def f ( a ) :. . . a = 5. . .>>> a = 4>>> f ( a )>>> a4
-
7.5. 91
Namespace
[0] [1] [2]
1 2 3
aList
bList
7.2: pi pi.
Namespace
[0] [1] [2]
1 2 "new"
aList
bList
7.3: .
Namespace
aDict
a
b
[0]
[0]
1
2
7.4: pi pi .
-
92 7.
a f pi , pi . , a = 5 pi pi pi . pi pi pi , .
pi pi, L -. , x pi L. , x pi . pi pi. , , L pi , pi .
, , pi pi - . , x pi . , Lpi pi foo() pi pipi pi .
def foo ( x ) :print ( 'point 2: ' , end= ' ' )print ( id ( x ) )x = [1 , 2 , 3]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 ) )
-
7.5. 93
print ( L )
pi pi pi pi pipi , pi L . pi pi L pi-pi , pi pi pi .
pi foo() pi , - pi L, python pi pi pi L error pi . pi Python pi pi pi pi pi pi.
def foo ( ) :print ( 'point 2: ' , end= ' ' )# Error . L is not declared in this scopeprint ( 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.
pi pi : pi pi pi pi .
, pi pi pi, - pi pi - pi , ,pipi , pi - , .
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 ) )print ( L )
7.6
pi , pi pi - pi . , pipi pi deepcopy.
pi pi pi pi pi pi Python - .
-
7.6. 95
from copy import deepcopy
def access_trie (d , sequence , position=None ) :" " "Access the dictionary which is referred by applyingconsequently each term of the sequence . In a more pythonterms , i f sequence is 'key ' , access : d [ 'k ' ] [ ' e ' ] [ ' y ' ] .Assume that the dictionary is at the `position ` of a l i s t ,i f `position ` i s an argument .
>>> a = { 'k ' : [0 , { 'a ' : [0 , { ' l ' : [0 , { ' o ' : [1 , { } ] } ] } ] } ] }>>> access_trie ( a , 'kal ' , 1){ ' o ' : [1 , { } ] }>>> access_trie ( a , 'kalo ' , 1){ }>>> a = { 'p ' : { ' y ' : { ' t ' : { 'h ' : { ' o ' : { 'n ' : { } } } } } } }>>> access_trie ( a , 'pyt ' ){ 'h ' : { ' o ' : { 'n ' : { } } } }>>> access_trie ( a , ' ' ){ 'p ' : { ' y ' : { ' t ' : { 'h ' : { ' o ' : { 'n ' : { } } } } } } }>>> access_trie ( a , 'python ' ){ }>>> b = access_trie ( a , 'pyth ' )>>> b [ 'O ' ] = '123 '>>> a{ 'p ' : { ' y ' : { ' t ' : { 'h ' : { 'O ' : '123 ' , 'o ' : { 'n ' : { } } } } } } }
" " "
for c in sequence :d = d [ c ]i f position is not None:
d = d [ position ]
-
96 7.
return d
def populate_trie ( t r ie , sequence , position=None ) :" " "Populate a t r i e .
Assume that the counter is always at `position ` 0 while the`position ` of the dictionary is the last one .
>>> t r i e = { }>>> populate_trie ( t r ie , 'python ' ){ 'p ' : { ' y ' : { ' t ' : { 'h ' : { ' o ' : { 'n ' : { } } } } } } }>>> t r i e = { }>>> populate_trie ( t r ie , 'kalo ' , 1){ 'k ' : [1 , { 'a ' : [1 , { ' l ' : [1 , { ' o ' : [1 , { } ] } ] } ] } ] }>>> t r i e = { }>>> populate_trie ( t r ie , 'heh ' , 2){ 'h ' : [1 , 0 , { ' e ' : [1 , 0 , { 'h ' : [1 , 0 , { } ] } ] } ] }>>> t r i e = { }>>> t r i e = populate_trie ( t r ie , 'heh ' , 1)>>> populate_trie ( t r ie , 'ha ' , 1){ 'h ' : [2 , { 'a ' : [1 , { } ] , 'e ' : [1 , { 'h ' : [1 , { } ] } ] } ] }
" " "
i f ( position is not None ) and ( position >= 1 ) :embedded_obj = [0 ] positionembedded_obj .append ( { } )
else :embedded_obj = { }
-
7.6. 97
d2 = t r i efor i , character in enumerate ( sequence ) :
d2 = access_trie ( t r ie , sequence [ : i ] , position )i f character not in d2:
i f position is None:d2 [ character ] = deepcopy ( embedded_obj )
else :d2 [ character ] = d2. get ( character ,\
deepcopy ( embedded_obj ) )d2 [ character ] [ 0 ] += 1
e l i f position is not None:d2 [ character ] [ 0 ] += 1
return t r i e
pi access_trie() pi pi pi - pi pi pipi pi pipi- pi pi. pi, pi pi position None, pi pi if pi, pi pi pi pipi .
pi sequence . , pi pi pi pi pi . pi pi pi pi pi . pi pi d pi (hides) pi pi . , pipi pipi d pi pi pi pi pi . pi pi pi pi pi pi .
populate_trie pi - pi, pi pipi -
-
98 7.
pi pi pi deepcopy.
pi pi. pi . embedded_obj , . pi pipi pi embedded_obj embedded_obj. . pi , ( pi pi) pi .
pi pi :
>>> L = l i s t ( range ( 5 ) )>>> L .append (L )>>> L[0 , 1 , 2 , 3 , 4 , [ . . . ] ]
pi pi pi pi pipi , pi 8.8, pi pi pi pi pi pi 8.3.
-
8
What can be said at all can be said clearly,and what we cannot talk about we must passover in silence.
Ludwig Wittgenstein
, pi - pi pi pi pi Python.8.1
Ludwig Wittgenstein , pi pi pipi pi pi -:
pi . (-)
pi. ( )
pi pi pi pi pi pi pi. ()
99
-
100 8.
pi pi , pi pi - pi pi , pi- pi , -pi pi . ( )
pi. ( )
pi pi .( pi)
, . (pi )
pi pi pi pi pi pi pi pi., pi, pi pi pi pi pi . pi pi- pipi , pi pi pi pi pipi pi pi- pi. ( ) pipi , . pi pi pi pi pi - .
pi - pi. pi, pi pi .
pi pi :
: pi: Guido van Rossum
: pi: Python
-
8.2. 101
pi pi pi pi pi :
(Class): (attributes) pi (methods) pi pi pi - . pi pi . pi pipi pi pi pi
(Object): , pi pi pi pi . pi .
pi (Instance): - pi pi pi .
(Method): pi -.
(Inheritance): pi - , pi pi pi pi , pi pipi . pi- pi pi .
pi pi pi . pi pi (fields) ((methods). pi pi- pi pi . pi pi .
8.2
pi pi pi pi :
-
102 8.
class Snake ( ) :pass
python = Snake ( )
pi class Snake(): Snake , python = Snake() - . pi pi pi pi pi pi pi pi .
class Snake ( ) :def helloWorld ( s e l f ) :
print ( 'Hello World ! ' )
python = Snake ( )python . helloWorld ( )
pi pi, pi , - def. pi, pi self . pipi pi self, pi .
pi , pi -. pi pi - pi pi. pi pi pi pi (pi pi) pi pi . pi pi , , pi. pi - ( pi, ), . pi , , pi . pi pi , . pi, pi-
-
8.2. 103
, , ,pi .
class Dog ( ) :def __ in i t__ ( se l f , name, color , height , mood, age ) :
" " "This method is called when an new objected isi n i t i a l l i z e d ." " "
# here we setup the attributes of our dogse l f .name = namese l f . color = colorse l f . height = heightse l f .mood = moodse l f . age = agese l f . hungry = Falsese l f . t i red = False
def print_attr ibutes ( s e l f ) :" " " Print a l l the attr ibutes of the dog " " "
print ( 'Name is ' , s e l f .name)print ( 'Color is ' , s e l f . color )print ( 'Height is ' , s e l f . height )print ( 'Mood is ' , s e l f .mood)print ( 'Age is ' , s e l f . age )print ( 'Hungry is ' , s e l f .name)print ( 'Tired is ' , s e l f . t i red )
ralph = Dog( 'Ralph ' , 'blue ' , 1.80 , 'good ' , 15)ralph . print_attr ibutes ( )
pi pi pipi, piDog() pipi pi pi pi-
-
104 8.
. pi - __init__(). pipi . __init__() pi pi pi self pi pi pi pi - pi pi pi pipi, pi pi . pi pi- .
8.2.1. pi pi-, pi self thispi pi . self pi pi . pipi, self pi , pi . -, pi pi pi , pi pi .
8.3
pipi pipipi . pi pi pi pi pipi - Trie pi pi pi pi .
class Trie :" " "A Trie is l ike a dictionary in that i t maps keys to values .However , because of the way keys are stored , i t allowslook up based on the longest pref ix that matches .
" " "
def __ in i t__ ( s e l f ) :# Every node consists of a l i s t with two position . In# the f i r s t one , there is the value while on the second
-
8.3. 105
# one a dictionary which leads to the rest of the nodes .se l f . root = [0 , { } ]
def insert ( se l f , key ) :" " "Add the given value for the given key .
>>> a = Trie ( )>>> a . insert ( ' kalo ' )>>> print ( a )[0 , { 'k ' : [1 , { 'a ' : [1 , { ' l ' : [1 , { ' o ' : [1 , { } ] } ] } ] } ] } ]>>> a . insert ( ' kalo ' )>>> print ( a )[0 , { 'k ' : [2 , { 'a ' : [2 , { ' l ' : [2 , { ' o ' : [2 , { } ] } ] } ] } ] } ]>>> b = Trie ( )>>> b. insert ( 'heh ' )>>> b. insert ( 'ha ' )>>> print (b )[0 , { 'h ' : [2 , { 'a ' : [1 , { } ] , 'e ' : [1 , { 'h ' : [1 , { } ] } ] } ] } ]
" " "
# find the node to append the new value .curr_node = se l f . rootfor k in key :
curr_node = curr_node [ 1 ] . setdefault (k , [0 , { } ] )curr_node [0 ] += 1
def f ind ( se l f , key ) :" " "Return the value for the given key or None i f key notfound .
-
106 8.
>>> a = Trie ( )>>> a . insert ( 'ha ' )>>> a . insert ( 'ha ' )>>> a . insert ( 'he ' )>>> a . insert ( 'ho ' )>>> print ( a . f ind ( 'h ' ) )4>>> print ( a . f ind ( 'ha ' ) )2>>> print ( a . f ind ( 'he ' ) )1
" " "
curr_node = se l f . rootfor k in key :
try :curr_node = curr_node [ 1 ] [ k ]
except KeyError :return 0
return curr_node [0 ]
def __str__ ( s e l f ) :return str ( s e l f . root )
def __getitem__ ( se l f , key ) :curr_node = se l f . rootfor k in key :
try :curr_node = curr_node [ 1 ] [ k ]
except KeyError :yield None
for k in curr_node [ 1 ] :
-
8.4. (attributes) 107
yield k, curr_node [ 1 ] [ k ] [ 0 ]
i f __name__ == '__main__ ' :a = Trie ( )a . insert ( 'kalo ' )a . insert ( 'kala ' )a . insert ( 'kal ' )a . insert ( 'kata ' )print ( a . f ind ( 'kala ' ) )for b in a [ 'ka ' ] :
print (b )print ( a )
8.4 (attributes)
pi pipi - ( ) (attributes) pi . pi ralph pi (instance) Dog, pi pipi name, ralph.name.
pi self pi . pi () pi pi - pi pi pipi. pi pi pipi pi self.characteristic = .
, pi print_attributes(). pi - self pi pi pi . pi pi .
-
108 8.
8.5
pi pi (member functions) pi - pi pi .
pi, pi , , (Member Functions). pi pi-pi pi pi, pi pi pi pi.
pi . pi pi pi pi pi .
Python :
variable . member_function ( [ any arguments required ] )
pi pi , pi- dir pi pi Python pi .
a = 'Python by example 'print ( 'Member functions for string ' )print ( dir ( a ) )
b = (1 , 2 , 3)print ( 'Member functions for tuple ' )print ( dir (b ) )
c = [1 , 2 , 3]print ( 'Member functions for l i s t ' )print ( dir ( c ) )
pi __functionname__ pi pi Python pi pi pi .
pi , pi-
-
8.6. 109
Python.
c = [1 , 2 , 3]print ( help ( c . sort ) )
8.6
8.6.1
8.6.1. ( ). .
class Snake :noOfSnakes = 0
def __ in i t__ ( se l f , name = 'unknown ' ) :s e l f .name = nameprint ( ' 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 ) :print ( 'Hello World from { 0 } ! ' . format ( s e l f .name ) )
@staticmethoddef numberOfSnakes ( ) :
print (Snake .noOfSnakes )
python = Snake ( 'TasPython ' )python . helloWorld ( )Snake .numberOfSnakes ( )cobra = Snake ( )cobra . helloWorld ( )Snake .numberOfSnakes ( )
-
110 8.
pi pipi pi pi pi pipi pi . pi , pi - (__init__, noOfSnakes.
8.6.2
8.6.2. pi , pipi pipi pi . pi, pi pi ( pi self ).
, pi (decorator) @staticmethod pi pipipi. , pi , pi , pipi pi , pi pi .
8.7
pi A b1 B. , pi - B A, - b1 pi pi 1. pipi - pi B2. pi : -pi (part-of) (has-a) - (is-a). pi Python pi pi. pipi pi
1 pi pi fun pi B a1.b1.fun(), pi a1 A.
2 pi pi pi a1.fun()
-
8.7. 111
pi .
8.7.1. pi - pi pi pi. - pi pipi pi . pi (pi-) pi pi- (pi).
class UniversityMember :def __ in i t__ ( se l f , name, age ) :
s e l f .name = namese l f . age = age
def who( se l f ) :print ( 'Name : " { } " Age : " { } " ' . format ( s e l f .name, se l f . age ) )
class Professor ( UniversityMember ) :def __ in i t__ ( se l f , name, age , salary ) :
UniversityMember . __ in i t__ ( se l f , name, age )se l f . salary = salary
def who( se l f ) :UniversityMember .who( se l f )print ( 'Salary : " { } " ' . format ( s e l f . salary ) )
class Student ( UniversityMember ) :def __ in i t__ ( se l f , name, age , marks ) :
UniversityMember . __ in i t__ ( se l f , name, age )se l f .marks = marks
def who( se l f ) :UniversityMember .who( se l f )print ( 'Marks: " { } " ' . format ( s e l f .marks ) )
-
112 8.
p = Professor ( 'Mr. Sipser ' , 40, 3000000)s = Student ( 'Kosmadakis ' , 25, 9.99)
for member in ( p , s ) :print ( '' )member.who ( )
pi, Professor pi pi UniversityMember. pi pipi , Professor pi pi (UniversityMember). ,pi pi pi Professor pi pi pipi pipi.
pi pi pi pi pi pipi- pi pi pi - . , pi pi pi pi pi pi , , pipi- pi pi pi DRY Dont Repeat Yourself pi , pipi pi pi pi pi ( - pipi pi pipi ).
8.8
, pi pi pi pipi (pi , , ..). pi __. . pi,
-
8.8. 113
pi Python pi operator overloading.
__init__(self, . . . ): pi pi . - . pi (base class) __init__(), pipi pi pi pi .pipi, pi __init__() pi pi
__del__(self): . (destructor). , pipi pi pi.
__repr__(self): repr() - pi pi -. , pipi pi Python pi . pi debugging.
__str__(self): str() pi pipi pi pi print(). pi __repr__() . pipi .
__lt__(self, other), __le__(self, other), __eq__(self, other), __ne__(self, o-ther), __ne__(self, other), __gt__(self, other), __ge__(self, other): pi- pi (=). pipi - pi pi pi pipi pi pi pi pi .
pi, pi pi pi - pi, pi pi pi pi.
__add__(self, other): (+)
__sub__(self, other): ()
-
114 8.
__mul__(self, other): pi ()
__truediv__(self, other): (/)
__floordiv__(self, other): (//)
__mod__(self, other): pipi (%)
pi , pi pi pi pi (descriptors) pi pipi. pipi pipi pi pi __, pi pi pi, pi pi pipi.
pi pi pi pi pi :
class EmbeddedDict ( dict ) :def __missing__ ( se l f , key ) :
value = EmbeddedDict ( )s e l f [ key ] = valuereturn value
d = { }d2 = EmbeddedDict (d )d2 [ 'a ' ] [ 'b ' ] [ 'c ' ] = 1print (d2 )
pi pipi pi pi, .
-
9
pi pi .
pi pi - pi pi pi pi pi pi . pi - pi , pi .
9.1 pi
pi pi pipi pi , pipi , pi pi pi . , pi open() . , pi pi , pi pi pipi. pi pi , -pi pi, pi .
115
-
116 9.
pi pi pi open() pi 9.1.
pi r
w ( pi pi)
a ( pi pi)b
+ r+ /
9.1: pi pi
pi r, w, a pi pi pi. pi , pipi ( pi r.
9.2
9.2.1 pi
pi read(). , bytes pi pi .
f = open ( ' input_ f i l e . txt ' ) # open , readonly ( default )print ( f .name) # recover name from f i l e objectprint ( f . readlines ( ) )print ( f . readlines ( ) ) # already at end of f i l ef . seek (0 ) # go back to byte 0 of the f i l eprint ( f . read ( ) ) # read to EOF, returning bytes in a stringf . close ( )
-
9.2. 117
pi pi readlines read, pi pi , pi , . , close() pi pi .
9.2.2
pi , pi , pi pipi , open(). pipi pi pi , pipi pi .
g = open ( ' new_file ' , 'w ' ) # open for writingg . write ( 'A new f i l e begins ' ) # takes just one argumentg . write ( ' . . . today !\n ' )g . close ( )
pi , pi- pi , pipi pi.
f = open ( ' f i l e . txt ' , 'a ' )f . write ( 'Append a new l ine at the end of the f i l e \n ' )f . close ( )
9.2.3
pi pi for pi (iterate), pi pi .
f = open ( ' input_ f i l e . txt ' ) # open , readonly ( default )
for l ine in f :print ( l ine )
-
118 9.
pipi pi, pi pi -pi . , , pi - \n. , pi, pi . pipi pi pi- pi print pi , pi pipi .
9.2.4 (pi)
pi (serialization) , -pi pi bits pi pi pi ( ) -. pi pipi pi pi . pi pi pi pi pi ( pi -pi) .
pi , Python pi (module) pickle. pickle pi pi pi pi .
0: pi pi pi pi pi
1: pi pi pi pi pi
2: pi pi 2 Python
3:
pi pi (pi pi 3),pipi . pipi , pi pi.
-
9.3. 119
import pickle
write_data = [1 , 2.0 , 'asdf ' , [None, True , False ] ]
with open ( 'data . pickle ' , 'wb ' ) as f :pickle .dump( write_data , f )
with open ( 'data . pickle ' , ' rb ' ) as f :read_data = pickle . load ( f )
print ( read_data )
pipi pi - python pi pi pipi . pi, pi pipi pi (binary for-mat), pi pi pipi pi.
9.3
, pi pi pi . python pi pi , pi pi. pi os pi pi (pi pi pi ) pi pi pi pi.
9.3.1
pi pi :
getcwd(): pi .
-
120 9.
listdir(): .
chdir(path): pi pi path.
(module) pi pi os. pi pi pi pi cross-platform, pipi.
pi pi - . os.path.split() os.path.join() pipi pi cross-platform , pi pi pi pi.
import os
abs_path = os . path . abspath ( os . path . curdir )# os . path . jo in is used to append a re la t i ve path at the# end of another pathpath2 = os . path . jo in ( abs_path , "new_dir " )print ( path2 )# os . path . sp l i t " sp l i t s " the path in two pieces .# The path unti l the last '/ ' and whatever fol lowspath0 , path1 = os . path . sp l i t ( path2 )print ( path0 )print ( path1 )
pi pi pi- pi pi pi( cross-platform) pi pi pi Python.
import os
print ( os . path . curdir ) # get current directory ( Pythonic humor)abs_path = os . path . abspath ( os . path . curdir ) # get i t s f u l l pathprint ( abs_path )
-
9.3. 121
ful l_path = os . getcwd ( )print ( full_path )
# get the t a i l end of the pathprint ( os . path .basename( full_path ) )
# l i s t the contents of the current directoryos . l i s t d i r ( ful l_path )
# get information about f i l e . txt# the numbers below are : inode protection mode; inode number;# device inode resides on; number of l inks to the inode ;# user id of the owner ; group id of the owner ; s ize in bytes ;# time of last access ; time of last modification ;# " ctime " as reported by OSprint ( os . stat ( ' f i l e . txt ' ) )
s ize = os . path . gets ize ( ' f i l e . txt ' )print ( 'The f i l e size is : ' , s ize )isdirectory = os . path . i sd i r ( ' f i l e . txt ' )print ( ' Is f i l e . txt a directory : ' , isdirectory )# time of last modification ( seconds since Epoch)last_mod = os . path . getmtime ( ' f i l e . txt ' )print ( 'The last time this f i l e modified is ' , last_mod )
, pi pi pi- pi os.system().
import os
os . system ( " ls " )
pipi pipi pi, pi pi pi pi pi -
-
122 9.
.
9.3.2
pi .
mkdir(path): path.
makedirs(path): pi pi path pi pi -, .
import os
# remove new_dir i f already exists and i t is emptyi f os . path . i sd i r ( 'new_dir ' ) :
os . rmdir ( 'new_dir ' )os . makedirs ( 'new_dir ' )print ( os . l i s t d i r ( ' . ' ) )# change to subdirectory new_diros . chdir ( 'new_dir ' )
-
10
Success is not final, failure is not fatal: it isthe courage to continue that counts.
Winston Churchill
pipi pipi pi pipi - (pi pi pi ) pi pi- . pi pi - pi pi pi, pi pi pi pi pi .
10.1
10.1.1. pi pipi pi pi.
pi pi pi pipi , -pi pipi pi pi pi , pi - . pi pi pipi pi
123
-
124 10.
pi pi. pi , pi pi pi (pi pi pi pi pi ).
pi :
1. pi Python .
2. (pi NameError, TypeError,IndexError).
3. pipi.
4. pi , pi .
5. pi , traceback, pi .
pi pi pi- , pi pipi pipi , pi if. . . else . . . ,pi pi . , , pi pi pi pi else. pi , pi pi pi, pi pi pi except.
10.2 .
pi pi pi , . pi pi pi .
>>> 8/0Traceback (most recent ca l l last ) :
-
10.2. . 125
Fi le "" , l ine 1, in ZeroDivisionError : int divis ion or modulo by zero
(shell) Py-thon, pi pi - . pi , pi (, pi -), pi ( 1), (ZeroDivisionError,pi ) (intdivision or modulo by zero).
pi pi , pipi .
>>> try :. . . 8/0. . . except ZeroDivisionError :. . . print ( 'Could not make the division ' ). . .Could not make the division
, pi pi pi pi- pi pi try - , pi pi pi except. pi pi ( pipi ZeroDivisionError), pi pi pi . pi pi pi .
pi pi pi , - pi pi:
>>> a 5Traceback (most recent ca l l last ) :
F i le "" , l ine 1, in NameError : name 'a ' is not defined
-
126 10.
pi pipi pi a pi . pi pi NameError. pi pi, pipi a, pi try. . . except. . . pi, pi (NameError).
pi pi pipi pipipi ( ) pi pi pi .
>>> b = None>>> b 7Traceback (most recent ca l l last ) :
F i le "" , l ine 1, in TypeError : unsupported operand type ( s ) for :'NoneType ' and ' int '
, pi pi ,pi pi , .
>>> with open ( '3BirdsAreSitting .mp3 ' , ' r ' ) as f :. . . f . read ( ). . .Traceback (most recent ca l l last ) :
F i le "" , l ine 1, in IOError : [ Errno 2] No such f i l e or directory :'3BirdsAreSitting .mp3 '
with, 3BirdsAreSitting.mp3, pi with, , , pi pi pi .
, pi pi pi except, pi pi , pi pi pi pi pi .
-
10.2. . 127
. . . except ( RuntimeError , TypeError , NameError ) :
. . . pass
pi -pi except:, pi pi, - pi pi pipi.
import sys
try :f = open ( 'myfile . txt ' )s = f . readline ( )i = int ( s . str ip ( ) )
except IOError as err :print ( " I/O error : { } " . format ( err ) )
except ValueError :print ( "Could not convert data to an integer . " )
except :print ( "Unexpected error : " , sys . exc_info ( ) [ 0 ] )raise
pi, pi pi pi -, pi pi pi, -pi pi pi except pi. , myfile.txt, pi pi pi pi pi .
, pi . , pi , pi pi pi IOError - pi err. pi pi pi pi pi . - pi except pi pi , pi , pi except pi
-
128 10.
pi try, pi pi pi. ValueError pi .
, pipi , pi pi pi raise, pi pi pi pi pipi.1 , , pipi ( pi pi) pipi. pi raise pi.
10.3 pi
, pi pi ( - web ) pipi pi pi pi pi , , pipi . pi pi pi pi pi pi pi .
while True :try :
x = int ( input ( " Please enter a number: " ) )break
except ValueError :print ( "Not a number. Try again . . . " )
print ( x )
pipi pi, pi -. , pi pi pi , . , input pi pi-
1 pi, pi , pi try. . . except. . . pi .
-
10.4. 129
. , int pipi . pi pi, x -pi pi while, break pi pi pi except ValueError, pi pi . pi break , pi . , pi pi print.
10.4
, pi Python.
1. try pi .
2. , pi except.
3. try pi, pi except.
4. except pi pi .
5. , .
6. , pi try pi.
7. , pi-.
10.4.1 try:. . . else: . . .
, pi pipi pi pi pi pi pipi . pi try pi. pi pi, Python pi else, pi pi if, pi pi.
-
130 10.
try :f = open ( 'myfile . txt ' )
except IOError as err :print ( " I/O error : { } " . format ( err ) )
else :s = f . readline ( )print ( 'The f i r s t l ine of f is : ' , s )f . close ( )
else pi pipi pi . , pi, pi.
pi pipi pi :
1. pi try.
2. pi except.
3. ( ) pi pi else.
pipi else pipi pi pi except pi pi pi.
10.4.2 finally
, pi finally, pi pipi , .
# how many times we have requested for inputtimes = 0
while True :try :
x = int ( input ( " Please enter a number: " ) )break
-
10.5. 131
except ValueError :print ( "Not a number. Try again . . . " )
f i na l l y :times += 1
print ( 'Requested input ' , times )
pipi pi, pi pi , pi pi pi- pi . , pi finally, , pi pi . pi pi pi pi pi pi .
10.5
pi .
10.5.1
2 pi pi Exception. pi . pi pi args pi pi pi . pi pi pi pi .
try :raise Exception ( 'Can you handle i t ? ' )
except Exception as inst :print ( inst . args )print ( inst )
2 pi pi
-
132 10.
, pi Exception. - pi Can you handle it?. pi pi pi as pi inst, pi pi. args pi-, pi . pi pi __str__() pi pi.
10.5.2 (raise)
, pi pi pi BaseException. , pi , pi pi pi -pi pi Exception. pi pi -pi raise.
>>> raise NameError ( 'TesseraPoulakiaKa8ontai ' )Traceback (most recent ca l l last ) :
F i le "" , l ine 1, in NameError : TesseraPoulakiaKa8ontai
pipi pi- pi.
>>> raise NameErrorTraceback (most recent ca l l last ) :
F i le "" , l ine 1, in NameError
10.5.3 pi
pi pi - pipi , pipi - pi Exception.
>>> class MyError ( Exception ) :
-
10.6. if . . . else 133
. . . def __ in i t__ ( se l f , value ) :
. . . s e l f . value = value
. . . def __str__ ( s e l f ) :
. . . return repr ( s e l f . value )
pi pi __init__, - __str__ pi pipi pi pi pi .
, pi - pi , pi pipi .
>>> try :. . . raise MyError (4 ). . . except MyError as e :. . . print ( 'My exception occurred : ' , e ). . .My exception occurred : 4
>>> raise MyError ( 'oops ! ' )Traceback (most recent ca l l last ) :
F i le "" , l ine 1, in ?__main__ .MyError : 'oops ! '
10.6 if . . . else
pi pi pipi. pi pi pi pi pi pi pi if. . . else. .
10.6.1. pi pi- pi pi pipipi pi pi , pi . pi,
-
134 10.
pi ( pi). , - , pipi pi pipi .
pipi pi pi pi pi .
from timeit import Timerfrom random import randint
VALUES = 10000inverseprob = 2d = dict ( [ ( x , y ) for x , y in zip ( range (VALUES) ,\
range (VALUES, 2 VALUES ) ) ] )
class MyError ( Exception ) :def __ in i t__ ( se l f , value ) :
s e l f . value = valuedef __str__ ( 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 ) :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 try_exceptMAYBE (d, inverseprob ) :s = randint (0 , inverseprob )try :
i f s == 0: raise MyError (2 )d [1 ]
except MyError :pass
def if_elseMAYBE (d, inverseprob ) :s = randint (0 , inverseprob )i f s == 0: returnelse : d [1 ]
def f a i l ( ) :print ( " Unsuccessful look up" )
-
136 10.
t = Timer ( " try_except (d ) " ,\" from __main__ import try_except , d" )
s f = 'Execution time with exceptions : { } seconds 'print ( s f . format ( t . t imeit ( ) / 106))
t = Timer ( " i f _ e l s e (d ) " ,\" from __main__ import i f _e lse , d" )
s f = 'Execution time with i f /else : { } seconds 'print ( s f . format ( t . t imeit ( ) / 106))
def success ( ) :print ( " Successful look up" )t = Timer ( " try_exceptYES (d ) " ,\
" from __main__ import try_exceptYES , d" )s f = 'Execution time with exceptions : { } seconds 'print ( s f . format ( t . t imeit ( ) / 106))
t = Timer ( " if_elseYES (d ) " ,\" from __main__ import if_elseYES , d" )
s f = 'Execution time with i f /else : { } seconds 'print ( s f . format ( t . t imeit ( ) / 106))
def maybe ( ) :print ( " Successful under a probabil i ty " )t = Timer ( " try_exceptMAYBE (d, inverseprob ) " ,\
" from __main__ import try_exceptMAYBE , d, inverseprob " )s f = 'Execution time with exceptions : { } seconds 'print ( s f . format ( t . t imeit ( ) / 106))
t = Timer ( " if_elseMAYBE (d, inverseprob ) " ,\" from __main__ import if_elseMAYBE , d, inverseprob " )
s f = 'Execution time with i f /else : { } seconds '
-
10.6. if . . . else 137
print ( s f . format ( t . t imeit ( ) / 106))
def main ( ) :success ( )f a i l ( )maybe ( )
i f __name__ == '__main__ ' :main ( )
-
138 10.
-
11
A woodpecker can peck twenty times on athousand trees and get nowhere, but staybusy. Or he can peck twenty-thousand timeson one tree and get dinner.
Seth Godin
pi, pi . pi - , pi pi