Вы находитесь на странице: 1из 110

. .

(Start with Python)

Revision: 170

: 170

........................................................................................................................................ 2
...................................................................................................................................... 5
...................................................................................................................................7
............................................................................................................................................. 8
0.1. ......................................................................................................................9
0.2. ?..........................................................................9
0.3. UNIX............................................................ 10
0.3.1. / rpm-......................................................... 10
0.3.2. .......................................................................10
0.4. Windows..................................................................................... 11
0.5. , ........................................................................11
0.6. ................................................................................................................ 12
1. .............................................................................................................14
1.1. ................................................................................................... 14
1.2. ............................................................. 14
1.3. .................................................................................. 16
1.4. .......................................................................................18
1.5. ............................................................................................................... 19
1.6. ?..............................................................................................................20
1.6.1. (syntax errors).................................................................... 20
1.6.2. (runtime errors)........................................................................ 21
1.6.3. (semantic errors).................................................................. 21
1.6.4. ..........................................................................................................21
2. , .........................................................................23
2.1. ..................................................................................................................23
2.2. ........................................................................................................24
2.3. ......................................................................................................................... 25
2.4. ..............................................................................26
2.5. ...........................................................................................................................28
2.6. .....................................................................................................28
2.7. .......................................................................................................30
2.8. ...............................................................................................................30
2.9. ................................................................................ 31
2.10. ....................................................................................................................... 32
3. ........................................................................................................................... 34
3.1. .................................................................................................................... 34
3.2. .................................................................................................................35
3.3. ............................................................................................................35
3.4. .................................................................. 36
3.5. ......................................................................................................................... 37
3.6. .............................................................................................................. 38
3.7. ..................................................................................................... 40
3.8. ......................................................................................................40
3.9. .............................................................................................................. 43
3.10. ........................................................................................................44
3.11. , ............................................................................... 46
4. ................................................................................................ 48
2

: 170

5. , ........................................................... 49
5.1. ...............................................................................................49
5.2. ...........................................50
5.3. ....................................................................................................... 51
5.4. ............................................................................... 52
5.5. ................................................................................................ 54
5.6. (Chained conditionals)..............................................55
5.7. .......................................................................................................................56
5.8. (Nested conditionals)................................................... 57
5.9. ...............................................................................................................................59
5.10. ..................................................................60
5.11. .................................................................................... 62
5.12. ..............................................................................................................62
6. ............................................................................................................................... 64
6.1. while......................................................................................................... 64
6.2. .............................................................................................................................. 65
6.3. ............................................................................................................ 66
6.4. while....................................................................................67
6.5. .................................................................................................... 67
6.6. ...........................................................................69
6.7. while....................................................................... 72
6.8. ...................................................... 73
6.9. .................................................................................... 74
6.10. ................................................................................................. 75
7. .............................................................................................................................. 76
7.1. ................................................................................................. 76
7.2. ......................................................................... 76
7.3. for.............................................................................................................. 77
7.4. ......................................................................................................................... 78
7.5. ..................................................................................................................79
7.6. .....................................................................................................79
7.7. find........................................................................................................................80
7.8. ............................................................................................................... 81
7.9. string....................................................................................................................... 81
7.10. ................................................................................................ 82
7.11. unicode.................................................................................................................. 83
8. .............................................................................................................................. 84
8.1. ................................................................................................................84
8.2. ................................................................................................84
8.3. ....................................................................................................................... 84
8.4. .....................................................................................................84
8.5. for............................................................................................................... 84
8.6. ..................................................................................................... 84
8.7. ..................................................................................................................... 84
8.8. ............................................................................................................. 84
8.9. ...............................................................................................84
8.10. ..........................................................................................................84
8.11. ........................................................................................................... 84
8.12. ....................................................................................................... 84
3

: 170

8.13. -............................................................................................................84
8.14. ............................................................................................................84
8.15. ............................................................................................................................ 84
8.16. ................................................................................................................84
9. ............................................................................................................................ 85
10. .......................................................................................................................... 86
10.1. .............................................................................................................. 86
10.2. ................................................................................................. 86
10.3. .............................................................................................................. 87
10.4. ................................................................. 88
10.5. ......................................................................................................88
10.6. .......................................................................................................................... 90
10.7. ............................................................................................. 91
10.8. ..................................................................................................................... 91
11. ...............................................................................93
12. .........................................................................................................94
13. ........................................................................................................95
14. ........................................................................................................................... 96
15. .......................................................................................................... 97
16. .................................................................................................................98
17. ............................................................................................................ 99
18. ............................................................................................................................. 100
19. ........................................................................ 101
20. ......................................................................................................................... 102
21. .....................................................................103
. ................................................................................. 104
A. ........................................................................105
B. ............................................................. 106
C. ..................................................................................107
D. ................................. 108
E. ...........................................................109
F. ................................................... 110

: 170

, 2002 php,
. -,
- ,
php :
, .
, php ,
. , ,
/.
php. php perl,
. C++
web-, ..
. (Python, http://python.org).
, ,
.
Psion.
How to think like a computer
scientist. Learning with Python (http://greenteapress.com/thinkpython/).
, . ,
, ,
.
.
,
- 9 13 .
, ..
, , .
C++ , .. . .
, ,
, .
, ,
Ruby ( http://ruby-lang.org/en/), . Ruby, perl,
, ,
. .
, How to think
like a computer scientist.
, ,
. , .
, How to think like a
computer scientist, . ,
.
, :
,
.
OPL (http://www.opencontent.org/openpub/)
VI-B. ,
, .
5

: 170

,
. . Take it. Use it.
:)

: 170

, .
, - , OPL.
, :













(http://opensource.org/), , , .

OpenOffice.org (http://OpenOffice.org/, http://OpenOffice.ru/) ,
.

: 170

,
. :
.
, .
,
.
.
? ,
:
.
;
:

?!
?!
:
, .
TCP/IP,
UNIX,
?
( )
, , . ?

.
: ,
, .
-.
, ,
-,
. - : .
,
. ,
, .
, ,
. ,
, ,
. ,
, , .

. ,
. ,

.
, .
, , .
8

: 170

, ,
. ,
, .

0.1.
, ,
, :
();
;
;
UNIX-,
;
;
.
, (MS Office, OpenOffice.org, StarOffice
) .
MS Notepad ( ).
, ,
, .
,
: Windows, UNIX (GNU/Linux,
FreeBSD .) Mac OS X. , ,
,
!
GNU/Linux,
, . -
. , open source,
.
2.3.3 ,
.

.

0.2. ?
Python
Software Foundation (PSF) Licence (http://python.org/psf/license.html), ,
, , GNU GPL (GNU General Public License:
http://gnu.org/copyleft/).
http://python.org/. Downloads
. UNIX-
: ( .tar.gz), rpm- (.rpm, .src.rpm,
) .deb ( Debian Linux).
Windows exe-,
.
9

: 170

0.3. UNIX
UNIX- ( BSD-, GNU/Linux,
Solaris .) . GNU/Linux,
RPM, UNIX
, rpm-.
RPM-based GNU/Linux (RedHat Linux, Mandrake, SuSE Linux, ASPLinux,
ALTLinux) rpm.
.
(root). ,
, , ,
.

0.3.1. / rpm-
,
:
$ su Password:
#

, rpm- (
, ):
# rpm -i python-x.x.rpm

0.3.2.
:
$ gzip -cd python-x.x.tar.gz | tar xvf -

, :
$ ./configure

:
$ make


make install:
$ su Password:
# make install

-, UNIX-
.
/usr/local/src/.

10

: 170

0.4. Windows
Windows , UNIX.
(, Python-2.3.3.exe),
, Next.
.
C:\PythonXX, XX .
Next.
, .
, No, do not make backups.
.
, ( , ).
20 .
, .
Next .
Next . Finish
.

0.5. ,
, , , UNIX-

, :
$ python my_program.py

, UNIX ,
.
:
#! /usr/bin/env python

:
$ chmod u+x my_program.py

,
:
$ my_program.py

, :
$ ./my_program.py

#! she-bang!.
Windows ,
, ,
. .py
,
, , .
, Windows .
,
11

: 170

. ,
:
raw_input("Press any key to exit")

,
.
,
. Windows .py .
pyw. , ,
. .pyw ,
, .
MS-DOS ( FAR)
:
C:\Examples> python my_program.py

,
.

0.6.

IDLE, ,
. IDLE
Tcl, ,
. IDLE ,
, . -
IDLE , .
UNIX- , ,
(vi, emacs, mc), (vim,
emacs, kate, IDLE .).
Kate
KDE . Kate
, ,
, : ,
.
: SciTE (http://scintilla.org/SciTE.html).
,
, (
), , SciTE ,
.
Windows
, IDLE.
-, PythonWin Windows
( http://pywin32.sf.net). PythonWin
,
.

12

: 170

UniRed (
http://www.esperanto.mv.ru/UniRed/RUS/index.html).
Windows 95/98/NT/2000/XP, ,
( Unicode).
,
FAR. , Norton Volkov Commander, FAR'.
, Windows,
, DOS.
Windows FAR, ,
.

. , .

13

: 170

1.
.
.
, . , ,
.

1.1.

. , ,
. , ,
,
. ,
. ,
. ,
: , ..
, ,
.
.
. , -
, .
,
, .
, .
, , , .
.

1.2.
.
.
- ,
, , ,
.
, ,
.
.
, , ,
, , .
( . Mnemonikos
mnemon )
, , .
.
,
.

14

: 170


. -
.
,
,
. ,
:
, - ;
, , ;
, ;
(,
);

.
, .
, ,
, .
.
, ..
.
. ,
, :
1. edx
- 10
eax 0
lp:
eax ,
edx
, l_next
eax ,
edx
l_next:
edx 4
- 0, 1 lp
Max eax
2. Max 0
i 1 10 +1:
i- Max,
Max
Max.

15

: 170

.
(
), , .
, ,
.. .
: ,
, . ,

,
,
,
.
, .
,
. , Intel 80286
, .. edx eax Intel 80386.
C1 Pascal.
, , ,
, . , , ,
,
, , , .
,
, , .

. ,
. Python,
.

1.3.
, ,
. :
.
, : ,
, , . ,
, - .
, .
, ,
.
: ( ,
, IV ..) 4000 . 8
, 3 , ,
. ,
,
, ,
.
1 .

16

: 170

, , .
- () XIX .
,
.
,
, , , , ,
, . ,
, .
, ,
, . ( )
, ,
( - ) . Esperanto estas tre interesa kaj
esprima lingvo.
? , . ,
, . , , .
,
. , ,
, .

. ,
.
, .
, 3+3=6 , 3=+6$
. H2O , 2Zz .
,
, .
. parsing.
, ,
()
(). , .
,
, .
,
(tokens) .
, , , ,
.
$ 3=+6$ ,
, .
2Zz: Zz.
, ..
. 3=+6$ ,
.. . ,
,
.
17

: 170

,
:
1.
;
, .
, .
,
.
2.

: .
.
, ,
( ). ,
, .
,
. , , .
( ),
, ,
.
, .
.

1.4.
,
: . ( ) ,
, . .

,
( ),
.
, .
, ,

.

()

,
,
. ,
18

: 170

,
.
,
,
2.
, ..
.
Windows- : py2exe,
exe- .
py2exe


.
, exe- dll-,
.
.
,
Windows.

, py2exe .
py2exe :
http://starship.python.net/crew/theller/py2exe/.
.

1.5.
.
:
.
, :
$ python
Python 2.3+ (#1, Sep 23 2003, 23:07:16)
[GCC 3.3.1 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>> print "Hello world!"
Hello world!

,
UNIX. Windows
IDLE.
( ,
2 ,
(,

).

19

: 170

). >>>,
,

print "Hello world!", .. "Hello world!",


, .
,
. ( . script
). , , prog1.py
:
print "Hello world!"

, ,
.py (, DOS
Windows, ). ,
:
$ python prog1.py
Hello world!

,
.
. ,
: ,
(.. ),
( ).
.

1.6. ?
, ,
. ,
( . bug ). ,
.
debugging,
.
, :
(syntax errors), (runtime errors)
(semantic errors). ,
.

1.6.1. (syntax errors)


,
.
,
. (.. ,
), .

. , ,
, .
20

: 170

( )
.
,
, , .
.
, , ,
. ,
.

1.6.2. (runtime errors)


(
, , -
exceptions). . ,
, - : ,
,
- , .
,
. , ,
, .

1.6.3. (semantic errors)


.
, , ..
, , .
,
, . , ..
,
.

1.6.4.
.

.
,
.
.
, ,
, , .
,
, .
,
, ,
.

, -
21

: 170

.
.
,
.
.
: , ,

. .
Linux, ,
, (Linus Torvalds)
Intel 80386.
, :
AAAA BBBB. Linux (Larry
Greenfield, The Linux Users' Guide Beta Version 1).
, ,
, . ,
- ,
, .
, , , - ,
, .
.
- A
, , .

22

: 170

2. ,
, , .
. ,
. -
pythonbook@it-arts.ru. ,
.

2.1.
. .
,
"Hello world!". :
>>> print 12
12
"Hello world!" 12 : str ( . string )

int ( . integer )3. ,

.
, , , .
:
>>> print 2,4
2 4

: ,
,
, . , ,
,
, 4:
>>> print 2.4
2.4

, ,
:
>>> type("Hello world!")
<type 'str'>
>>> type(12)
<type 'int'>
>>> type(2.4)
<type 'float'>

str, int,
float ( . floating-point number ).
3 : string integer.
4
.

23

: 170

. :
"12" "2.4"? ?
. , "8.53"
int()? ?

2.2.

, ? ,
.. .

, . ,
int() .
, :
>>> int("32")
32
>>> int("Hello")
Traceback (most recent call last):
File "", line 1, in ?
ValueError: invalid literal for int(): Hello

int() , ,
:
>>> int(3.99999)
3
>>> int(-2.3)
-2

float() .
>>> float(32)
32.0
>>> float("3.14159")
3.14159

, , str() .
print:
>>> str(32)
'32'
>>> str(3.14149)
'3.14149'

24

: 170

, 1 1.0:
, . ,
.

2.3.

, . C++ Pascal
, ,
. , , ,
. , .
, .

(=).
>>> message = "Hello world!"
>>> n = 12
>>> pi = 3.14159

message ( )
"Hello world!", n 12, pi 3.14159.
:
, , .
(state diagram), ..
, , ..
.
Hello world!
12
3.14159

message
n
pi
print :
>>> print message
Hello world!
>>> print n
12
>>> print pi
3.14159

, print , . ,
, . type():
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)

25

: 170

<type 'float'>

.
:
>>> message = "Hello world!"
>>> n = 12
>>> type(message)
<type 'str'>
>>> message = n
>>> print message
12
>>> type(message)
<type 'int'>

. -,
. message = n
: message
n. 12
.
Hello world!

message

12

-, , message
n .
.

2.4.
(Frederick P. Brooks, Jr)5,
, :
, .
,
, ,
, . , , ,
, , .
.
,

.

, _ ( ).
5 (Frederick P. Brooks, Jr) IBM OS/360;
No Silver Bullet (NSB ,
- ). -,
.

26

: 170

: , user_name full_price.
.
>>> 1message = "Hello world!"
File "<stdin>", line 1
1message = "Hello world!"
^
SyntaxError: invalid syntax
>>> price_in_$ = 300
File "<stdin>", line 1
price_in_$ = 300
^
SyntaxError: invalid syntax
>>> class = "Computer Science 101"
File "<stdin>", line 1
class = "Computer Science 101"
^
SyntaxError: invalid syntax

. ,
^, :
1message. , 1message ,
. price_in_$:
$. ?
class - , , class_:
>>> class_ = "Computer Science 101"
>>> print class_
Computer Science 101

. ? class ,
class_ ? ? :
>>> print = "Some message"
File "<stdin>", line 1
print = "Some message"
^
SyntaxError: invalid syntax

, ? , .
print ,
class, , - .
, class print .
2.3. 29 :

27

: 170

and

del

for

is

raise

assert

elif

from

lambda

return

break

else

global

not

try

class

except

if

or

while

continue

exec

import

pass

yield

def

finally

in

print

, ,
.
, , ..
message Message .
. , ,
.

2.5.

. .
,
. , print "Hello world!" message = n
.
,
, . print "Hello world!"
: Hello world!. .
,
. , ,
:
print 1
x = 2
print x

:
1
2

2.6.
, , .
, , , :
>>> 1 + 1
2

, :
28

: 170

>>> 17
17
>>> x = 2
>>> x
2

:
>>> message = "Hello world!"
>>> message
"Hello world!"
>>> print message
Hello world!

,
, . ,
. print ,
, .
, , print.
, :
17
3.2
"Hello, World!"
1 + 1

. ,
.

_ ( ).
:
>>> 1.25 + 1
2.25
>>> print _
2.25
>>> 5 + _
7.25

.
,
.

29

: 170

2.7.
( ),
. , + ,
* . , ,
.
, , :
20+32

hour-1

hour*60+minute

minute/60

5**2

(5+9)*(15-7)

. +, -, * /
, . ,
(**) .
,
, .
, ,
, .
:
>>> minute = 59
>>> minute/60
0

minute 59; 59 60
0.98333, 0. ,
.
, ,
. .
?
:
>>> minute = 59
>>> float(minute) / 60
0.983333333333

:
>>> minute = 59
>>> minute / 60.0
0.983333333333

float,
, .

2.8.

. , ,
:
30

: 170

>>> print 100 * 20 / 80, "%"


25 %

: 20 80.
%
, , .
,
, .
.
,
. , .
, 2*(3-1) 4, (1+1)**(5-2) 8. ,
,
: (100*20)/80.
, 2**1+1 3,
4, 3*1**3 3, 27.
, ,
. 2*3-1 5, 4; 2/3-1 -1, 1 (
2/3=0).
.
100*20/80 (
2000/80); , 25.
, .
. 100*20/80 ,
.
?

2.9.
, , ,
:
message-1

"Hello"/123

"Hello"*"world!"

"15"+2

+ , :
.
>>> str1 = "Hello"
>>> str2 = " world"
>>> print str1 + str2 + "!"
Hello world!

, . ,
.
* , ,
. *
( ). , 'Fun'*3 'FunFunFun'.

31

: 170


: , 4*3 4+4+4, 'Fun'*3 'Fun'+'Fun'+'Fun'.
,
.
.
(, ..). ,
, ?
,
, .
.

"hello"+" world"*3? ?

2.10.
: .
, .
. ,
, ,
, . ,
,
,
.
(.. )
.
, .
, , .
, :
>>> print 17 + 3
20

:
, .
, .
.
:
>>> percentage = 100 * 20 / 80; print percentage
25

-, . ,
,
, ,
. , :
, .

.

32

: 170

.
( percentage)
. . ,
.
, :
.
, C++
.
,
, .
.
: 100 * 20 / 80 = percentage. ?

33

: 170

3.
3.1.
,
, -
. ,
, , , .

, .
, , ..
,
, .

- ,
, , ,
: -, ,
; -, , ..

,
.
, ..

. ,
,
.

. .
, ,
.
- .
Pascal : . ,
C++, ,
.
,
,
.
B. .

34

: 170

3.2.
,
:
>>> type("Hello world!")
<type 'str'>
>>> int("32")
32

, , type();

. , int()
.
,
, ,
. , str() ,
.. :
>>> str()
''

3.3.
, .
.
, ,
, , , .
, ..
.

__doc__ ( ),
:
>>> print str.__doc__
str(object) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
>>>

str() :
, , , .
2.2, ,
help(). (
, ) .
. str(). ,
2.2 help() .
[Q].
35

: 170

3.4.
, ,

:
, . ,
,
. :
>>> import math
>>>

math.
( B), .
,
. ,
:
>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil',
'cos', 'cosh', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp',
'hypot', 'ldexp',
'log', 'log10', 'modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan',
'tanh']
>>>

,
. __doc__. ,
,
:
>>> print math.__doc__
This module is always available. It provides access to the
mathematical functions defined by the C standard.
>>> print math.pi
3.14159265359
>>> decibel = math.log10(17.0)

; ,
17 10.
(..
e = 2.7182818284590451): math.log(). :
>>> height = math.sin(45)
>>> print height
0.850903524534

, , , , 45
2 2. :
36

: 170

>>> math.sqrt(2) / 2.0


0.707106781187

. ? ?
. ,
, :
>>> help(math.sin)
Help on built-in function sin:
sin(...)
sin(x)
Return the sine of x (measured in radians).
(END)

,
. [Q]
: math.sin();
:
>>> degrees = 45
>>> angle = degrees * math.pi / 180.0
>>> height = math.sin(angle)
>>> print height
0.707106781187

.
. 2.2
:
>>> import math
>>> print math.__doc__
...
>>> help(math)

.
, -.
[Q].
, ,
. ?

3.5.

.
: ,

37

: 170

, ; ,
(, ) :
>>> x = math.sin(math.asin(math.sqrt(2) / 2.0) + math.pi / 2)
>>> print x
0.70710678118654757
>>>

. ,
, ,
=, x.
, .. math.asin(math.sqrt
(2) / 2.0) + math.pi / 2, ,
math.asin(math.sqrt(2) / 2.0) math.pi / 2.
: ,
, math.asin(),
. /2.
,
math.sin(), x.

,
ax +bx+c=0, a<>0 .
a, b c.
a, b c 1, 0 -1 .
1.0 -1.0.
.
, ,
( ),
, : ValueError: math domain
error. , .
2

3.6.
,
.
, ,
. , .
, :
def _(_):
_


, .
,
.
, def ( . define ).
.
, .
38

: 170

, , ,
( [Tab]).
; ,
[Enter] ( ,
, [Backspace],
):
>>> def printAnything(object):
...

print object

...
>>> printAnything("Some string")
Some string
>>> number = 15
>>> printAnything(number)
15

PrintAnything(),
, .
, .
,
.
? PrintAnything(),
:
>>> printAnything(printAnything)
<function printAnything at 0x80d7554>
>>>

: , !
0x80d7554,
. :
def printHello():
print "Hello!"
def runFunction(function_name):
function_name()
runFunction(printHello)

prog2.py
( Windows
6):
$ python prog2.py
Hello!
6 ,
, (. ).

39

: 170

, , , runFunction
() printHello():
function_name
printHello(). .
C++ Pascal .
,
.
.
printRoots().
: a, b c. ,
.
. ,
( (x1, y1) (x2, y2) ).
distance x 1, y 1, x 2, y 2 = x 2 x 1 2 y 2 y 1 2

3.7.
,
. :
? , .
,
.
. , .
:
>>> def printAnything(object):
...

print object

...
>>> printAnything("Some string")
Some string
>>> number = 15
>>> printAnything(number)
15

object , "Some string"


number . ,
, .
.

3.8.
PrintRoots().
:
def printRoots(a, b, c):

40

: 170

D = b**2 - 4 * a * c
import math
x1 = (-b + math.sqrt(D)) / 2 * a
x2 = (-b - math.sqrt(D)) / 2 * a
print 'x1 =', x1, '\nx2 =', x2

\n
print . : D, x1
x2. , ..
. .
:
def printRoots(a, b, c):
D = b**2 - 4 * a * c
import math
x1 = (-b + math.sqrt(D)) / 2 * a
x2 = (-b - math.sqrt(D)) / 2 * a
print 'x1 =', x1, '\nx2 =', x2
printRoots(1.0, 0, -1.0)
print D

,
PrintRoots() :
$ python prog5.py
x1 = 1.0
x2 = -1.0
Traceback (most recent call last):
File "prog5.py", line 12, in ?
print D
NameError: name 'D' is not defined

? ?
:
def printRoots(a, b, c):
D = b**2 - 4 * a * c
import math
print "In function D = ", D
x1 = (-b + math.sqrt(D)) / 2 * a
x2 = (-b - math.sqrt(D)) / 2 * a
print "x1 =", x1, "\nx2 =", x2

41

: 170

D = 'test'
print "Before function call D = ", D
printRoots(1.0, 0, -1.0)
print "After function call D = ", D

.
$ python prog5.py
Before function call D = test
In function D = 4.0
x1 = 1.0
x2 = -1.0
After function call D = test

, printRoots() D
"test" : "test".
printRoots(), D
D: 4.0.
D:
"test".
, D D printRoots()
. , .
id(). .
:
def printRoots(a, b, c):
D = b**2 - 4 * a * c
import math
print "In function D = ", D, "\nAdress:", id(D), "\n"
x1 = (-b + math.sqrt(D)) / 2 * a
x2 = (-b - math.sqrt(D)) / 2 * a
print "x1 =", x1, "\nx2 =", x2
D = "test"
print "Before function call D = ", D, "\nAdress:", id(D), "\n"
printRoots(1.0, 0, -1.0)
print "After function call D = ", D, "\nAdress:", id(D), "\n"

:
$ python prog5.py
Before function call D = test
Adress: 135287104

42

: 170

In function D = 4.0
Adress: 135293780
x1 = 1.0
x2 = -1.0
After function call D = test
Adress: 135287104

,
: D D printRoots() .
.
. ?

3.9.
, ( )
,
, .
,
, . ,
, ..
, .
, , , ,
,
.
,
, ..
, ..
, ,
, ,
, .
, , : f1(), f2() f3().
:
def f1():
print "f1() begins"
print "Hello world!"
print "f1() ends"
def f2():
print "f2() begins"
f1()

43

: 170

print "f2() ends"


def f3():
print "f3() begins"
f2()
print "f3() ends"
print "Main program begins"
f3()
print "Main program ends"

, ,
, .
, , :
$ python prog6.py
Main program begins
f3() begins
f2() begins
f1() begins
Hello world!
f1() ends
f2() ends
f3() ends
Main program ends

. ,
. ,
:
, .
, ,
f3(), , , f2(). , ,
, f1(). f1()
, .
f2() , f1(),
, ,
f2() . ,
f3(), .

3.10.
.
: .
, ,
LIFO ( . Last In First
44

: 170

Out , ). ,
, , .
,
, , ,
.
F1() begins
Hello world!

f1()

f1() ends

f2() begins

f2()

f2() ends

f3() begins

f3()

f3() ends

Main program begins

__main__

Main program ends

,
; ,
. (
__main__); ,
, . ,
.

.
,
, ( ) , ..
.
,
, .
, f1()
,
a = 1/0:
def f1():
print "f1() begins"
a = 1/0
print "f1() ends"
...

:
$ python prog6.py
Main program begins
f3() begins
f2() begins
f1() begins
Traceback (most recent call last):

45

: 170

File "prog6.py", line 17, in ?


f3()
File "prog6.py", line 13, in f3
f2()
File "prog6.py", line 8, in f2
f1()
File "prog6.py", line 3, in f1
a = 1/0
ZeroDivisionError: integer division or modulo by zero

f1()
traceback (
). Traceback ,
, .
, .
.

3.11. ,
.
,
. ,
, , .. .
,
, return.
:
>>> def getSum(x,y):
...

z = x + y

...

return z

...
>>> print getSum(1,3)
4
>>>

, ,
, .
7.
:
>>> def PrintRoots(a, b, c):
...

D = b**2 - 4 * a * c

...

import math

7 , C++
. , .

46

: 170

...

x1 = (-b + math.sqrt(D)) / 2 * a

...

x2 = (-b - math.sqrt(D)) / 2 * a

...

return x1, x2

...
>>> print PrintRoots(1.0, 0, -1.0)
(1.0, -1.0)

,
:
>>> x1, x2 = PrintRoots(1.0, 0, -1.0)
>>> print "x1 =", x1, "\nx2 =", x2
x1 = 1.0
x2 = -1.0
>>>

, ,
.

47

: 170

4.
/* turtle*/

48

: 170

5. ,
5.1.
,
.
,
.
(Martin Fowler),
("Refactoring")

: . ,
, , ,
,

. ,
, ,
, .
,
.
,
(, ,
), , ,
. , -
, .
# ,
,
:
# : 20 80
print 100 * 20 / 80, "%"

, ..
:
>>> print 100 * 20 / 80, "%"

25 %

, .
:
def printTwice(value):
""" printTwice()
,
."""
print value, value

49

: 170

,
.
. ,
. __doc__
( ):
>>> print printTwice.__doc__
printTwice()
,
.

(printTwice).

help


,
.
,
.

5.2.

,
: .
- ,
.

, ..
( )
;
- .
, ,
, .

(True) (False).
. ,
, . 2+2 4 , 2+2 5
.
,
. == (
).
>>> x = 2 + 2
>>> x == 4
True
>>> x == 5
False

50

: 170

:
>>> x != 5

# x 5

True
>>> x > 5

# x 5

False
>>> x < 5

# x 5

True
>>> x >= 4

# x 4

True
>>> x <= 4

# x 4

True

, :
>>> y = x == 5
>>> print y
False

, ,
, , .
, :
>>> type(y)
<type 'bool'>

, ,
2.2.2 . 1,
0; type(4 != 5) <type 'int'>.
. .
:
>>> bool(2)
>>> bool(-1)
>>> bool(1.0)
>>> bool("string")
>>> bool(true)

5.3.

.
: and, or not.
,
. x and y , x ,
51

: 170

y . . x or y
, . not :
not x , x , : not x , x .
, not , .. .

. x , not not x
?

(
):
x

x and y x or y

not x

.
:
x and y y and x
x or y y or x
x and x and x x
x or x or x x
not x and not y not (x or y)

5.4.
,
.
:
if _:
_

if (. ); ;
, , , ,
. :
x = 2
if x > 0:
print "x is positive"
if x < 0:
print "x is negative"

52

: 170

print "Stopping..."

, :
$ python prog7.py
x is positive
Stopping...

x, 2.
x > 0 x
, :
x is positive. if,
x < 0, ,
.
, , . ,
: .
,
, .
printRoots() ,
:
>>> def PrintRoots(a, b, c):
...

D = b**2 - 4 * a * c

...

if D < 0:

...

return None, None

...

import math

...

x1 = (-b + math.sqrt(D)) / 2 * a

...

x2 = (-b - math.sqrt(D)) / 2 * a

...

return x1, x2

>>>
>>> print PrintRoots(3, 2, 1)
(None, None)

, 3x2 + 2x + 1= 0 , ..
, return None,
None. ,
return.
, (0, 0), ..
, :
. None.
.
:

compare(x, y),

53

: 170

1, x y ,
compare x , y= 0, x= y ,
1, x y

5.5.
, , , ..
, ,
.
. ,
. raw_input().
,
.
[Enter]8: , raw_input()
:
>>> text = raw_input()
What are you waiting for?
>>> print text
What are you waiting for?
>>>type(text)
<type 'str'>


, , (-
prompt). raw_input
():
>>> name = raw_input("What is your name? ")
What is your name? Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!

, ,
input().
>>> prompt = "How old are you?"
>>> age = input(prompt)
How old are you? 17
>>> print age
17

int
age. ,
():
8 [Return] Apple.

54

: 170

>>> age = input(prompt)


How old are you?
I'm 17th years old.
SyntaxError: invalid syntax


, (
).
. ,
a, b c.

5.6. (Chained
conditionals)
if ,
,
. :
if __1:
__1
elif __2:
__2
elif __3:
__3
...
else:
__N

. ,
, .
, (.. N). False,
( elif), 2, ,
. . else
, .
elif . else if - . .. ,
, .
, , .
choice = raw_input('Input your choice, please (1 or 2): ')
if choice == "1":
function1()

55

: 170

elif choice == "2":


function2()
else:
print "Invalid choice!"
print "Thank you."

,
'1' ( ,
raw_input() ). ,
function1(), "Thank you."
; choice '2':
, function2(),
"Thank you." ; ,
, .

chained conditionals, .. .
. compare(x, y) ,
.

5.7.

, ,
,
. , , -
. , :
choice = raw_input('Enter your choice, please:')
if choice == "1":
function1_1()
finction1_2()
elif choice == "2":
elif choice == "3":
elif choice == "4":
else:
print "Invalid choice!"

, choice "2", "3" "4",


, - Expected an indented
block.
pass,
:
choice = raw_input('Enter your choice, please:')
if choice == "1":

56

: 170

function1_1()
finction1_2()
elif choice == "2":
pass
elif choice == "3":
pass
elif choice == "4":
pass
else:
print "Invalid choice!"

:
def f1():
pass

, ,
.

5.8. (Nested conditionals)


, ,
, . :
if x == y:
print x, "and", y, "are equal"
else:
if x < y:
print x, "is less than", y
else:
print x, "is greater than", y

,
. ,
.. .
. :
if x < 1:
pass
else:
if x < 10:
print "x is between 1 and 10"

57

: 170

: x < 1, , .. ,
pass, , ;
x < 10,
, "x is between 1 and 10".
, :
if not x < 1 and x < 10:
print "x is between 1 and 10"

?
, if.
not x < 1 , x , x
x >= 1:
if x >= 1 and x < 10:
print "x is between 1 and 10"

,
? .
x : 1 x10 .
, :
>>> x = 3
>>> if 1 <= x < 10:
...

print "x is between 1 and 10"

...
x is between 1 and 10
>>>

. , ,
C++, .
, .
. :
if x < -5:
print "x is NOT between -5 and 5"
else:
if x < 5:
print "x is between -5 and 5"
else:
print "x is NOT between -5 and 5"

. 10 < x < 0 .

58

: 170

5.9.
,
, . ,
, , , .
.
, : , 3!=1 2 3 =6 9. n !=1 ...n ,
n{0 } 10, 0 !=1 .
,

5!=120 ,

7 !=5040 ,

10 !=3628800 . .

, . , n
n !=1 ...n . -
:
n !=12...n ,
n1!=12...nn1=n !n1 , :

n !=n1!n
-. , n1! , n!
. , n1!=n2!n1 .
. ,
. ?
, , :
>>> def fact(n):
...

return fact(n-1)*n

...
>>> fact(3)
File "<stdin>", line 2, in fact
[...]
File "<stdin>", line 2, in fact
RuntimeError: maximum recursion depth exceeded

, , , ,
: RuntimeError:
maximum recursion depth exceeded .
. ,
.
,
().
9 .
10 n , , ,
0, 1, 2, 3 ..

59

: 170

, ,
.
3, . ,
: , .
.
, funct(3) funct(2)*3, funct(2)
funct(1)*2; funct(0), funct(-1). n
! , ,
n, funct()
, . ,
0! , .
>>> def fact(n):
...

if n == 0:

...
...

return 1
return fact(n-1)*n

...
>>> fact(3)
6

! ,
( , ),
.
. , fact()
. , .
, 11.

5.10.
,
. fact(3).

11 , (, n >
1000). , .
.

60

: 170

fact(0)
fact(1-1)*1

return 1

fact(1)
fact(2-1)*2

return 1 *1

fact(2)
fact(3-1)*3

return 1*1 *2

fact(3)
return 1*1*2 *3

__main__
, . 1 x == 0
, .
, : ,
,
,
(, recursio ).
,
, .
.
? , , ,
1 1 . ,
,
- .
: , x == 1.
: fact(0)?
. :
def fact(n):
if type(n) != type(1) or n < 0:

# n

return None
if n == 1 or n == 0:
return 1
return fact(n-1)*n

,
, .
, ,
:
. ,

.
. , fact()
? .

61

: 170

5.11.
,
( base case
). , ,
.
, ,
maximum recursion depth (
).
, ..
. sys
: sys.getrecursionlimit(),
sys.setrecursionlimit(), .
>>> import sys
>>> sys.getrecursionlimit()
1000
>>> sys.setrecursionlimit(5)
>>> sys.getrecursionlimit()
5
>>>

, 1000.
. , , .
.

5.12.
( )
(1170-1240), (1202),
.
, ,
.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55
.
,
,
0.618 ( ),
1.618. - ,
, .
[NOTE: ,
.]
, n- . ,
: f 1 = f 2 =1, f n= f n1 f n2 , n .
?
62

: 170


, ,
, , .
.
>>> def fibonacci(n):
...
...
...

if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)

...
>>> fibonacci(5)
13

.
.
def fibonacci(n):
if type(n) != type(1) or n < 0:

# n

return None
if n == 1 or n == 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
n

. ,

i 3 =13 ...n3 .
i=1

63

: 170

6.
6.1. while

. ,
, , . , , - , ,
,
, . -,
,
.
, . ,

.
, .
: .
,
.
:
while __:
_

:
while (. ). ? , :

, :
correct_choice = False
while not correct_choice:

choice = raw_input("Enter your choice, please (1 or 2):")


if choice == "1" or choice == "2":
correct_choice = True
else:
print "Invalid choice! Try again, please."
print "Thank you."

correct_choice,


False.

not correct_choice: False .
: "Enter your choice, please (1 or 2):"
. [Enter]
"1" "2", , correct_choice
True. "Invalid
choice! Try again, please.".
- , ,
, "Thank you.". ,
.
64

: 170

. :
. ?

6.2.

.
n

i3 =13 ...n3

n.

i=1

i, i
1 n.
while :
n = input("Input n, please:")
sum = 0
i = 1
while i <= n:
sum = sum + i**3

# : sum +=

i**3
i = i + 1

#: i += 1

print "sum = ", sum

, . n
i. sum (
, 0) i ( , 1).
, , i <= n. sum
, ,
i, ; i .
sum .

( 1).
, . ,
(.. ).
.
.
. ,
- ,
, .. , ,
. ?
i ? .
n = input("Input n, please:")
sum = i = 0
while i <= n:

65

: 170

i += 1
sum += i**3
print "sum = ", sum

, sum = i = 0.
,
.
, i 0,
. ,
. ?
, , , , :
i = n. , i
.
. , while
0 n.

6.3.
,
( ), ,
, , - .
, , - .
:
i = 0
while i < 10:
print i

, .. i < 10 ,
i :
. ,
,
,
[Ctrl+C],
, (,
),
. , .
- ,
,
.
A.
,
. ,

.
, !

66

: 170

,
.

6.4. while
,
:
while __:
_
else:
__

, while ,
, ,
else ,
if, .
>>> i = 0
>>> while i < 3:
print i
i += 1
else:
print "end of loop"
0
1
2
end of loop
>>>

,
, .
. , ,
.

6.5.
while
.
. , ,
,
, , ,
12.

12 , , , , .. .

67

: 170


. , ,
(..
). .
:
import math
x = 1.0
while x < 10.0:
print x, "\t", math.log(x)
x += 1.0

:
1.0

0.0

2.0

0.69314718056

3.0

1.09861228867

4.0

1.38629436112

5.0

1.60943791243

6.0

1.79175946923

7.0

1.94591014906

8.0

2.07944154168

9.0

2.19722457734

"\t" .
.
, . x 1.0 1.0,
10.0. x,
math.log(x), .. x (
log e x=ln x ). 2
:
log 2 x=

ln x
ln 2

:
import math
x = 1.0
while x < 10.0:
print x, "\t", math.log(x)/math.log(2)
x += 1.0

:
1.0

0.0

2.0

1.0

68

: 170

3.0

1.58496250072

4.0

2.0

5.0

2.32192809489

6.0

2.58496250072

7.0

2.80735492206

8.0

3.0

9.0

3.16992500144

, 1, 2, 4 8 2. ,
2:
import math
x = 1.0
while x < 100.0:
print x, "\t", math.log(x)/math.log(2)
x *= 2.0

, :
1.0

0.0

2.0

1.0

4.0

2.0

8.0

3.0

16.0

4.0

32.0

5.0

64.0

6.0


.
,
( , ) ,
.. ,
.
. , 2 10-
. . 1000
, 1024?

6.6.
,
,
: "\t". , ( ,
, )
.
/. : ,

69

: 170

. .. ,
, :

\t

\n

\r

() 13

, ,
:
>>> print "hello\rH\n\tworld"
Hello
world

, "hello\rH\n\tworld".
"hello"
: "\r" .
"H", !
14. "\n" "\t"
.
"world".
, ,
: ,
"\rH". .

13 , ,

, . .
,
, .
14 , , , :
,
.

70

: 170

. ,
:
I can use
tabs and
new lines
in program output.

: , ,
, "Main \template/".
>>> print "Main \template/"
Main

emplate/

"\t" ,
, .
"\"
: "\".
>>> print "Main \\template/"
Main \template/

. ?
>>> print "I said: "Hello world""
File "<stdin>", line 1
print "I said: "Hello world""
^
SyntaxError: invalid syntax

, ,
.
:
>>> print "I said: \"Hello world\""
I said: "Hello world"

:
>>> print 'I said: "Hello world"'
I said: "Hello world"

,
. , ,
.
, . ,
, ,
, . , .
? , , ,
. :
71

: 170

print " n " \


+ " ,\n ."

"\" ( :
), .
,
.

6.7. while
,
, . .


, ,
, .
,
, ,
. ( , , ).

. , : f 1 = f 2 =1, f n= f n1 f n2 , n .
. : fn
, fn1 fn2 .
, ?
.
1.
while.
fn = fn1 + fn2, fn1 fn2,
: fn2
fn1, fn1 fn. ,
- i. , :
def fibonacciWithWhileLoop(n):
"""
while."""
fn = fn1 = fn2 = 1
i = 3
while i <= n:
fn = fn1 + fn2
fn2 = fn1
fn1 = fn
i += 1
return fn

72

: 170

. .
? ?
, fibonacciWithWhileLoop()
2.4? ,
.
? ,
.
, . . , ,
.
, .

6.8.
, , , ,
. -.

, :
i = 1
while i <= 10:
j = 1
while j <= 10:
print i * j, "\t",
j += 1
print
i += 1

, . , i <= 10,
. ,
i j ,
. , ,
. print
, . .
:
1

10

10

12

14

16

18

20

12

15

18

21

24

27

30

12

16

20

24

28

32

36

40

10

15

20

25

30

35

40

45

50

12

18

24

30

36

42

48

54

60

14

21

28

35

42

49

56

63

70

16

24

32

40

48

56

64

72

80

18

27

36

45

54

63

72

81

90

10

20

30

40

50

60

70

80

90

100

73

: 170

1 10. i-
j- i j. .
,
. , , .
,
. , , .

6.9.
.
while.
. ,
.
. ,
, . ..
. , Pascal
:
do

{ Pascal}
_

until _;

, ..
.
.
-. , Pascal'
:
for i:=0 to15 9 do

{ Pascal}

_;

C
(, ),
,
(, ):
for (i = 9; i <= 9; i += 1) {

//

_;
}

, ,
: .
, . :
for i in range(0,10):
_


.
15 downto.

74

: 170

6.10.
. ,
.
. ,
:
(
input raw_input);
( ;
print);
,
( , ,
);
(
if);

( while for).
, ,
, :

;
:

, ,
;
,
;
,

;
, ,
, .
, : ,
,
( ).
,
.

75

: 170

7.
,
,
, .
(str).

7.1.
,
.
( ) ,
,
.
, ,
. , ,
,
.
,
, ,
.
.
. :
[]

, ,
:
>>> 'Hello!'[1]
'e'

, , - ,
. . ,
, , . :
>>> 'Hello!'[0]
'H'

! .

7.2.

. , . :
>>> len('Hello world!')
12
>>>

, .
:
76

: 170

>>> a = 'Hello!'
>>> a[len(a)]
Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevela[len(a)]
IndexError: string index out of range
>>>

.. ,
,
IndexError: string index out of range. :
>>> a = 'Hello!'
>>> a[len(a)-1]
'!'

len() ,
:
>>> a[-1]
'!'

.
:
>>> a[-5]
'e'

, .
, .
.
. ,
, , . ,
.

7.3. for
, .

. .
string = "hello"
index = 0
while index < len(string):
letter = string[index]
print letter
index = index + 1

77

: 170


. , index < len(string),
len(string) - 1,
.
. ,
, , .
, , , ,
. (
): for. :
for letter in string:
print letter

, string
letter, .
,
.

7.4.

, :
, (-, slices). :
>>> s = "Peter, Paul, and Mary"
>>> print s[0:5]
Peter
>>> print s[7:11]
Paul
>>> print s[17:21]
Mary

: string[n:m], n , m
. .
, m .
.

:
>>> print s[:5]
Peter
>>> print s[17:]
Mary

, .. ,
,
.

78

: 170

. s[:]?
, ,
2.3.
:
>>> print s[::2]
Ptr al n ay

? (
, )!
. 10-15 ,
:
1. ;
2. ;
3.
.
2-3 .

7.5.
.
, :
if word == "banana":
print

"Yes, we have no bananas!"

:
if word < "banana":
print "Your word," + word + ", comes before banana."
elif word > "banana":
print "Your word," + word + ", comes after banana."
else:
print "Yes, we have no bananas!"

,
. ,
. :
Your word, Zebra, comes before banana.

,
, . , .

7.6.

([]) . :
greeting = "Hello, world!"

79

: 170

greeting[0] = 'J'

# ERROR!

print greeting

Jello, world!, :
TypeError: object doesn't support item assignment.
,
. , ,
:
greeting = "Hello, world!"
newGreeting = 'J' + greeting[1:]
print newGreeting

,
greeting. .

. , 5- ( , .. ) Hello, world! .

7.7. find
:
def find(str, ch):
index = 0
while index < len(str):
if str[index] == ch:
return index
index = index + 1
return -1

? find()
[]. , ,
, .
, -1.
return .
str[index] == ch, ,
.
,
-1.
. find() ,
, .

(,
).

80

: 170

7.8.
, :
fruit = "banana"
count = 0
for char in fruit:
if char == 'a':
count = count + 1
print count

.
count 0 16
a . , count
a. ,
, , .
. countLetters
, .
. ,
find ,
.

7.9. string
string ,
. , :
>>> import string

string find(), ,
, . :
,
, - .
.
, , ,
:
>>> fruit = "banana"
>>> index = string.find(fruit, "a")
>>> print index
1

( ,
)
16 - ;
.

81

: 170

, .
, find() .
, ,
string.find() , . -,
, :
>>> string.find("banana", "na")
2

,
:
>>> string.find("banana", "na", 3)
4

,
:
>>> string.find("bob", "b", 1, 2)
-1

, , b
1 2 ( 2).
. string
:
1. capitalize()
2. capwords()
3. count()
4. find()
5. lower()
6. replace()
7. split()
8. upper()
.

7.10.

. string ,
.
string.lowercase .
string.uppercase .
, :
>>> print string.lowercase
>>> print string.uppercase
>>> print string.digits

find()
. , find(lowercase, ch) , -1,
ch .
82

: 170

def isLower(ch):
return string.find(string.lowercase, ch) != -1

in, ,
:
def isLower(ch):
return ch in string.lowercase

:
def isLower(ch):
return 'a' <= ch <= 'z'

ch a z, .
. isLower() ? ,
, ?
string
() , , ("\t")
("\r") ("\n") :
>>> print string.whitespace

6.6, : .

7.11. unicode

83

: 170

8.
8.1.
8.2.
8.3.
8.4.
8.5. for
8.6.
8.7.
8.8.
8.9.
8.10.
8.11.
8.12.
8.13. -
8.14.
8.15.
8.16.

84

: 170

9.

85

: 170

10.
, .

, .
,
(, str, float, tuple).

10.1.
- ,
.
.
{}:
>>> eng2sp = {}
>>> eng2sp['one'] = 'uno'
>>> eng2sp['two'] = 'dos'

eng2sp;
.
:
>>> print eng2sp
{'one': 'uno', 'two': 'dos'}

;
, . ,
-.
-,
.
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

eng2sp, :
>>> print eng2sp
{'one': 'uno', 'three': 'tres', 'two': 'dos'}

- !
,
. :
>>> print eng2sp['two']
'dos'

'two' 'dos' -.

10.2.
del -. ,
:

86

: 170

>>> inventory = {'apples': 430, 'bananas': 312, 'oranges': 525,


'pears': 217}
>>> print inventory
{'oranges': 525, 'apples': 430, 'pears': 217, 'bananas': 312}

- , :
>>> del inventory['pears']
>>> print inventory
{'oranges': 525, 'apples': 430, 'bananas': 312}

,
:
>>> inventory['pears'] = 0
>>> print inventory
{'oranges': 525, 'apples': 430, 'pears': 0, 'bananas': 312}

len , -:
>>> len(inventory)
4

10.3.
[NOTE: ( )
]
, ,
. ,
- ,
.
, key ,
keys(eng2sp), eng2sp.keys
().
>>> eng2sp.keys()
['one', 'three', 'two']

, keys, ,
, eng2sp. ,
.
invocation; , ,
keys() eng2sp.
values() :
>>> eng2sp.values()
['uno', 'tres', 'dos']

items -:
>>> eng2sp.items()

87

: 170

[('one','uno'), ('three', 'tres'), ('two', 'dos')]

,
. , has_key() (1)
.
>>> eng2sp.has_key('one')
1
>>> eng2sp.has_key('deux')
0

, .
, :
>>> has_key('one')
NameError: has_key

10.4.
, . ,
,
.
[TODO: ]
,
copy(). , opposites , :
>>> opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'}
>>> alias = opposites
>>> copy = opposites.copy()

alias opposites ;
copy() .
, opposites .
>>> alias['right'] = 'left'
>>> opposites['right']
'left'

copy, , opposites .
>>> copy['right'] = 'privilege'
>>> opposites['right']
'left'

10.5.
8.14 .
,
:

88

: 170

0
0
0
0
0

0
0
2
0
0

0
0
0
0
0

1
0
0
0
3

0
0
0
0
0

:
>>> matrix1 = [ [0,0,0,1,0],
[0,0,0,0,0],
[0,2,0,0,0],
[0,0,0,0,0],
[0,0,0,3,0] ]

:
, .
:
>>> matrix2 = {(0,3): 1, (2, 1): 2, (4, 3): 3}

-,
. .
:
>>> matrix1[0][3]
1
>>> matrix2[0,3]
1


.
.
. ,
, :
>>> matrix2[1,3]
KeyError: (1, 3)

get():
>>> matrix.get((0,3), 0)
1

, , get()
, :
>>> matrix.get((1,3), 0)
0

get definitely improves the semantics of accessing a sparse matrix. Shame about the syntax.
get .
89

: 170

10.6.
5.12,
, , , ,
. , .
, fibonacci(20) , fibonacci(30)
fibonacci(40) .
,
fibonacci() n = 4:
[TODO:
http://www.ibiblio.org/obp/thinkCSpy/illustrations/fibonacci.png]
,
, ,
. , fibonacci() n = 4 fibonacci()
n = 3 n = 2. , fibonacci() n = 3 fibonacci() n = 2
n = 1. .
, , , , ..
, .
fibonacci(0) fibonacci(1).
, ( , ,
).
, ,
. ,
, . fibonacci(),
:
previous = {0:1, 1:1}
def fibonacci(n):
if previous.has_key(n):
return previous[n]
else:
newValue = fibonacci(n-1) + fibonacci(n-2)
previous[n] = newValue
return newValue

previous , .
: 0 1 1 1.
, fibonacci(), ,
. ,
, . ,
. ,
.
, fibonacci()
n = 40 . fibonacci(50),
:
90

: 170

>>> fibonacci(50)
OverflowError: integer addition

, 20365011074. ,
int. .
.

10.7.
long int,
. long int.
L .
>>> type(1L)
<type 'long int'>

long()
long int. long() :
>>> long(1)
1L
>>> long(3.9)
3L
>>> long('57')
57L

long int, ,
fibonacci():
>>> previous = {0:1L, 1:1L}
>>> fibonacci(50)
20365011074L

,
. long int,
.
. factorial() ,
long int. .

10.8.
7 countLetters,
.
, ,
.
(, )17,
. ,
17 , ,
.

91

: 170

, ,
( , ).
:
>>> letterCounts = {}
>>> for letter in "Mississippi":
...

letterCounts[letter] = letterCounts.get (letter, 0) + 1

...
>>> letterCounts
{'M': 1, 's': 4, 'p': 2, 'i': 4}

.
( ) . :
.

items() sort():
>>> letterItems = letterCounts.items()
>>> letterItems.sort()
>>> print letterItems
[('M', 1), ('i', 4), ('p', 2), ('s', 4)]

[NOTE: :]
items() , sort()
. , append(), extend()
reverse(). ( help())
.

92

: 170

11.

93

: 170

12.

94

: 170

13.

95

: 170

14.

96

: 170

15.

97

: 170

16.

98

: 170

17.

99

: 170

18.

100

: 170

19.

101

: 170

20.

102

: 170

21.

103

: 170

.
, ,
. ,

. ,
.

104

: 170

A.

105

: 170

B.

106

: 170

C.

107

: 170

D.

108

: 170

E.

109

: 170

F.

110

Вам также может понравиться