Obliczenia Symboliczne I Python - Składnia Typizacja
Sprawy organizacyjne Tryb zaliczenia ćwiczeń Zakres i tematyka wykładu http://home.agh.edu.pl/~korzycki/osi/ <under construction>
Zakres tematyczny wykładu Python... i inne języki Skryptowe (Groovy, Ruby, JavaScript) Przetwarzanie tekstu i symboli Programowanie funkcjonalne Glue Languages Web Frameworks
Python "Python is fast enough for our site and allows us to produce maintainable features in record times, with a minimum of developers," Cuong Do, Software Architect, YouTube.com.
Python Centrum Wiskunde & Informatica Amsterdam Hollandia 1sza implementacja XII 1989 Guido van Rossum Benevolent Dictator For Life
Python Wersja 1.0 I 1994 Wersja 2.0 16 X 2000 Pełen Garbage collector Unicode (!) 2.2 wszystko stało się obiektem, wprowadzono generatory z Icona Wersja 3.0 3 XII 2008 Na wykładzie korzystamy z wersji 2.6
Python Na wykładzie korzystamy z wersji 2.6 3.0? We don't need no stinkin' 3.0! from future import *
Python Python jest językiem: Wysoko poziomowym (programowanie funkcjonalne!) Skryptowym (ale ma bytecode jak Java) Bo można w nim pisać skrypty...... ale i duże aplikacje Ogólnego zastosowania (!) o wysokiej czytelności składni Dynamicznie typowanym... i gdzie używa się wcięć zamiast bloków
Python Python ZEN
#!/usr/bin/python import sys def parrot(param): print param, ' is dead' if name == ' main ': for i in sys.argv: parrot(i))
Python import dołącza plik z PYTHONPATH:.:/usr/local/lib/python. import test Do x w test odwołujemy się przez "test.x". from test import x Do x w test odwołujemy się przez "x". from test import * Wczytuje wszystko z test. Do x w test odwołujemy się przez "x". Nie zalecane import test as thetest Do x w test odwołujemy się przez "thetest.x".
Moduły Zmienna name zawiera nazwę bieżącego pakietu #!/usr/bin/python # Filename: using_name.py if name == ' main ': print 'This program is being run by itself' else: print 'I am being imported from another module'
Moduły $ python using_name.py This program is being run by itself $ python >>> import using_name I am being imported from another module >>>
Moduły >>> import sys >>> dir(sys) # get list of attributes for sys module [' displayhook ', ' doc ', ' excepthook ', ' name ', ' stderr ', ' stdin ', ' stdout ', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type',...
Pakiety sound/ Top-level package init.py Initialize the sound package formats/ Subpackage for format conversions init.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py >>> from sound.formats import wavwrite
number = 23 running = True while running: guess = int(raw_input('enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' running = False # this causes the while loop to stop #break - but we can't use break here -> no else then elif guess < number: print 'No, it is a little higher than that.' else: print 'No, it is a little lower than that.' else: print 'The while loop is over.' # Do anything else you want to do here print 'Done'
For for i in range(1, 5): print i else: print 'The for loop is over' W for może wystąpić dowolny typ sekwencyjny: str, unicode, list, tuple, buffer, xrange Range zwraca listę, lista: [1,2,3,4] Tuple (krotka) tworzona operatorem, : 1,2,3 (3,) () 'ala', makota (rzutowanie str() ) u'ala', u makota (rzutowanie unicode() ) Operacje na sekwencjach: Operacje: x in s, x not in s, s+t, s * n, s[i], s[i:j], s[i:j:k] Operacje: len(s), min(s), max(s)
Typy sekwencyjne >>> lists = [[]] * 3 >>> lists [[], [], []] >>> lists[0].append(3) >>> lists [[3], [3], [3]] >>> lists = [[], [], []] >>> lists[0].append(3) >>> lists[1].append(5) >>> lists[2].append(7) >>> lists [[3], [5], [7]]
Slicing >>> word= Hello >>> word[0:2] 'He' >>> word[2:4] 'll' >>> word[:2] # The first two characters 'He' >>> word[2:] # Everything except the first two characters 'llo' >>> word[-2:] # The last two characters 'lo' >>> word[:-2] # Everything except the last two characters 'Hel' >>> word[1:5:3] # Slice from 1 to 5 with step 3 'eo'
Slicing +---+---+---+---+---+ H e l l o +---+---+---+---+---+ 0 1 2 3 4 5-5 -4-3 -2-1
Deklaracja funkcji i zmiennych globalnych Funkcje def say(message, times = 1): print message * times say(times=3,message= hello ) Zmienne globalne def func(): global x print 'x is', x x = 2 print 'Changed global x to', x x = 50 func()
Typizacja Python, Groovy, JavaScript, Ruby są dynamicznie typowalne (dynamic typing) Typ związany z wartością nie zmienną x=5 x= 5 C/C++, Java są statycznie typowalne (static typing) Typ związany ze zmienną nie wartością, czasem niejawnie: int main() { length::meter a(5); force::newton b(6); BOOST_AUTO(c, a * b); }
Typizacja Python jest silnie typowalny (strongly typed) Kontrolowane są operacje czy są wykonalne na danym typie >>> a="a" >>> a=a+3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects JavaScript jest słabo typowalny (weakly typed) Rzutowania wykonywane są w locie Python ma bezpieczną typizację (type-safe) C nie ma bezpiecznej typizacji (type-unsafe) rzutowanie z/na void*
Duck Typing class Duck: def quack(self): print "Quaaaaaack!" def feathers(self): print "The duck has white and gray feathers." class Person: def quack(self): print "The person imitates a duck." def feathers(self): print "The person takes a feather and shows it."
Duck Typing def in_the_forest(duck): duck.quack() duck.feathers() def game(): donald = Duck() john = Person() in_the_forest(donald) in_the_forest(john) game()
Python - problemy Nie jest tak szybki jak C/C++ Dynamiczna typizacja może być niebezpieczna Global Interpreter Lock
Unladen Swallow JVM dla Pythona od Google We want to make Python faster, but we also want to make it easy for large, well-established applications to switch to Unladen Swallow. 1. Produce a version of Python at least 5x faster than CPython. 2. Python application performance should be stable. 3. Maintain source-level compatibility with CPython applications. 4. Maintain source-level compatibility with CPython extension modules. 5. We do not want to maintain a Python implementation forever; we view our work as a branch, not a fork. In addition, we intend to remove the GIL and fix the state of multithreading in Python. We believe this is possible through the implementation of a more sophisticated GC
Alternatywne implementacje Psyco JIT Jython interpreter w Javie PyPy interpreter w Pythonie (sic!)... JIT Zawężony zakres języka (RPython) Stackless Python