Professional Documents
Culture Documents
.
.
devpractice.ru
, .
.
devpractice.ru
.
devpractice.ru, 2017
.., 2017
! Python.
! ,
devpractice.ru .
Yandex.: 410011113064717
: https://money.yandex.ru/to/410011113064717
http://devpractice.ru/donation/
, !
1
devpractice.ru
1. 5
1.1 Python 5
1.2 Python 5
1.2.1 Python Windows 5
1.2.2 Python Linux 8
1.3 Anaconda 9
1.3.1 Anaconda Windows 9
1.4 PyCharm 17
1.4.1 PyCharm Windows 17
1.5 21
1.5.1 Python 21
1.5.2 Anaconda 22
1.5.3 PyCharm 25
2. Python 28
2.1 28
2.2 32
3. 33
3.1 33
3.2 Python 33
3.3 34
3.4 37
4. 39
4.1 39
4.2 42
4.3 43
4.4 44
4.5 () math 44
5. 47
5.1 if 47
5.1.1 if 47
5.1.2 if else 48
5.1.3 if elif else 49
5.2 while 50
5.3 break continue 50
5.4 for 51
7. (list) 62
7.1 (list) Python? 62
7.2 ? 62
7.3 , , 63
7.4 66
7.5 List Comprehensions 69
8. (tuple) 70
8.1 (tuple) Python? 70
8.2 Python? 70
8.3 , 71
8.3.1 71
8.3.2 72
8.3.3 72
8.3.4 73
9. (dict) 74
9.1 (dict) Python? 74
9.2 , , 74
9.2.1 74
9.2.2 75
9.2.3 75
9.3 76
10. Python 79
10.1 Python? 79
10.2 79
10.3 80
10.4 Lambda- 81
11. 82
11.1 82
11.2 Python 83
11.3 Python 83
11.4 Python 84
11.5 Python 85
11.6 finally 88
11.7 Python 89
11.8 (User-defined Exceptions) Python 90
3
devpractice.ru
12. - . 91
12.1 91
12.2 92
12.3 93
12.3.1 93
12.3.2 94
12.3.3 95
12.3.4 95
13. 97
13.1 Python 97
13.1.1 Python? 97
13.1.2 Python? 97
13.2 Python 99
13.2.1 Python? 99
13.2.2 Python 100
14. 101
14.1 - 101
14.2 Python 102
14.2.1 102
14.2.2 104
14.3 104
14.4 105
15. 107
15.1 Python 107
15.2 108
15.3 110
4
devpractice.ru
1.
1.1 Python
Python Python 2 Python 3,
.
Python , , ,
, , .
, Python 3, , , -
Python, Python 3.
Python 2 .
1.2 Python
Python , ,
. ,
https://www.python.org/downloads/.
5
devpractice.ru
.
1. .
2. .
6
devpractice.ru
,
Python. .
Documentation .
pip pip.
tcl/tk and IDLE (IDLE)
(tkinter).
4. ( Customize installation)
7
devpractice.ru
,
:
Install for all users .
, ,
.
Associate files with Python , .py, Python.
Windows,
Python .
Create shortcuts for installed applications
.
Add Python to environment variables Python
PATH.
Precomple standard library .
(Download debugging symbols, Download debug binaries)
, .
5. .
8
devpractice.ru
> python
> python3
, Python 2 Python 3. ,
, Linux, Python,
. , Python, ,
, , , , : )
Python ; ) .
Ubuntu :
> sudo apt-get install python3
.
1.3 Anaconda
Python,
Anaconda. Python (
2 3),
, .
,
https://www.continuum.io/downloads.
Windows, Linux Mac OS.
9
devpractice.ru
2. .
3. :
Just Me , ;
10
devpractice.ru
All Users .
4. , Anaconda.
11
devpractice.ru
5. :
Add Anaconda to the system PATH environment variable Anaconda
PATH
Register Anaconda as the system Python 3.5 Anaconda,
Python 3.5 .
Install.
12
devpractice.ru
5. Anaconda .
13
devpractice.ru
2. , .
14
devpractice.ru
, yes,
:
Do you approve the license terms? [yes|no]
3. . :
Press ENTER to confirm the location ENTER
. :
/home/tester/anaconda3, .
Press CTRL-C to abort the installation CTRL-C .
Or specify a different location below .
ENTER.
15
devpractice.ru
4. .
16
devpractice.ru
1.4 PyCharm
IDE, ,
IDE PyCharm JetBrains.
https://www.jetbrains.com/pycharm/download/
IDE Windows, Linux Mac OS.
PyCharm Professional Community. Community,
.
17
devpractice.ru
2. .
3. , ( 32- 64-
PyCharm) Create associations
.py PyCharm.
18
devpractice.ru
4. .
5. PyCharm .
19
devpractice.ru
4.2 PyCharm Linux
1. .
2. , :
> tar xvf _.tar.gz
, ,
bin . pycharm.sh :
> ./pycharm.sh
20
devpractice.ru
PyCharm.
1.5
, .
1.5.1 Python
.
Windows, Win+R python. Linux
python3 ( python).
Python ,
( Windows, Linux ):
21
devpractice.ru
:
print(Hello, World!)
:
1.5.2 Anaconda
, Anaconda Windows,
C:\Anaconda3, Linux, , .
Scripts :
> ipython notebook
Windows C:\Anaconda3\Scripts
,
cmd.
22
devpractice.ru
23
devpractice.ru
- .
, New (
) Python.
.
print(Hello, World!)
Alt+Enter .
.
24
devpractice.ru
1.5.3 PyCharm
PyCharm Create New Project .
Python ,
.
25
devpractice.ru
Python .
26
devpractice.ru
.
27
devpractice.ru
2. Python
Python ,
.
Python Linux MS Windows.
Python . ,
,
. ,
. ,
. , ,
, , .
(
, ).
C++ C.
,
.
Python, .
.
Python :
;
.
2.1
,
> python
> python3
Python
.
28
devpractice.ru
Python, ,
Python
. , test.py
:
> python test.py
Python :
print(Hello, World!)
ENTER.
.
29
devpractice.ru
Python ,
,
Matlab, Octave
..
.
.
30
devpractice.ru
,
exit()
ENTER.
Python IDLE (
). ,
( ,
, ..).
IDLE Windows Python
IDLE (Python 3.5 XX-bit).
Linux IDLE ,
. , Ubuntu, (
Python 3.4):
> sudo apt-get install idle-python3.4
IDLE .
, :
> idle-python3.4
IDLE Linux.
31
devpractice.ru
2.2
Python
( ). test.py,
:
a = int(input())
print(a**2)
.
,
> python test.py
.
32
devpractice.ru
3.
Python ,
.
Python, .
3.1
Python,
,
.
,
, .
Java, C++.
Java Python.
Java:
int a = 1;
Python:
a = 1
.
,
(
2). Python ,
, C#, Java .
, .
, .
Python, Java, ++.
3.2 Python
Python (built-in)
,
.
33
devpractice.ru
:
1. None ( )
2. (Boolean Type)
3. (Numeric Type)
a. int
b. float
c. complex
4. (Sequence Type)
a. list
b. tuple
c. range
5. (Text Sequence Type )
a. str
6. (Binary Sequence Types)
a. bytes
b. bytearray
c. memoryview
protocol buffer
7. (Set Types)
a. set
b. frozenset
8. (Mapping Types)
a. dict
3.3
, ,
.
,
, ,
.
:
b = 5
b 5.
34
devpractice.ru
5 Python
. , ,
, , .. ,
, ( ).
, .
,
, , ,
.
, ,
:
5 ( ,
5 );
, : 5, :
;
= b
5 ( b 5).
Python. ,
keyword keyword.kwlist.
>>> import keyword
>>> print "Python keywords: ", keyword.kwlist
:
>>> keyword.iskeyword("try")
True
>>> keyword.iskeyword("b")
False
,
, id().
>>> a = 4
>>> b = 5
>>> id(a)
1829984576
35
devpractice.ru
>>> id(b)
1829984592
>>> a = b
>>> id(a)
1829984592
, ,
. a
4 1829984576, b id
= 1829984592. a = b, a
, b.
type().
.
>>> a = 10
>>> b = "hello"
>>> c = (1, 2)
>>> type(a)
<class 'int'>
>>> type(b)
<class 'str'>
>>> type(c)
<class 'tuple'>
36
devpractice.ru
3.4
Python .
(immutable) :
(int);
(float);
(complex);
(bool);
(tuple);
(str);
(frozen set).
(mutable)
(list);
(set);
(dict).
, , ,
, ,
.
,
. , k = 15,
15, int ,
id().
>>> k = 15
>>> id(k)
1672501744
>>> type(k)
<class 'int'>
id = 1672501744 15 .
, .
37
devpractice.ru
, [1, 2], 3.
>>> a = [1, 2]
>>> id(a)
47997336
>>> a[1] = 3
>>> a
[1, 3]
>>> id(a)
47997336
, a, .
.
, , ,
. .. a
1 3, .
38
devpractice.ru
4.
Python,
, Matlab
Octave. , , ,
. ,
.
,
Python, :
(int);
(float);
(complex).
, .
, .
,
.
4.1
Python,
.
.
>>> 3+2
5
, .
>>> a = 3
>>> b = 2
>>> a + b
5
39
devpractice.ru
>>> a = 3
>>> b = 2
>>> c = a + b
>>> print(c)
5
,
, :
>>> a = 3
>>> b = 2
>>> a = a + b
>>> print(a)
5
:
>>> a = 3
>>> b = 2
>>> a += b
>>> print(a)
5
.
.
>>> 4-2
2
>>> a = 5
>>> b = 7
>>> a - b
-2
40
devpractice.ru
.
>>> 5 * 8
40
>>> a = 4
>>> a *= 10
>>> print(a)
40
.
>>> 9 / 3
3.0
>>> a = 7
>>> b = 4
>>> a / b
1.75
.
>>> 9 // 3
3
>>> a = 7
>>> b = 4
>>> a // b
1
.
>>> 9 % 5
4
>>> a = 7
>>> b = 4
>>> a % b
3
41
devpractice.ru
.
>>> 5 ** 4
625
>>> a = 4
>>> b = 3
>>> a ** b
64
4.2
complex(a, b),
, , ,
. a + bj.
.
.
>>> z = 1 + 2j
>>> print(z)
(1+2j)
>>> x = complex(3, 2)
>>> print(x)
(3+2j)
, , ,
.
>>> x + z
(4+4j)
>>> x - z
(2+0j)
>>> x * z
(-1+8j)
>>> x / z
(1.4-0.8j)
>>> x ** z
(-1.1122722036363393-0.012635185355335208j)
>>> x ** 3
(-9+46j)
42
devpractice.ru
.
>>> x = 3 + 2j
>>> x.real
3.0
>>> x.imag
2.0
conjugate().
>>> x.conjugate()
(3-2j)
4.3
Python , .
(AND).
>>> p = 9
>>> q = 3
>>> p & q
1
(OR).
>>> p | q
11
(XOR).
>>> p ^ q
10
.
>>> ~p
-10
43
devpractice.ru
.
>>> p << 1
18
>>> p >> 1
4
4.4
,
, , ,
.
.
>>> m = 124504
>>> hex(m)
'0x1e658'
.
>>> oct(m)
'0o363130'
.
>>> bin(m)
'0b11110011001011000'
4.5 () math
Python math,
.
.
>>> import math
.
math.ceil(x)
, x.
>>> math.ceil(3.2)
4
44
devpractice.ru
math.fabs(x)
.
>>> math.fabs(-7)
7.0
math.factorial(x)
x.
>>> math.factorial(5)
120
math.floor(x)
, x.
>>> math.floor(3.2)
3
math.exp(x)
e**x.
>>> math.exp(3)
20.08553692318766
math.log2(x)
2.
math.log10(x)
10.
math.log(x[, base])
e,
.
>>> math.log2(8)
3.0
>>> math.log10(1000)
3.0
>>> math.log(5)
1.609437912434100
>>> math.log(4, 8)
0.666666666666666
45
devpractice.ru
math.pow(x, y)
x y.
>>> math.pow(3, 4)
81.0
math.sqrt(x)
x.
>>> math.sqrt(25)
5.0
, .
math.cos(x)
math.sin(x)
math.tan(x)
math.acos(x)
math.asin(x)
math.atan(x)
.
math.pi
.
math.e
.
, math ,
(https://docs.python.org/3/library/math.html).
46
devpractice.ru
5.
if while for.
.
5.1 if
if
. .
5.1.1 if
if .
if :
_1
_2
...
_n
if . ,
, .
, , ,
True. :.
: , ,
, !
:
if 1:
print("hello 1")
: hello 1
a = 3
if a == 3:
print("hello 2")
: hello 2
47
devpractice.ru
a = 3
if a > 1:
print("hello 3")
: hello 3
lst = [1, 2, 3]
if lst :
print("hello 4")
: hello 4
5.1.2 if else
,
. ..
, . if else.
if :
_1
_2
...
_n
else:
_a
_b
...
_x
.
a = 3
if a > 2:
print("H")
else:
print("L")
: H
48
devpractice.ru
a = 1
if a > 2:
print("H")
else:
print("L")
: L
,
.
a = 17
b = True if a > 10 else False
print(b)
: True
if elif else.
if _1:
_(_1)
elif _2:
_(_2)
elif _3:
_(_3)
else:
_(_4)
.
a = int(input(" :"))
if a < 0:
print("Neg")
elif a == 0:
print("Zero")
else:
print("Pos")
, Neg,
Zero, Pos.
49
devpractice.ru
5.2 while
while ,
. if.
while .
while :
_1
_2
...
_n
.
.
a = 0
while a < 7:
print("A")
a += 1
.
.
a = 0
while a == 0:
print("A")
,
a 7. ,
.
50
devpractice.ru
continue , ,
, .
.
a = -1
while a < 10:
a += 1
if a >= 7:
continue
print("A")
7 , ,
11 .
5.4 for
for ,
.
.
for i in range(5):
print("Hello")
Hello .
break continue,
while.
,
( ),
for .
lst = [1, 3, 5, 7, 9]
for i in lst:
print(i ** 2)
51
devpractice.ru
.
word_str = "Hello, world!"
for l in word_str:
print(l)
Hello, world! .
.
52
devpractice.ru
6. IPython Jupyter Notebook
IPython Python.
IPython
Jupyter. Jupyter notebook
- IPython,
.
, ,
, ,
, , ,
, pdb Python .
IPython
, , .
Jupyter notebook ,
Python, : -,
, ,
, , ..
:
Python , ,
;
;
(, );
Markdown LaTeX.
, ,
, . , ,
, .
PDF, HTML.
6.1
Jupyter Notebook Anaconda.
. Jupyter Notebook Scripts (
, Anaconda)
:
53
devpractice.ru
> ipython notebook
6.2
: !
, , Jupyter notebook.
Jupyter notebook ,
New Folder.
Untitled folder,
notebooks: Rename.
54
devpractice.ru
,
New, Python [Root].
.
Python Markdown :
Python, Code.
Markdown Markdown.
: Code,
2 + 3 Ctrl+Enter Shift+Enter,
55
devpractice.ru
Python,
, ,
.
, .
56
devpractice.ru
, :
(Edit
mode) (Command mode).
, ,
, .
Help->Keyboard Shortcuts
57
devpractice.ru
Python. ,
.
- ,
.
6.4
,
Kernel -> Interrupt.
Insert->Insert Cell Above Insert->Insert
Cell Below.
Cell,
:
Ctrl+Enter .
Shift+Enter .
Alt+Enter .
6.5 ?
,
, :
, .ipynb,
Jupyter Notebook;
html;
https://gist.github.com/;
http://nbviewer.jupyter.org/.
58
devpractice.ru
6.6
,
matplotlib . ,
. , ,
:
%matplotlib inline
.
6.7
Jupyter Notebook .
IPython ,
, .
59
devpractice.ru
%lsmagic
%env.
Python .py ,
.ipynb, %run.
%%time %timeit.
%%time
.
60
devpractice.ru
%timeit 100000 ( )
.
61
devpractice.ru
7. (list)
Python,
.
, , . ,
.
7.2 ?
, .
, ,
, .
,
. ,
.
1 2, a[1] = 3,
3.
62
devpractice.ru
3 ( ).
7.3 , ,
.
>>> a = []
>>> type(a)
<class 'list'>
>>> b = list()
>>> type(b)
<class 'list'>
.
>>> a = [1, 2, 3]
>>> type(a)
<class 'list'>
63
devpractice.ru
,
:
>>> a = [1, 3, 5, 7]
>>> b = a[:]
>>> print(a)
[1, 3, 5, 7]
>>> print(b)
[1, 3, 5, 7]
:
>>> a = [1, 3, 5, 7]
>>> b = list(a)
>>> print(a)
[1, 3, 5, 7]
>>> print(b)
[1, 3, 5, 7]
, ,
b ,
a, . .. a, b
.
>>> a = [1, 3, 5, 7]
>>> b = a
>>> print(a)
[1, 3, 5, 7]
>>> print(b)
[1, 3, 5, 7]
>>> a[1] = 10
>>> print(a)
[1, 10, 5, 7]
>>> print(b)
[1, 10, 5, 7]
64
devpractice.ru
append().
>>> a = []
>>> a.append(3)
>>> a.append("hello")
>>> print(a)
[3, 'hello']
, , ,
remove(x),
.
>>> b = [2, 3, 5]
>>> print(b)
[2, 3, 5]
>>> b.remove(3)
>>> print(b)
[2, 5]
,
del _[].
>>> c = [3, 5, 1, 9, 6]
>>> print(c)
[3, 5, 1, 9, 6]
>>> del c[2]
>>> print(c)
[3, 5, 9, 6]
, ,
.
>>> d = [2, 4, 9]
>>> print(d)
[2, 4, 9]
>>> d[1] = 17
>>> print(d)
[2, 17, 9]
65
devpractice.ru
,
.
.
>>> a = [3, 5, 7, 10, 3, 2, 6, 0]
>>> a[2]
7
,
,
:
>>> a[-1]
0
, ,
.
>>> a[1:4]
[5, 7, 10]
7.4
list.append(x)
. a[len(a):] =
[x].
>>> a = [1, 2]
>>> a.append(3)
>>> print(a)
[1, 2, 3]
list.extend(L)
L.
a[len(a):] = L.
>>> a = [1, 2]
>>> b = [3, 4]
>>> a.extend(b)
>>> print(a)
[1, 2, 3, 4]
66
devpractice.ru
list.insert(i, x)
x i.
x.
>>> a = [1, 2]
>>> a.insert(0, 5)
>>> print(a)
[5, 1, 2]
>>> a.insert(len(a), 9)
>>> print(a)
[5, 1, 2, 9]
list.remove(x)
x .
>>> a = [1, 2, 3]
>>> a.remove(1)
>>> print(a)
[2, 3]
list.pop([i])
i .
, .
>>> a = [1, 2, 3, 4, 5]
>>> print(a.pop(2))
3
>>> print(a.pop())
5
>>> print(a)
[1, 2, 4]
67
devpractice.ru
list.clear()
. del a[:].
>>> a = [1, 2, 3, 4, 5]
>>> print(a)
[1, 2, 3, 4, 5]
>>> a.clear()
>>> print(a)
[]
list.count(x)
x .
>>> a=[1, 2, 2, 3, 3]
>>> print(a.count(2))
2
list.sort(key=None, reverse=False)
.
reverse=True.
key, .
>>> a = [1, 4, 2, 8, 1]
>>> a.sort()
>>> print(a)
[1, 1, 2, 4, 8]
list.reverse()
.
>>> a = [1, 3, 5, 7]
>>> a.reverse()
>>> print(a)
[7, 5, 3, 1]
68
devpractice.ru
list.copy()
. a[:].
>>> a = [1, 7, 9]
>>> b = a.copy()
>>> print(a)
[1, 7, 9]
>>> print(b)
[1, 7, 9]
>>> b[0] = 8
>>> print(a)
[1, 7, 9]
>>> print(b)
[8, 7, 9]
list comprehensions :
n = int(input())
a = [i for i in range(n)]
print(a)
, n:
a = [i for i in range(int(input()))]
print(a)
69
devpractice.ru
8. (tuple)
(tuple) Python.
,
. .
, ..
.
>>> b = (1, 2, 3)
>>> print(b)
(1, 2, 3)
>>> b[1] = 15
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
b[1] = 15
TypeError: 'tuple' object does not support item assignment
8.2 Python?
,
. .
- , ,
70
devpractice.ru
, , ,
. ,
-, .
,
.
>>> lst = [10, 20, 30]
>>> tpl = (10, 20, 30)
>>> print(lst.__sizeof__())
32
>>> print(tpl.__sizeof__())
24
- , ,
, (.. ..
). ,
.
8.3 ,
8.3.1
.
>>> a = ()
>>> print(type(a))
<class 'tuple'>
>>> b = tuple()
>>> print(type(b))
<class 'tuple'>
71
devpractice.ru
,
.
>>> a = (1, 2, 3, 4, 5)
>>> print(type(a))
<class 'tuple'>
>>> print(a)
(1, 2, 3, 4, 5)
tuple().
>>> a = tuple((1, 2, 3, 4))
>>> print(a)
(1, 2, 3, 4)
8.3.2
. , !
>>> a = (1, 2, 3, 4, 5)
>>> print(a[0])
1
>>> print(a[1:3])
(2, 3)
>>> a[1] = 3
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
a[1] = 3
TypeError: 'tuple' object does not support item assignment
8.3.3
.
>>> a = (1, 2, 3, 4, 5)
>>> del a[0]
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
del a[0]
TypeError: 'tuple' object doesn't support item deletion
72
devpractice.ru
.
>>> del a
>>> print(a)
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
print(a)
NameError: name 'a' is not defined
8.3.4
, .
tuple().
>>> lst = [1, 2, 3, 4, 5]
>>> print(type(lst))
<class 'list'>
>>> print(lst)
[1, 2, 3, 4, 5]
>>> tpl = tuple(lst)
>>> print(type(tpl))
<class 'tuple'>
>>> print(tpl)
(1, 2, 3, 4, 5)
.
>>> tpl = (2, 4, 6, 8, 10)
>>> print(type(tpl))
<class 'tuple'>
>>> print(tpl)
(2, 4, 6, 8, 10)
>>> lst = list(tpl)
>>> print(type(lst))
<class 'list'>
>>> print(lst)
[2, 4, 6, 8, 10]
73
devpractice.ru
9. (dict)
9.2 , ,
9.2.1
, dict(),
.
>>> d1 = dict()
>>> print(type(d1))
<class 'dict'>
>>> d2 = {}
>>> print(type(d2))
<class 'dict'>
,
,
-.
>>> d1 = dict(Ivan="manager", Mark="worker")
>>> print(d1)
{'Mark': 'worker', 'Ivan': 'manager'}
>>> d2 = {"A1":"123", "A2":"456"}
>>> print(d2)
{'A2': '456', 'A1': '123'}
74
devpractice.ru
9.2.2
.
>>> d1 = {"Russia":"Moscow", "USA":"Washington"}
>>> d1["China"]="Beijing"
>>> print(d1)
{'Russia': 'Moscow', 'China': 'Beijing', 'USA': 'Washington'}
del.
>>> d2 = {"A1":"123", "A2":"456"}
>>> del d2["A1"]
>>> print(d2)
{'A2': '456'}
9.2.3
in.
>>> d2 = {"A1":"123", "A2":"456"}
>>> "A1" in d2
True
>>> "A3" in d2
False
, ,
.
>>> d1 = {"Russia":"Moscow", "USA":"Washington"}
>>> d1["Russia"]
'Moscow'
75
devpractice.ru
9.3
.
clear()
.
>>> d2 = {"A1":"123", "A2":"456"}
>>> print(d2)
{'A2': '456', 'A1': '123'}
>>> d2.clear()
>>> print(d2)
{}
copy()
.
>>> d2 = {"A1":"123", "A2":"456"}
>>> d3 = d2.copy()
>>> print(d3)
{'A1': '123', 'A2': '456'}
>>> d3["A1"]="789"
>>> print(d2)
{'A2': '456', 'A1': '123'}
>>> print(d3)
{'A1': '789', 'A2': '456'}
fromkeys(seq[, value])
seq value.
value None.
get(key)
key.
>>> d = {"A1":"123", "A2":"456"}
>>> d.get("A1")
'123'
76
devpractice.ru
items()
(, ) .
>>> d = {"A1":"123", "A2":"456"}
>>> d.items()
dict_items([('A2', '456'), ('A1', '123')])
keys()
.
>>> d = {"A1":"123", "A2":"456"}
>>> d.keys()
dict_keys(['A2', 'A1'])
pop(key[, default])
key ,
, default.
default ,
KeyError.
>>> d = {"A1":"123", "A2":"456"}
>>> d.pop("A1")
'123'
>>> print(d)
{'A2': '456'}
popitem()
(, ) . ,
KeyError.
>>> d = {"A1":"123", "A2":"456"}
>>> d.popitem()
('A2', '456')
>>> print(d)
{'A1': '123'}
77
devpractice.ru
setdefault(key[, default])
key , .
, key default,
default , None.
>>> d = {"A1":"123", "A2":"456"}
>>> d.setdefault("A3", "777")
'777'
>>> print(d)
{'A2': '456', 'A3': '777', 'A1': '123'}
>>> d.setdefault("A1")
'123'
>>> print(d)
{'A2': '456', 'A3': '777', 'A1': '123'}
update([other])
(key/value) other, ,
.
>>> d = {"A1":"123", "A2":"456"}
>>> d.update({"A1":"333", "A3":"789"})
>>> print(d)
{'A2': '456', 'A3': '789', 'A1': '333'}
values()
.
>>> d = {"A1":"123", "A2":"456"}
>>> d.values()
dict_values(['456', '123'])
78
devpractice.ru
10. Python
Python (
, ..). lambda-,
.
10.1 Python?
Python
.
,
( lambda-, , ).
, ,
,
.
10.2
def,
.
( ): .
, , .
def fun():
pass
return,
.
.
>>> def fun():
return 1
>>> fun()
1
79
devpractice.ru
10.3
.
, .
.
.
>>> def summa(a, b):
return a + b
>>> summa(3, 4)
7
:
.
.
>>> def fibb(n):
if n == 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 1
else:
return fibb(n-1) + fibb(n-2)
>>> print(fibb(10))
55
.
>>> def factorial(n):
prod = 1
for i in range(1, n+1):
prod *= i
return prod
>>> print(factorial(5))
120
80
devpractice.ru
,
.
math.
>>> import math
>>> f = math.factorial
>>> print(f(5))
120
10.4 Lambda-
Lambda-
.
( ).
- ( filter(), map() reduce())
, , ,
.
>>> (lambda x: x**2)(5)
25
Lambda- -
.
>>> sqrt = lambda x: x**0.5
>>> sqrt(25)
5.0
lambda- map(),
filter(), reduce(). map , ,
, ,
.
>>> l = [1, 2, 3, 4, 5, 6, 7]
>>> list(map(lambda x: x**3, l))
[1, 8, 27, 64, 125, 216, 343]
81
devpractice.ru
11.
.
,
Python, .
11.1
(exceptions) ,
,
.
,
(), , ..
, ,
,
(exception handling).
.
. ,
, ,
.
, , ,
- , .
.
. ,
,
. , , ,
, , .
.
,
.
,
82
devpractice.ru
, ,
.
Python :
.
11.2 Python
Python .
. print.
>>> for i in range(10):
prin("hello!")
11.3 Python
.
,
( ..). ,
.
ZeroDivisionError, 0.
>>> a = 10
>>> b = 0
>>> c = a / b
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
c = a / b
ZeroDivisionError: division by zero
Python ,
() .
,
83
devpractice.ru
, .
11.4 Python
Python, , ,
.
BaseException
+ SystemExit
+ KeyboardInterrupt
+ GeneratorExit
+ Exception
+ StopIteration
+ StopAsyncIteration
+ ArithmeticError
| + FloatingPointError
| + OverflowError
| + ZeroDivisionError
+ AssertionError
+ AttributeError
+ BufferError
+ EOFError
+ ImportError
+ ModuleNotFoundError
+ LookupError
| + IndexError
| + KeyError
+ MemoryError
+ NameError
| + UnboundLocalError
+ OSError
| + BlockingIOError
| + ChildProcessError
| + ConnectionError
| | + BrokenPipeError
| | + ConnectionAbortedError
| | + ConnectionRefusedError
| | + ConnectionResetError
| + FileExistsError
| + FileNotFoundError
| + InterruptedError
| + IsADirectoryError
| + NotADirectoryError
84
devpractice.ru
| + PermissionError
| + ProcessLookupError
| + TimeoutError
+ ReferenceError
+ RuntimeError
| + NotImplementedError
| + RecursionError
+ SyntaxError
| + IndentationError
| + TabError
+ SystemError
+ TypeError
+ ValueError
| + UnicodeError
| + UnicodeDecodeError
| + UnicodeEncodeError
| + UnicodeTranslateError
+ Warning
+ DeprecationWarning
+ PendingDeprecationWarning
+ RuntimeWarning
+ SyntaxWarning
+ UserWarning
+ FutureWarning
+ ImportWarning
+ UnicodeWarning
+ BytesWarning
+ ResourceWarning
,
BaseException.
https://docs.python.org/3/library/exceptions.html.
11.5 Python
,
, . ,
tryexcept.
85
devpractice.ru
print("start")
try:
val = int(input("input number: "))
tmp = 10 / val
print(tmp)
except Exception as e:
print("Error! " + str(e))
print("stop")
ValueError, , ,
, ZeroDivisionError 0.
.
start
input number: 0
Error!
stop
tryexcept ,
.
print(start)
val = int(input(input number: ))
tmp = 10 / val
print(tmp)
print(stop)
0 ,
.
start
input number: 0
Traceback (most recent call last):
File "F:/work/programming/python/devpractice/tmp.py", line 3, in <module>
tmp = 10 / val
ZeroDivisionError: division by zero
, stop .
86
devpractice.ru
Python, ,
try :
, try except.
, except
, try .
, try
except. except ,
. ,
except, .
except ,
try. ,
, (unhandled exception)
.
,
except ()
except.
ValueError
ZeroDivisionError, .
print("start")
try:
val = int(input("input number: "))
tmp = 10 / val
print(tmp)
except(ValueError, ZeroDivisionError):
print("Error!")
print("stop")
87
devpractice.ru
, ValueError, ZeroDivisionError , ,
,
.
print("start")
try:
val = int(input("input number: "))
tmp = 10 / val
print(tmp)
except ValueError:
print("ValueError!")
except ZeroDivisionError:
print("ZeroDivisionError!")
except:
print("Error!")
print("stop")
except.
print("start")
try:
val = int(input("input number: "))
tmp = 10 / val
print(tmp)
except ValueError as ve:
print("ValueError! {0}".format(ve))
except ZeroDivisionError as zde:
print("ZeroDivisionError! {0}".format(zde))
except Exception as ex:
print("Error! {0}".format(ex))
print("stop")
11.6 finally
try/except, finally.
88
devpractice.ru
try:
val = int(input("input number: "))
tmp = 10 / val
print(tmp)
except:
print("Exception")
finally:
print("Finally code")
, try
, finally .
- ,
try , else.
try:
f = open("tmp.txt", "r")
for line in f:
print(line)
f.close()
except Exception as e:
print(e)
else:
print("File was readed")
11.7 Python
raise.
raise .
try:
raise Exception("Some exception")
except Exception as e:
print("Exception exception " + str(e))
, .
89
devpractice.ru
11.8 (User-defined
Exceptions) Python
Python .
,
.
,
.
class NegValException(Exception):
pass
try:
val = int(input("input positive number: "))
if val < 0:
raise NegValException("Neg val: " + str(val))
print(val + 10)
except NegValException as e:
print(e)
90
devpractice.ru
12. - .
Python
: , , .
12.1
Python
. ,
, .
print.
.
>>> print("Hello")
Hello
>>> print("Hello, " + "world!")
Hello, world!
>>> print("Age: " + str(23))
Age: 23
, print .
>>> print("A", "B", "C")
A B C
sep print.
print("A", "B", "C", sep="#")
A#B#C
,
.
>>> for i in range(3):
print("i: " + str(i))
i: 0
i: 1
i: 2
91
devpractice.ru
end.
>>> for i in range(3):
print("[i: " + str(i) + "]", end=" -- ")
[i: 0] -- [i: 1] -- [i: 2] --
12.2
input().
>>> input()
test
'test'
.
>>> a = input()
hello
>>> print(a)
hello
, ,
input(), int().
>>> val = int(input())
123
>>> print(val)
123
>>> type(val)
<class 'int'>
-,
input().
92
devpractice.ru
split(),
, , .
>>> l = input().split()
1 2 3 4 5 6 7
>>> print(l)
['1', '2', '3', '4', '5', '6', '7']
, split().
>>> nl = input().split("-")
1-2-3-4-5-6-7
>>> print(nl)
['1', '2', '3', '4', '5', '6', '7']
int
.
>>> nums = map(int, input().split())
1 2 3 4 5 6 7
>>> print(list(nums))
[1, 2, 3, 4, 5, 6, 7]
12.3
12.3.1
open(),
.
open(_, _).
:
r ;
w ;
x , ,
open ;
a ,
, ;
b ;
t ;
+ .
93
devpractice.ru
.
.
file.closed true false ;
file.mode ,
;
file.name .
>>> f = open("test.txt", "r")
>>> print("file.closed: " + str(f.closed))
file.closed: False
>>> print("file.mode: " + f.mode)
file.mode: r
>>> print("file.name: " + f.name)
file.name: test.txt
close().
12.3.2
read()
readline().
read() ,
. ,
.
>>> f = open("test.txt", "r")
>>> f.read()
'1 2 3 4 5\nWork with file\n'
>>> f.close()
,
.
>>> f = open("test.txt", "r")
>>> f.read(5)
'1 2 3'
>>> f.close()
94
devpractice.ru
readline() .
>>> f = open("test.txt", "r")
>>> f.readline()
'1 2 3 4 5\n'
>>> f.close()
for.
>>> f = open("test.txt", "r")
>>> for line in f:
... print(line)
...
1 2 3 4 5
Work with file
>>> f.close()
12.3.3
write(),
.
>>> f = open("test.txt", "a")
>>> f.write("Test string")
11
>>> f.close()
12.3.4
tell() .
, , 5.
>>> f = open("test.txt", "r")
>>> f.read(5)
'1 2 3'
>>> f.tell()
5
>>> f.close()
95
devpractice.ru
seek() .
>>> f = open("test.txt", "r")
>>> f.tell()
0
>>> f.seek(8)
8
>>> f.read(1)
'5'
>>> f.tell()
9
>>> f.close()
with.
,
, .
>>> with open("test.txt", "r") as f:
... for line in f:
... print(line)
...
1 2 3 4 5
Work with file
Test string
>>> f.closed
True
96
devpractice.ru
13.
. , ,
,
, , , .
.
13.1 Python
13.1.1 Python?
Python .py.
, , ,
.. :
,
. ,
Python, ( C).
13.1.2 Python?
Python
:
import _
math,
, .
>>> import math
>>> math.factorial(5)
120
,
import:
import _1, _2
97
devpractice.ru
>>> import math, datetime
>>> math.cos(math.pi/4)
0.707106781186547
>>> datetime.date(2017, 3, 21)
datetime.date(2017, 3, 21)
,
:
import _ as _
>>> import math as m
>>> m.sin(m.pi/3)
0.866025403784438
,
, (
). , from
import
from _ import _
>>> from math import cos
>>> cos(3.14)
0.999998731727539
( :
cos), , .
>>> from math import cos
>>> cos(3.14)
-0.999998731727539
>>> sin(3.14)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
sin(3.14)
NameError: name 'sin' is not defined
>>> math.sin(3.14)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
math.sin(3.14)
NameError: name 'math' is not defined
98
devpractice.ru
,
.
from _ import _1, _2
>>> from math import cos, sin, pi
>>> cos(pi/3)
0.500000000000000
>>> sin(pi/3)
0.866025403784438
.
from _ import _ as _
>>> from math import factorial as f
>>> f(4)
24
, .. ,
from import
from _ import *
>>> from math import *
>>> cos(pi/2)
6.123233995736766e-17
>>> sin(pi/4)
0.707106781186547
>>> factorial(6)
720
13.2 Python
13.2.1 Python?
Python , ,
__init__.py.
,
( ).
,
.
99
devpractice.ru
13.2.2 Python
:
fincalc
|-- __init__.py
|-- simper.py
|-- compper.py
|-- annuity.py
fincal
(simper.py), (compper.py) (annuity.py).
,
:
import fincalc.simper
fv = fincalc.simper.fv(pv, i, n)
import fincalc.simper as sp
fv =sp.fv(pv, i, n)
__init__.py __all__,
,
from _ import *
__init__.py :
__all__ = ["simper", "compper", "annuity"]
100
devpractice.ru
14.
- Python.
, ,
Python.
14.1 -
- ()
,
, ,
.
. .
- ,
.
()
( ). ,
, :
, , , ..,
: / , /.
.
, .
.
.
, , ( )
.
, ,
, : , ,
: .
, ,
101
devpractice.ru
, : ,
..
,
, .
,
, .. ,
( ).
.
,
.
14.2 Python
14.2.1
Python class.
.
class C:
pass
( class), (
C) , (
pass).
:
_ = _()
. ,
color (), width (), height ().
class Rectangle:
color = green
width = 100
height = 100
102
devpractice.ru
.
_.
rect1 = Rectangle()
print(rect1.color)
.
, , , ,
. , Rectangle,
, . , ,
( , :
(width) (height)),
self, .
class Rectangle:
color = "green"
width = 100
height = 100
def square(self):
return self.width * self.height
, ,
, :
class Rectangle:
color = "green"
width = 100
height = 100
def square(self):
return self.width*self.height
rect1 = Rectangle()
print(rect1.color)
print(rect1.square())
rect2 = Rectangle()
rect2.width = 200
rect2.color = "brown"
print(rect2.color)
print(rect2.square())
103
devpractice.ru
14.2.2
.
. :
__init__(self)
, , ,
, Rectangle :
class Rectangle:
def __init__(self, color="green", width=100, height=100):
self.color = color
self.width = width
self.height = height
def square(self):
return self.width * self.height
rect1 = Rectangle()
print(rect1.color)
print(rect1.square())
rect1 = Rectangle("yellow", 23, 34)
print(rect1.color)
print(rect1.square())
14.3
:
. ,
.
, Python .
/ :
class _(_1, [_2,, __n])
, .
class Figure:
def __init__(self, color):
self.color = color
def get_color(self):
return self.color
104
devpractice.ru
class Rectangle(Figure):
def __init__(self, color, width=100, height=100):
super().__init__(color)
self.width = width
self.height = height
def square(self):
return self.width*self.height
rect1 = Rectangle("blue")
print(rect1.get_color())
print(rect1.square())
rect2 = Rectangle("red", 25, 70)
print(rect2.get_color())
print(rect2.square())
14.4
, ,
. .
info(), Figure
Rectangle,
.
class Figure:
def __init__(self, color):
self.color = color
def get_color(self):
return self.color
def info(self):
print("Figure")
print("Color: " + self.color)
105
devpractice.ru
class Rectangle(Figure):
def __init__(self, color, width=100, height=100):
super().__init__(color)
self.width = width
self.height = height
def square(self):
return self.width * self.height
def info(self):
print("Rectangle")
print("Color: " + self.color)
print("Width: " + str(self.width))
print("Height: " + str(self.height))
print("Square: " + str(self.square()))
fig1 = Figure("green")
print(fig1.info())
rect1 = Rectangle("red", 24, 45)
print(rect1.info())
106
devpractice.ru
15.
, , ,
.
Python,
.
15.1 Python
.
, , , (,
..). Python, ,
. ,
, ,
.
for.
for, ,
, ,
, /,
, , ,
for .
, .
.
>>> num_list = [1, 2, 3, 4, 5]
>>> for i in num_list:
print(i)
1
2
3
4
5
, , for,
, ,
107
devpractice.ru
iter(),
next().
>>> itr = iter(num_list)
>>> print(next(itr))
1
>>> print(next(itr))
2
>>> print(next(itr))
3
>>> print(next(itr))
4
>>> print(next(itr))
5
>>> print(next(itr))
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print(next(itr))
StopIteration
next(itr)
, ,
StopIteration.
15.2
,
. ,
, ,
. ,
__next__(),
.
108
devpractice.ru
class SimpleIterator:
def __init__(self, limit):
self.limit = limit
self.counter = 0
def __next__(self):
if self.counter < self.limit:
self.counter += 1
return 1
else:
raise StopIteration
s_iter1 = SimpleIterator(3)
print(next(s_iter1))
print(next(s_iter1))
print(next(s_iter1))
print(next(s_iter1))
next()
StopIteration. ,
for, SimpleIterator __iter__(),
, self.
class SimpleIterator:
def __iter__(self):
return self
def __init__(self, limit):
self.limit = limit
self.counter = 0
def __next__(self):
if self.counter < self.limit:
self.counter += 1
return 1
else:
raise StopIteration
s_iter2 = SimpleIterator(5)
for i in s_iter2:
print(i)
109
devpractice.ru
15.3
. , ,
. ,
next() .
return yield.
. ,
.
def simple_generator(val):
while val > 0:
val -= 1
yield 1
gen_iter = simple_generator(5)
print(next(gen_iter))
print(next(gen_iter))
print(next(gen_iter))
print(next(gen_iter))
print(next(gen_iter))
print(next(gen_iter))
, SimpleIterator
.
,
yield , ,
next(). , -
return,
StopIteration, return - ,
StopIteration.
110
devpractice.ru