Download presentation
Presentation is loading. Please wait.
Published byBernard Nelson Modified over 9 years ago
1
1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile continueexecifpassyield deffinallyinprint 29 riječi
2
2 # -*- coding: cp1250 -*- ime = raw_input ("Kako se zoveš? ") print ime broj=input('Tvoj najdraži broj? ') print broj, 'puta hura za:', broj*ime Interpreter : Python Shell 2.5 – IDLE + batch; PythonWin, PyScripter,... >>> Kako se zoveš? miki miki Tvoj najdraži broj? 3 3 puta hura za: miki miki miki >>>
3
3 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 >>>
4
4 Numbers, sequences, dictionaries integer long integer float, double complex 0101 84 -237 0x80 16384L -0x4E8L 017L -2147483648l 3.1416 4.2E-10 -90. 6.022e23 6.23+1.5j -1.23-875J -.0224+0j string list tuple aString = 'Hello World!' aList = [123,'abc', 4.56,['inner','l'], 7-9j] aTuple = (123,'abc',4.56,['inner', 't'],7-9j) dictionary dict2 = {'name': 'earth', 'port': 80} print 'host %s is running on port %d' % \ … (dict2['name'], dict2['port'])
5
5 Conditionals and loops if if not warn and (system_load >= 10): print "WARNING: losing resources" else (elif) if (balance > 0.00): if ((balance - amt) > min_bal) and (atm_cashout() == 1): print "here's your cash; please take all bills."..else: print "your balance is zero or negative" for for eachLetter in 'Names': print 'current letter:', eachLetter nameList=['Walter', "Nicole", 'Steven', 'Henry'] for eachName in nameList: print eachName, "Lim"...while, break, continue
6
6 Indexing, slicing, formating,....insert,.new,.extend,.append.,.index,.pop(), len(),... slicing indexing >>> 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' >>> range(7) [0, 1, 2, 3, 4, 5, 6] >>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) >>> MONDAY 0 >>> TUESDAY 1
7
7 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']
8
8 Functions def foo(): print 'in foo()' bar() def bar(): print 'in bar()' >>> foo() in foo() in bar() def taxMe(cost, rate=0.0825): … return cost + (cost * rate) >>> taxMe(100) 108.25 >>> taxMe(100, 0.05) 105.0 Nije važan redoslijed definicija funkcija 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)
9
9 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 >>>
10
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 >>> john.name 'John Doe' >>> jane.phone '650-555-1212' >>> john.updatePhone('415-555-1212') Updated phone# for: John Doe >>> john.phone '415-555-1212'
11
11 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'
12
12 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()
13
13 Functional Programming def add(x, y): lambda x, y: x + y return x + y >>> a = lambda x, y=2: x + y >> a(3) 5 >> a(3,5) 8 >> a(0) 2 >> a(0,9) 9 Built-in Functions: apply(), filter(), map(), reduce() >>> 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
14
14 Exceptions (try – except, assert, raise) >>> aDict = {'host': 'earth', 'port': 80} >>> print aDict['server'] Traceback (innermost last): File " ", line 1, in ? KeyError: server >>> try: … f = open('blah') … except IOError: … print 'could not open file' … could not open file def safe_float(object): try: retval = float(object) except ValueError: retval = 'could not convert non-number to float‘ return retval OverflowError, ZeroDivisionError, ValueError, IndexError, EOFError,... >>> safe_float('12.34') >>> safe_float('bad input') 12.34 'could not convert non-number to float'
15
15 TCP Timestamp from socket import * 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 tcpCliSock.send('[%s] %s' % \ ctime(time()), data) tcpCliSock.close() tcpSerSock.close() from socket import * 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 tcpCliSock.send(data) data = tcpCliSock.recv(1024) if not data: break print data tcpCliSock.close() Server Client
16
16 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 >>>
17
17 Executing Non-Python Programs 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 import os result = os.system('cat /etc/motd') Have a lot of fun… result 0 result = os.system('uname -a') 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 os.fork(), os.exec*(), os.wait*()
18
18 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,...
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.