Р.А. Сузи - Язык программирования Python

  • Published on
    04-Jan-2016

  • View
    321

  • Download
    15

Embed Size (px)

Transcript

  • Python

    (PDF hunger.ru nerezus)

    Python, .

    - Python. Python , , . Python . . , . Python : - , , - (GUI-), (Unicode, XML ..). Python . Python , . .

  • 2

    1. Python

    Python , , . , Python .

    2. Python

    Python , .

    3.

    , ( Pascal, C++ Java). , , , . Python , , .

    , . . Python , , . , , .

    , . , , .

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

    4. -

    5. .

    Numeric , .

    6. . . Unicode

    Python . , Unicode.

  • 3

    7.

    - Python. Python , . .

    8. Web-

    Python - web- - . , web-.

    9. Python

    Python - , Internet . Python . (TCP/IP, UDP/IP), (HTTP, FTP, SMTP, POP3, IMAP, NNTP, ...). ( socket) (urllib2, poplib, smtplib). , IP- , WWW.

    10.

    DB-API 2.0 , SQL.

    11.

    () . (, , ). .

    12.

    . (" "), (Tk).

    13. Python

    (embedding) Python C, , , Python C (extending). C- Python (SWIG). Python : C++, Java, OCaml, Prolog. Python - Pyrex.

    14. Python

    Python. , "".

  • 4

    #1: Python

    Python?

    Python ( "", "") - , , :

    "Python - , - . (RAD, Rapid Application Development). , . Python , , . Python , . Python ."

    , , Python - . , . Python . Python : , , , , , .. , Python C, C++ ( Java) (embedding) , , , , Python-. Python : (, , ), - .

    , Python - ( ). ( 32-, 64-) C Java.

    , , - C/C++, Java, Visual Basic, C#. . , Python , .

    ?

    Python: . , , , .

    . - , , . , ( ""), . . ,

  • 5

    , . , .

    - : ( ). . "" . . . Python , "" . Python .

    Python

    Python (Guido van Rossum) 1991 , . , . ABC -3. Python BBC " -", . Python , . , , . - .

    Python

    Python . , 7- ASCII. , , . , , KOI8-R, :

    # -*- coding: koi8-r -*-

    Python , Unicode- Unicode. Python , .

    , , . , , Python. >>>. (#) .

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

    print a, " - , ", \ 80, "" :

    "" Python "Python Style Guide", http://python.org

  • 6

    , , Python. , Python ( , Python), Python , -.

    . , , , , , , :

    a = 1 b = 2 a = a + b b = a - b a = a - b print a, b

    ? Python.

    Python , . print.

    , , :

    if a > b: c = a else: c = b

    Python , , if - "", else - "". , . - - ( ):

    if a < 0: s = -1 elif a == 0: s = 0 else: s = 1

    , elif - else if. :

    if a < 0: s = -1 else: if a == 0:

  • 7

    s = 0 else: s = 1

    print, if-else - .

    . . Python : ( ) ( ). Python:

    s = "abcdefghijklmnop" while s != "": print s s = s[1:-1]

    while Python: " , ". Python . . , .

    break () continue (). , - , (, , ).

    , 5:

    f = open("file.txt", "r") while 1: l = f.readline() if not l: break if len(l) > 5: print l, f.close()

    , (l), .

    Python : , , None False "", "". 1 True.

    :

    True False Python 2.3.

    . :

    for i in range(1, 10): for j in range(1, 10): print "%2i" % (i*j), print

  • 8

    for . range() [1, 10). . Python. , . , range(len(s)) s ( Python- 0). % ( ). ( ) printf C.

    : def , lambda. ( ) Python, :

    def cena(rub, kop=0): return "%i . %i ." % (rub, kop) print cena(8, 50) print cena(7) print cena(rub=23, kop=70)

    ( - 0). . , , , . . return . , .

    def cena .

    , . ( ) . try-except :

    try: res = int(open('a.txt').read()) / int(open('c.txt').read()) print res except IOError: print " -" except ZeroDivisionError: print " 0" except KeyboardInterrupt: print " " except: print ""

    . , except ( Python). except ,

  • 9

    . , , int() ValueError. - except. , try except.

    , Python . try-except, : ", - except". , :

    try: value = dict[key] except: value = default_value

    if dict.has_key(key): value = dict[key] else: value = default_value :

    Python : Python value = dict.get(key, default_value).

    . raise. :

    class MyError(Exception): pass try: ... raise MyError, "my error 1" ... except MyError, x: print ":", x

    , , ZeroDivisionError ArithmeticError, except .

    assert. AssertionError, . . , . :

    c = a + b assert c == a + b

    , try-finally try-finally . , , :

    try: ...

  • 10

    finally: print " "

    try-except try-finally .

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

    , . , Python , .

    ( ):

    : None, NotImplemented Ellipsis; ;

    o int long bool

    o float o complex

    ; o :

    str; Unicode- unicode; tuple;

    o : list;

    : o dict

    , : o ( ); o -; o ( ); o ( ""); o ( __call__);

    ; (. ); (. ); file; buffer, slice.

    type().

    int long

    : int ( ) long ( ) . long C . 8, 10 16:

  • 11

    # 10 print 10, 012, 0xA, 10L

    - , :

    >>> print 1 + 1, 3 - 2, 2*2, 7/4, 5%3 2 1 4 1 2 >>> print 2L ** 1000 107150860718626732094842504906000181056140481170553360744375038 837035105112493612249319837881569585812759467291755314682518714 528569231404359845775746985748039345677748242309854210746050623 711418779541821530464749835819412673987675591655439460770629145 71196477686542167660429831652624386837205668069376 >>> print 3 < 4 < 6, 3 >= 5, 4 == 4, 4 != 4 # True False True False >>> print 1 > 2, ~4 # 256 1 -5 >>> for i, j in (0, 0), (0, 1), (1, 0), (1, 1): ... print i, j, ":", i & j, i | j, i ^ j # ... 0 0 : 0 0 0 0 1 : 0 1 1 1 0 : 0 1 1 1 1 : 1 1 0

    int -2147483648 2147483647, .

    , , , int long:

    >>> type(-2147483648) >>> type(-2147483649)

    . - , 8:

    >>> 008 File "", line 1 008 ^ SyntaxError: invalid token

    float

    C- double . , :

    >>> pi = 3.1415926535897931 >>> pi ** 40 7.6912142205156999e+19

    , math.

    :

    .

  • 12

    round(), abs().

    complex

    j ( ):

    >>> -1j * -1j (-1-0j)

    . , cmath.

    bool

    "" . : True () False () - , . , Python , :

    >>> for i in (False, True): ... for j in (False, True): ... print i, j, ":", i and j, i or j, not i ... ... False False : False False True False True : False True True True False : False True False True True : True True False

    , Python and or, . , , or, . and .

    string unicode

    Python : Unicode-. - ( " "). - . ('), ("). . (\). :

    s1 = "1" s2 = '2\n ' s3 = """3 """ u1 = u'\u043f\u0440\u0438\u0432\u0435\u0442' # u2 = u' ' # coding!

    : . , " ":

    my_re = r"(\d)=\1"

  • 13

    ( , ).

    "+", "*", "%". , . ( ) Python.

    >>> "A" + "B" 'AB' >>> "A"*10 'AAAAAAAAAA' >>> "%s %i" % ("abc", 12) 'abc 12'

    , .

    tuple

    () . , , , . :

    p = (1.2, 3.4, 0.9) # for s in "one", "two", "three": # print s one_item = (1,) empty = () p1 = 1, 3, 9 # p2 = 3, 8, 5, #

    . . :

    a, b = b, a

    list

    "" Python . . , , . :

    lst1 = [1, 2, 3,] lst2 = [x**2 for x in range(10) if x % 2 == 1] lst3 = list("abcde")

    , , . .

    . , . .

    len(s) s

  • 14

    x in s . Python . True False

    x not in s = not x in s s + s1 s*n n*s

    n s. n < 0, .

    s[i] i- s len(s)+i-, i < 0 s[i:j:d] s i j d min(s) s max(s) s

    :

    s[i] = x i- s x s[i:j:d] = t i j ( d) () t del s[i:j:d]

    (, ).

    append(x) count(x) , x extend(s) s index(x) i, , s[i] == x.

    ValueError, x s insert(i, x) x i- pop([i]) i- , reverse() s sort([cmpfunc]) s.

    cmpfunc

    ( - ) . , , . Python . (-1 - ). :

    >>> s = [0, 1, 2, 3, 4] >>> print s[0], s[-1], s[3] 0 4 3 >>> s[2] = -2 >>> print s [0, 1, -2, 3, 4] >>> del s[2] >>> print s

  • 15

    [0, 1, 3, 4] :

    .

    . , Python , . , , . ( ) 0, - 1 ... . :

    [::]

    - , - , - . =0, =len(), =1, , .

    :

    >>> s = range(10) >>> s [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> s[0:3] [0, 1, 2] >>> s[-1:] [9] >>> s[::3] [0, 3, 6, 9] >>> s[0:0] = [-1, -1, -1] >>> s [-1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> del s[:3] >>> s [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    , , , , .

    dict

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

    d = {1: 'one', 2: 'two', 3: 'three', 4: 'four'} d0 = {0: 'zero'} print d[1] # d[0] = 0 # del d[0] # - print d for key, val in d.items(): # print key, val for key in d.keys(): # print key, d[key] for val in d.values(): # print val

  • 16

    d.update(d0) # print len(d) #

    file

    . - . : read(), write(), readline(), readlines(), seek(), tell(), close() ..

    :

    f1 = open("file1.txt", "r") f2 = open("file2.txt", "w") for line in f1.readlines(): f2.write(line) f2.close() f1.close()

    , Python . , file , ( ). , (URL) file2.txt ,

    import urllib f1 = urllib.urlopen("http://python.onego.ru")

    , , .

    . . Python - . ( .)

    ( ). x . Python - -, (**), .

    lambda - or and not x in, not in is, is not =,!=,== | ^ & +, -

  • 17

    *, /, % , , +x, -x ~x ** x. x[] x[:] ( ) f(,...) ( ... ) [ ... ] {:, ...} - `` (repr)

    , :

    1. , .

    2. a < b < c ... y < z : ( < b) and (b < c) and ... and (y < z).

    3. . ( ), or and , , . . , .

    4. , , , .. -, .

    . , , . , % , *, , :

    print "%i" % (i*j)

    Python . , ( ) "" - None.

    . Python ( , , C) , = , , , () . ( ).

    () , , Python.

    ( ) , . . :

  • 18

    >>> import keyword >>> keyword.kwlist ['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'yield']

    , , . , , . - - .

    "" : , . - .

    , Python , . Python , , , , .

    - , . - , , global. - __builtins__.

    , , , . , , , .

    , , , NameError. , for, import, , , except try-except.

    , . , , :

    1. () .

    2. . -, .

    3. from import * - , .

    , , , , : .

    del. , , . Python (reference counting), - (garbage collection).

  • 19

    - , , . , . , , , .

    :

    , , ; , , ,

    ; ; ; ()

    ;

    .

    Python . "Python Style Guide" http://www.python.org/doc/essays/styleguide.html.

    . .

    4 . 79 . ( ),

    . . Emacs python-mode (IDE) Python-:

    def draw(figure, color="White", border_color="Black", size=5): if color == border_color or \ size == 0: raise "Bad figure" else: _draw(size, size, (color,

    border_color))

    , , , . . , .

    . .

    .

    . ( !)

  • 20

    , . Python , , , .

    , . "#" . "#" . .

    , , . "#" .

    , .

    , , , , , , .

    , .

    (""").

    , : " ", " ".

    , , . , , .

    , , , .

    , , ( ). , .

    , . , , , , , . .

    . RCS CVS. "Python Style Guide" $Revision: 1.31 $ __version__, "#".

    . , . Python , , Python.

    , , shelve, string, , StringIO, UserDict. C "_", - : _tkinter Tkinter.

    , , - , . : class_.

  • 21

    , , Tag HTTPServer.

    "error" ( "warning"). ( os.error) ( ): distutils.DistutilsModuleError.

    , , -. , .

    ( ) , from-import .

    , . (, )

    , : RED, GREEN, BLUE. Python ,

    ( ).

    , Python , . , , Python , Python.

  • 22

    #2: Python

    Python , . , Python " ".

    , , Python .

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

    Python , , . xml, XML.

    Python -, , :

    >>> import datetime >>> d1 = datetime.date(2004, 11, 20)

    datetime. import datetime.

    Python ( Python) , ( , C). . , : Python C. , , pickle cPickle. Python - , .

    Python

    . , . , Python , sys.path:

    >>> sys.path ['', '/usr/local/lib/python23.zip', '/usr/local/lib/python2.3', '/usr/...

Recommended

View more >