1 python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise...

18
1 Python strukturalno, objektno (sve je objekt!), funkcionalno and del for is raise assert elif from lambda return break else global not try class except import or while continu e exec if pass yield def finally in print 29 riječi

Upload: bernard-nelson

Post on 31-Dec-2015

219 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

1

Python strukturalno, objektno (sve je objekt!), funkcionalno

and del for is raise

assert elif from lambda return

break else global not try

class except import or while

continue exec if pass yield

def finally in print 29 riječi

Page 2: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

2

# -*- coding: cp1250 -*-ime = raw_input ("Kako se zoveš? ")print imebroj=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? 33 puta hura za: miki miki miki >>>

Page 3: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

3

Modules (+classes, functions, vars) import module

koristiti : module.name from module import name

koristiti : name

import mathx = 1.0while x < 10.0: print x, '\t', math.log(x) x = x + 1.0

1.0 0.02.0 0.693147180563.0 1.098612288674.0 1.386294361125.0 1.609437912436.0 1.791759469237.0 1.945910149068.0 2.079441541689.0 2.19722457734>>>

Page 4: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

4

Numbers, sequences, dictionaries

integerlong integerfloat, doublecomplex

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

stringlisttuple

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'])

Page 5: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

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

Page 6: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

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)>>> MONDAY0>>> TUESDAY1

Page 7: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

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']

Page 8: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

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ža

n redoslij

ed

definicija fu

nkcija

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)

Page 9: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

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: 1220formal arg2: 740.0Xtra arg c: grail----------formal arg1: mysteryformal arg2: talesXtra arg c: 123Xtra arg d: poe----------formal arg1: oneformal arg2: defaultBXtra arg men: ('freud', 'gaudi')Xtra arg e: zooXtra arg d: 10>>>

Page 10: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

10

Classclass 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'

Page 11: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

11

Subclassclass 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', '[email protected]') Created instance for: John Doe >>> john.name 'John Doe' >>> john.email '[email protected]' >>> john.updatePhone('415-555-1212') Updated phone# for: John Doe

>>> john.phone '415-555-1212' >>> john.updateEmail('[email protected]') Updated e-mail address for: John Doe>>> john.email '[email protected]'

Page 12: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

12

Multiple inheritanceclass 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()

Page 13: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

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

Page 14: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

14

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

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'

Page 15: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

15

TCP Timestamp

from socket import * <$nopage>from time import time, ctime

HOST = ''PORT = 21567BUFSIZ = 1024ADDR = (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()

from socket import * <$nopage>

HOST = 'localhost'PORT = 21567BUFSIZ = 1024ADDR = (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()

Server

Client

Page 16: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

16

Threadingfrom time import sleep, time, ctimedef 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 2006loop 0 done at: Thu Apr 27 13:30:01 2006start loop 1 at: Thu Apr 27 13:30:01 2006loop 1 done at: Thu Apr 27 13:30:03 2006all DONE at: Thu Apr 27 13:30:03 2006>>>

Page 17: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

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*()

Page 18: 1 Python strukturalno, objektno (sve je objekt!), funkcionalno anddelforisraise asserteliffromlambdareturn breakelseglobalnottry classexceptimportorwhile

18

Strings (NLTK), sys, os, web,...import sys # load the system libraryfor 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 = 0for char in fruit: if char == 'a': count = count + 1print count

import stringfruit = "banana"index = string.find(fruit, "a")print indexprint string.find("banana", "na", 3)print string.find("bob", "b", 1, 2)

def isLower(ch): return string.find(string.lowercase, ch) != -1def isLower(ch): return ch in string.lowercasedef isLower(ch): return 'a' <= ch <= 'z'

urllib, re, cgi, subprocess, HTMLParser, BeautifulSoup,...