180 likes | 473 Views
Python strukturalno, objektno (sve je objekt!), funkcionalno. Interpreter : Python Shell 2.5 – IDLE + batch; PythonWin, PyScripter,. # -*- coding: cp1250 -*- ime = raw_input ("Kako se zoveš? ") print ime broj=input('Tvoj najdraži broj? ') print broj, 'puta hura za:', broj*ime. >>>
E N D
Python strukturalno, objektno (sve je objekt!), funkcionalno
Interpreter: Python Shell 2.5 – IDLE + batch; PythonWin, PyScripter,... # -*- coding: cp1250 -*- ime = raw_input ("Kako se zoveš? ") print ime broj=input('Tvoj najdraži broj? ') print broj, 'puta hura za:', broj*ime >>> Kako se zoveš? miki miki Tvoj najdraži broj? 3 3 puta hura za: miki miki miki >>>
Modules (+classes, functions, vars) • import module koristiti : module.name • from module import name koristiti : name import math x = 1.0 while x < 10.0: print x, '\t', math.log(x) 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 >>>
Indexing, slicing, formating, ....insert, .new, .extend, .append., .index, .pop(),len(), ... >>> li = ["a", "b", "mpilgrim", "z", "example"] >>> li ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li[−3] 'mpilgrim' >>> li[1:−1] ['b', 'mpilgrim', 'z'] >>> li.insert(2, "new") >>> li ['a', 'b', 'new', 'mpilgrim', 'z', 'example'] >>> li.pop() 'example' >>> li = [1, 2] * 3 >>> li [1, 2, 1, 2, 1, 2] >>> k = "uid" >>> v = "sa" >>> "%s=%s" % (k, v) 'uid=sa' indexing slicing >>> range(7) [0, 1, 2, 3, 4, 5, 6] >>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) >>> MONDAY 0 >>> TUESDAY 1
keys, values, items ; .join, .split, ... >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> params.keys() ['server', 'uid', 'database', 'pwd'] >>> params.values() ['mpilgrim', 'sa', 'master', 'secret'] >>> params.items() [('server', 'mpilgrim'), ('uid', 'sa'), ('database', 'master'), ('pwd', 'secret')] >>> [k for k, v in params.items()] ['server', 'uid', 'database', 'pwd'] >>> [v for k, v in params.items()] ['mpilgrim', 'sa', 'master', 'secret'] >>> ["%s=%s" % (k, v) for k, v in params.items()] ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret'] >>>s = ";".join(["%s=%s" % (k, v) for k, v in params.items()])s 'server=mpilgrim;uid=sa;database=master;pwd=secret' >>> s.split(";") ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
Functions Nije važan redoslijed definicija funkcija def foo(): print 'in foo()' bar() def bar(): print 'in bar()' >>> foo() in foo() in bar() >>> taxMe(100) 108.25 >>> taxMe(100, 0.05) 105.0 def taxMe(cost, rate=0.0825): … return cost + (cost * rate) def tupleVarArgs(arg1, arg2='defaultB', *theRest): print 'formal arg 1:', arg1 print 'formal arg 2:', arg2 for eachXtrArg in theRest: print 'another arg:', eachXtrArg (non-keyword)
Function arguments (keyworded) def dictVarArgs(arg1, arg2='defaultB', **theRest): 'display 2 regular args and keyword variable args' print 'formal arg1:', arg1 print 'formal arg2:', arg2 for eachXtrArg in theRest.keys(): print 'Xtra arg %s: %s' % \ (eachXtrArg, str(theRest[eachXtrArg])) dictVarArgs(1220, 740.0, c='grail') dictVarArgs('mystery', arg2='tales', c=123, d='poe') dictVarArgs('one', d=10, e='zoo', men=('freud','gaudi')) formal arg1: 1220 formal arg2: 740.0 Xtra arg c: grail ---------- formal arg1: mystery formal arg2: tales Xtra arg c: 123 Xtra arg d: poe ---------- formal arg1: one formal arg2: defaultB Xtra arg men: ('freud', 'gaudi') Xtra arg e: zoo Xtra arg d: 10 >>>
Class class AddrBookEntry: 'address book entry class' def __init__(self, nm, ph): self.name = nm self.phone = ph print 'Created instance for:', self.name def updatePhone(self, newph): self.phone = newph print 'Updated phone# for:', self.name >>> john = AddrBookEntry('John Doe', '408-555-1212') Created instance for: John Doe >>> jane = AddrBookEntry('Jane Doe', '650-555-1212') Created instance for: Jane Doe >>> john <__main__.AddrBookEntry instance at 80ee610> >>> john.name 'John Doe' >>> jane.phone '650-555-1212' >>> john.updatePhone('415-555-1212') Updated phone# for: John Doe >>> john.phone'415-555-1212'
Subclass class AddrBookEntryWithEmail(AddrBookEntry): 'update address book entry class' def __init__(self, nm, ph, em): AddrBookEntry.__init__(self, nm, ph) self.email = em def updateEmail(self, newem): self.email = newem print 'Updated e-mail address for:', self.name >>> john = AddrBookEntryWithEmail('John Doe, '408-555- 1212', 'john@spam.doe') Created instance for: John Doe >>> john.name 'John Doe' >>> john.email 'john@spam.doe' >>> john.updatePhone('415-555-1212') Updated phone# for: John Doe >>> john.phone '415-555-1212' >>> john.updateEmail('john@doe.spam') Updated e-mail address for: John Doe>>> john.email 'john@doe.spam'
Multiple inheritance class P1: # parent class 1 def foo(self): print 'called P1-foo()' class P2: # parent class 2 def foo(self): print 'called P2-foo()' def bar(self): print 'called P2-bar()' class C1(P1,P2): # child 1 der.from P1,P2 pass class C2(P1,P2): # child 2 der.from P1,P2 def foo(self): print 'called C2-foo()' def bar(self): print 'called C2-bar()‘class GC(C1,C2): # define grandchild class pass # derived from C1 and C2 >> gc = GC() >> gc.foo() # GC ? C1 ? P1 called P1-foo() >> gc.bar() # GC ? C1 ? P1 ? P2 called P2-bar() >> C2.foo(gc) called C2-foo()
Functional Programming def add(x, y): lambda x, y: x + y return x + y Built-in Functions: apply(), filter(), map(), reduce() >>> a = lambda x, y=2: x + y >> a(3) 5 >> a(3,5)8>> a(0)2>> a(0,9)9 >>>map((lambda x: x+2),[0, 1, 2, 3, 4, 5]) [2, 3, 4, 5, 6, 7]>>> map(lambda x: x**2, [0, 1, 2, 3, 4, 5]) [0, 1, 4, 9, 16, 25]>>> map((lambda x: x**2),range(6)) [0, 1, 4, 9, 16, 25]>>> map(lambda x, y: (x+y, x-y), [1,3,5], [2,4,6]) [(3, -1), (7, -1), (11, -1)] >>> def sum(x,y): return x+y >>> allNums = range(5) >>> total = 0 >>> for eachNum in allNums: ... total = sum(total, eachNum)...>>> print 'the total is:' total the total is: 10 >>> print 'the total is:', reduce((lambda x,y: x+y), range(5))the total is: 10
Exceptions (try – except, assert, raise) >>> aDict = {'host': 'earth', 'port': 80} >>> print aDict['server'] Traceback (innermost last): File "<stdin>", line 1, in ? KeyError: server >>> try: … f = open('blah') … except IOError: … print 'could not open file' … could not open file OverflowError , ZeroDivisionError , ValueError, IndexError, EOFError, ... def safe_float(object): try: retval = float(object) except ValueError: retval = 'could not convert non-number to float‘ return retval >>> safe_float('12.34') >>> safe_float('bad input')12.34 'could not convert non-number to float'
TCP Timestamp Server from socket import * <$nopage> from time import time, ctime HOST = '' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) while 1: print 'waiting for connection…' tcpClisock, addr = tcpSerSock.accept() print '…connected from:', addr while 1: data = tcpCliSock.recv(BUFSIZ) if not data: break <$nopage> tcpCliSock.send('[%s] %s' % \ ctime(time()), data) tcpCliSock.close() tcpSerSock.close() Client from socket import * <$nopage> HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(ADDR) while 1: data = raw_input('> ') if not data: break <$nopage> tcpCliSock.send(data) data = tcpCliSock.recv(1024) if not data: break <$nopage> print data tcpCliSock.close()
Threading from time import sleep, time, ctime def loop0(): print 'start loop 0 at:', ctime(time()) sleep(4) print 'loop 0 done at:', ctime(time()) def loop1(): print 'start loop 1 at:', ctime(time()) sleep(2) print 'loop 1 done at:', ctime(time()) def main(): print 'starting…' loop0() loop1() print 'all DONE at:', ctime(time()) if __name__ == '__main__': main() >>> starting… start loop 0 at: Thu Apr 27 13:29:57 2006 loop 0 done at: Thu Apr 27 13:30:01 2006 start loop 1 at: Thu Apr 27 13:30:01 2006 loop 1 done at: Thu Apr 27 13:30:03 2006 all DONE at: Thu Apr 27 13:30:03 2006 >>>
Executing Non-Python Programs import os result = os.system('cat /etc/motd') Have a lot of fun…result 0 result = os.system('uname -a') import os f = os.popen('uname -a') data = f.readline() f.close()print data Linux solo 2.2.13 #1 Mon Nov 8 15:08:22 CET 1999 i586 unknown os.fork(), os.exec*(), os.wait*() ret = os.fork() # spawn 2 processes, both return if ret == 0: # child returns with PID of 0 child_suite # child code else: # parent returns with child's PID parent_suite # parent code
Strings (NLTK), sys, os, web,... import sys # load the system library for line in sys.stdin.readlines(): # for each line of input for word in line.split(): # for each word in the line if word.endswith('ing'): # does the word end in 'ing'? print word # if so, print the word fruit = "banana" count = 0 for char in fruit: if char == 'a': count = count + 1 print count import string fruit = "banana" index = string.find(fruit, "a") print index print string.find("banana", "na", 3) print string.find("bob", "b", 1, 2) def isLower(ch): return string.find(string.lowercase, ch) != -1 def isLower(ch): return ch in string.lowercase def isLower(ch): return 'a' <= ch <= 'z' urllib, re, cgi,subprocess, HTMLParser, BeautifulSoup,...