Upload
dragoljub-zivanovic
View
257
Download
0
Embed Size (px)
Citation preview
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
1/18
1
Pythonstrukturalno, 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 rijei
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
2/18
2
# -*- coding: cp1250 -*-ime = raw_input ("Kako se zove? ")print imebroj=input('Tvoj najdrai broj? ')
print broj, 'puta hura za:', broj*ime
Interpreter: Python Shell 2.5 IDLE + batch;PythonWin, PyScripter,...
>>>
Kako se zove? miki
miki
Tvoj najdrai broj? 33 puta hura za: miki miki miki
>>>
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
3/18
3
Modules (+classes, functions, vars)
import modulekoristiti : 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.0
2.0 0.69314718056
3.0 1.09861228867
4.0 1.38629436112
5.0 1.609437912436.0 1.79175946923
7.0 1.94591014906
8.0 2.07944154168
9.0 2.19722457734
>>>
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
4/18
4
Numbers, sequences, dictionaries
integerlong 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
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'])
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
5/18
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
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
6/18
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
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
7/18
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']
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
8/18
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
def tupleVarArgs(arg1, arg2='defaultB', *theRest):print 'formal arg 1:', arg1print 'formal arg 2:', arg2for eachXtrArg in theRest:print 'another arg:', eachXtrArg
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
9/18
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
>>>
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
10/18
10
Classclass AddrBookEntry:'address book entry class'def __init__(self, nm, ph):
self.name = nmself.phone = phprint 'Created instance for:', self.name
def updatePhone(self, newph):self.phone = newphprint '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'
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
11/18
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 = newemprint '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
>>> 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
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
12/18
12
Multiple inheritance
class P1: # parent class 1def foo(self):print 'called P1-foo()'
class P2: # parent class 2def foo(self):
print 'called P2-foo()'def bar(self):print 'called P2-bar()'
class C1(P1,P2): # child 1 der.from P1,P2pass
class C2(P1,P2): # child 2 der.from P1,P2def foo(self):
print 'called C2-foo()'def bar(self):print 'called C2-bar()
class GC(C1,C2): # define grandchild classpass # derived from C1 and C2
>> gc = GC()
>> gc.foo() # GC ? C1 ? P1called P1-foo()
>> gc.bar() # GC ? C1 ? P1 ? P2called P2-bar()
>> C2.foo(gc)called C2-foo()
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
13/18
13
Functional Programming
defadd(x, y): lambda x, y: x + yreturn 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:' totalthe total is: 10
>>> print 'the total is:', reduce((lambda x,y: x+y), range(5))the total is: 10
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
14/18
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)exceptValueError: retval = 'could not convert non-number to floatreturn retval
OverflowError , ZeroDivisionError ,
ValueError, IndexError, EOFError, ...
>>> safe_float('12.34') >>> safe_float('bad input')12.34 'could not convert non-number to float'
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
15/18
15
TCP Timestamp
from socket import * from time import time, ctime
HOST = ''PORT = 21567BUFSIZ = 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 = 21567BUFSIZ = 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
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
16/18
16
Threading
from 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()
>>>
startingstart 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>>>
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
17/18
17
Executing Non-PythonPrograms
import osf = 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 osresult = os.system('cat /etc/motd')Have a lot of funresult0
result = os.system('uname -a')
ret = os.fork() # spawn 2 processes, both returnif ret == 0: # child returns with PID of 0child_suite # child code
else: # parent returns with child's PIDparent_suite # parent code
os.fork(), os.exec*(), os.wait*()
7/28/2019 Python 2.x. Tut Na Srpskom Acess-u
18/18
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 lineif 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 + 1
print 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) != -1
def isLower(ch):return ch in string.lowercase
def isLower(ch):return 'a'