Błyskawiczny kurs języka Python od podstaw do prostej strony opartej o microframework Flask. Marius Rejdak mariuswol@gmail.com #inf.aei.polsl.pl @ QuakeNet
2 / 44 Agenda 1. Filozofia języka 2. REPL 3. Podstawy języka 4. Klasy i obiekty 5. Wyjątki 6. Elementy funkcyjne 7. Debugowanie 8. Microframework Flask
3 / 44 PEP 20 The Zen of Python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
http://xkcd.com/353/ 4 / 44
5 / 44 Learn the power of the Dark Side REPL
6 / 44 Pierwszy program $./hello_world.py Hello world! $ python2 hello_world.py Hello world!
7 / 44 Operatory lambda args: expr X if Y else Z X or Y X and Y not X X in Y, X not in Y X is Y, X is not Y X < Y, X <= Y X > Y, X >= Y X Y X ^ Y X & Y X << Y, X >> Y X + Y, X Y X * Y, X % Y, X / Y, X // Y -X, +X ~X X ** Y X[i] X[i:j:k] X( ) X.attr ( ) [ ] { }
8 / 44 Dokumentowanie >>> import os >>> os. doc "OS routines for Mac, NT, or Posix depending on what system we're on.\n" >>> def test():... """Does nothing :)... """... pass >>> test. doc 'Does nothing :)\n'
9 / 44 Deklarowanie zmiennych, Python jako język dynamicznie i silnie typowany foo = 1 a,b,c = ('a','b','c')
10 / 44 Łańcuchy znaków (1) >>> text = "A complex line of meaningless text" >>> text 'A complex line of meaningless text' >>> text2 = """Text line with > " <""" >>> text2 'Text line with > " <'
11 / 44 Łańcuchy znaków (2) Kodowanie i unicode >>> text = "Krótki tekst" >>> text 'Kr\xc3\xb3tki tekst' >>> print text Krótki tekst >>> text = u"krótki tekst" >>> text u'kr\xf3tki tekst' >>> print text Krótki tekst >>> text.encode("utf-8") 'Kr\xc3\xb3tki tekst' >>> text.decode("utf-8") u'kr\xf3tki tekst'
12 / 44 Listy (1) >>> li = ["a", "b", "c", 1, 2, -3] >>> li ['a', 'b', 'c', 1, 2, -3] >>> li[0] 'a' >>> li[4] 2 >>> len(li) 6
13 / 44 Listy (2) Ujemne indeksy >>> li = ["a", "b", "c", 1, 2, -3] >>> li ['a', 'b', 'c', 1, 2, -3] >>> li[-1] -3 >>> li[-2] 2
14 / 44 Listy (3) Dodawanie elementów >>> li ['a', 'b', 'c', 1, 2, -3] >>> li.append("new") >>> li ['a', 'b', 'c', 1, 2, -3, 'new'] >>> li.insert(2, "new2") >>> li ['a', 'b', 'new2', 'c', 1, 2, -3, "new"] >>> li.extend(["x", "y"]) >>> li ['a', 'b', 'new2', 'c', 1, 2, -3, 'new', 'x', 'y']
15 / 44 Listy (4) Usuwanie elementów >>> li ['a', 'b', 'c', 1, 2, -3] >>> li.remove("c") >>> li ['a', 'b', 1, 2, -3] >>> li.remove(-3) >>> li ['a', 'b', 1, 2] >>> li.pop() 2
16 / 44 Listy (5) Przeszukiwanie >>> li ['a', 'b', 'c', 1, 2, -3] >>> li.index("c") 2 >>> "x" in li False >>> "c" in li True
17 / 44 Listy (6) Operatory >>> li = ["a", "b", "c"] >>> li = li + ["x", "y"] >>> li ['a', 'b', 'c', 'x', 'y'] >>> li = [1, 2] * 3 >>> li [1, 2, 1, 2, 1, 2]
18 / 44 Listy (7) Wycinanie >>> li ['a', 'b', 'c', 1, 2, -3] >>> li[1:3] ['b', 'c'] >>> li[1:-1] ['b', 'c', 1, 2] >>> li[:3] ['a', 'b', 'c'] >>> li[3:] [1, 2, -3] >>> li[:] ['a', 'b', 'c', 1, 2, -3]
19 / 44 Listy (8) Append a extend >>> li = ['a', 'b', 'c'] >>> li.extend(['d', 'e', 'f']) >>> li ['a', 'b', 'c', 'd', 'e', 'f'] >>> len(li) 6 >>> li[-1] 'f' >>> li = ['a', 'b', 'c'] >>> li.append(['d', 'e', 'f']) >>> li ['a', 'b', 'c', ['d', 'e', 'f']] >>> len(li) 4 >>> li[-1] ['d', 'e', 'f']
20 / 44 Krotka (ang. tuple) >>> k = ("a", "b", "c") >>> k ('a', 'b', 'c') >>> k[0] 'a' >>> k[-1] 'c' >>> 'c' in k True >>> tuple([1, 2, 3]) (1, 2, 3) >>> list((1, 2, 3)) [1, 2, 3]
21 / 44 Słowniki (1) >>> d = {} >>> d["klucz"] = "wartosc" >>> d["klucz"] = "inna wartosc" >>> d {'klucz': 'inna wartosc'} >>> d["klucz"] = "jeszcze inna wartosc" >>> d {'klucz': 'inna wartosc', 'Klucz': 'jeszcze inna wartosc'} >>> del d['klucz'] >>> d.clear() >>> d {}
22 / 44 Słowniki (2) >>> d = {"k1": "w1", "k2": "w2"} >>> d.items() [('k2', 'w2'), ('k1', 'w1')] >>> d.keys() ['k2', 'k1'] >>> d.values() ['w2', 'w1']
if, elif, else 23 / 44
24 / 44 Pętla for >>> for i in ("a", "b", "c"):... print i a b c >> for i in range(4):... print i 0 1 2 3 >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Pętla while 25 / 44
26 / 44 Formatowanie łańcucha znaków >>> a = "qwe" >>> b = "rty" >>> "%s zzz %s" % (a, b) 'qwe zzz rty' >>> "Liczba: %d" % (1,) 'Liczba: 1' >>> "Liczba zmiennoprzecinkowa: %.2f" % 12.3456 'Liczba zmiennoprzecinkowa: 12.34' >>> ";".join(["x", "y", "z"]) 'x;y;z' >>> "x;y;z".split(";") ['x', 'y', 'z']
27 / 44 Wyrażenia listowe (ang. list comprehesion) >>> li = [1, 9, 8, 4] >>> [element*2 for element in li] [2, 18, 16, 8] >>> li [1, 9, 8, 4] >>> li = [elem*2 for elem in li] >>> li [2, 18, 16, 8] >>> d = {"k1": "w1", "k2": "w2"} >>> ["%s=%s" % (k, v) for k, v in d.items()] ['k2=w2', 'w1=w1']
28 / 44 Filtrowanie list >>> list = [1, 9, 8, 4] >>> [element for element in list if element < 7] [1, 4] >>> [element**3 for element in list if element < 7] [1, 64]
29 / 44 Argumenty nazwane i opcjonalne >>> def funkcja(arga, argb=1, argc=2):... return arga + argb + argc... >>> funkcja(0) 3 >>> funkcja(0, 2) 4 >>> funkcja(0, 2, 5) 7 >>> funkcja(0, argc=1) 2 >>> funkcja(arga=0, argb=0, argc=0) 0
30 / 44 Importowanie modułów >>> import os >>> os <module 'os' from '/usr/lib/python2.7/os.pyc'> >>> os.open <built-in function open> >>> from os import fork >>> fork <built-in function fork> >>> import os as os2 >>> from os import fork as fork2 >>> fork2 <built-in function fork>
31 / 44 Funkcja str >>> str(1) '1' >>> li = ["a", "b", "c"] >>> str(li) "['a', 'b', 'c']" >>> import os >>> str(os) "<module 'os' from '/usr/lib/python2.7/os.pyc'>"
32 / 44 Funkcja dir >>> import re >>> dir(re) ['DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', ' all ', ' builtins ', ' doc ', ' file ', ' name ', ' package ', ' version ', '_alphanum', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_pattern_type', '_pickle', '_subx', 'compile', 'copy_reg', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'sys', 'template'] >>> dir(0) [' abs ', ' add ', ' and ', ' class ', ' cmp ', ' coerce ', ' delattr ', ' div ', ' divmod ', ' doc ', ' float ', ' floordiv ', ' format ', ' getattribute ', ' getnewargs ', ' hash ', ' hex ', ' index ', ' init ', ' int ', ' invert ', ' long ', ' lshift ', ' mod ', ' mul ', ' neg ', ' new ', ' nonzero ', ' oct ', ' or ', ' pos ', ' pow ', ' radd ', ' rand ', ' rdiv ', ' rdivmod ', ' reduce ', ' reduce_ex ', ' repr ', ' rfloordiv ', ' rlshift ', ' rmod ', ' rmul ', ' ror ', ' rpow ', ' rrshift ', ' rshift ', ' rsub ', ' rtruediv ', ' rxor ', ' setattr ', ' sizeof ', ' str ', ' sub ', ' subclasshook ', ' truediv ', ' trunc ', ' xor ', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real'] >>> dir("") [' add ', ' class ', ' contains ', ' delattr ', ' doc ', ' eq ', ' format ', ' ge ', ' getattribute ', ' getitem ', ' getnewargs ', ' getslice ', ' gt ', ' hash ', ' init ', ' le ', ' len ', ' lt ', ' mod ', ' mul ', ' ne ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' rmod ', ' rmul ', ' setattr ', ' sizeof ', ' str ', ' subclasshook ', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
33 / 44 Funkcja type >>> type(0) <type 'int'> >>> type("a") <type 'str'> >>> import os >>> type(os) <type 'module'>
34 / 44 Metody specjalne init (self [, argumenty]) repr (self) str (self) cmp (self, arg) len (self) call (self [, argumenty]) setitem (self, key, item) getitem (self, key) add (self, arg)...i wiele innych
35 / 44 Wyrażenia lambda >>> l = lambda x: x*2 >>> l(3) 6 >>> (lambda x: x*3)(3) 9 >>> (lambda x,y: x*y)(6,8) 48
36 / 44 Definiowanie i inicjalizacja klas >>> n = NazwaKlasy("a", "b") >>> n.metoda() a b
Wyjątki 37 / 44
38 / 44 Praca na plikach >>> plik = open("plik.txt", "w") >>> plik.write("test") >>> plik.close() >>> print open("plik.txt").read() test >>> plik = open("plik.txt", "a") >>> plik.write(" test2") >>> plik.close() >>> print
39 / 44 The Python Debugger $ python -m pdb myscript.py Breakpoint w kodzie: import pdb; pdb.set_trace() $ python -m ipdb myscript.py import ipdb; ipdb.set_trace()
40 / 44 Flask is Fun (1) Instalacja $ pip install Flask
Flask is Fun (2) 41 / 44
Flask is Fun (3) 42 / 44
43 / 44 Ciekawe biblioteki Frameworki webowe Django Pylons / Pyramids CherryPy Zope SQLAlchemy Pickle BeautifulSoup PyGTK, PyQt Py2exe
44 / 44 Polecane materiały Książka Dive into Python http://www.diveintopython.net/ http://pl.wikibooks.org/wiki/zanurkuj_w_pythonie The Python Tutorial http://docs.python.org/tutorial/