+MЪMXLMЖY ,MЖRRE]4]XLSRPɧQШXXVSRKRLоRKRKɺRRKоPϼTXVɳRL чERKчвGGLɾʁFЮMXɴRLчEHϰRKZАиRKHдRKXLZMЖR TLSRKTLɾZɧGШRKчТRKчɺRKчϲS ɇɪPɧQZMЖGZЪM4,4RʆQZɧGɹRLоRKXɨGZдQɧ4,4 OLɹQɧXLрGLMЖRXРMYчвGOLMЎRQɳRLTLϲMXMЎTGϼRZЪM 4]XLSRXVSRKKMEMчSϰRRɧ] 'YРRWɨGLRLОRɧ]чвGZMЎXXVSRKUYɨXVɳRLQɳRLFϾXч϶Y LМG4]XLSRZɧKMϲMUY]ЎXGɨGFɧMXSɨRGFϲRXLISRLYG϶Y GжEQɳRL ,]ZМRKRLоRKKLMGLɰTGжEQɳRLGˢRKWЌKMɾTɴGLGLS RLоRKEMчERKUYERXɩQчЎRZMЖGиRKHдRK4]XLSRZɧS GɺRKZMЖGZɧ\мPʁLMЖRXϰM 1дGPдG 7ɨGLчвGGLMEPɧQGLRKQЦMGLRKWЌXVɳRLFɧ] OLɴEGϰRLGжE4]XLSRQɧQɳRLWЌKІTTLϲMZɧWЌLоYɴGL OLMFMЎXGɨGOMЎRXLиGRɧ]XVSRKZMЖGɨTHдRK4]XLSRZɧS GɺRKZMЖGXVSRKXRKPEM ,IPPS[SVPH 'ɾTLɨT 4LɩRGLMEQSHYPI 'PEWW 8LESXɨGXVɱRXϼTXMR <мPʁLɳRLϲRL <мPʁJMPI.732 <мPʁJMPI<10 /ЎXRРM1]750 /ЎXRРM6IHMW /ЎXRРM1IQGEGLIH /ЎXRРM6EFFMX15 6IWXJYP'PMIRX +ЮMIQEMPZЪM7184 7SGOIX4VSKVEQQMRK 'LRK,IPPS[SVPH 4]XLSRPɧQШXRKɺRRKоTLMɱRHКGL -RXIVTVIXIV0ERKYEKI XиGPɧOLɺRKG϶RFYMPHXLɧRLJMPIXLрGXLMQɧGLϰ]XVрGXMЎT RL4,4 ,MЖRXϰM4]XLSRGɹRLɨRLGLɴRLPɧ\Zɧ\ЭRLɨRL\ чɪHкRKTLɨXXVMВRZɧчERKчиRKЮTLMɱRFϲR2LɨRL 4]XLSR\XLɳZϺRчERKчвGXMЎTXдGTLɨXXVMВR ;IFWMXIGLɴRLXLиGGжE4]XLSR[[[T]XLSRSVK 'ɧMчІX 4]XLSRLЦXVвL϶YLЎXGɨGRАRXϲRKZɧVϴXHДXɳQXLϴ]WЄR XVɱRQШXWРLЖчMАYLɧRLRL1EG37ŷ ɇВFMЎXPɧLЖXLРRKGжEFϰRчɪGɧM4]XLSRGLEGɹXLВZɧS QɧRLɳRLGSQQERHPMRIZɧKɻ $ python --version 2ЎYчɪGɧMчІXT]XLSRXLɳWЌLMВRXLКXLɺRKXMRTLMɱRFϲR T]XLSR2ЎYFɨSPЦMXLɳчТRKRKLʨEZЪMFϰRGLEGɧMчІX 4]XLSR 'ɹXLВXLEQOLϲSGɨGLGɧMчІX4]XLSRXϰM LXXTW[[[T]XLSRSVKHS[RPSEHW 'ɺRKGдTLɨXXVMВR 'LИG϶RHɽRKQШXXI\XIHMXSVPɧFϰRGɹXLВZMЎXчвGGSHI T]XLSRLSІGGɹXLВHɽRKGɨGGɺRKGдGESGϴTLR -() RL%TXERE4]'LEVQŷ'ɨG-()XLЬRKLЦXVвXLɱQUYɨ XVɳRLTLɩRXɴGLGɾTLɨTHɸRKPЖRLHIFYKŷXVSRKTLϰQZM GYРRWɨGLRLОRɧ]XLɳQɳRLLЪRKчЎRGɨGLXLрGXLM T]XLSRFЀRKHɸRKPЖRL ,IPPS[SVPH 8ϰSQШXJMPIGɹXɱRPɧ helloworld.py ZɧGɹRШMHYRKRL WEY print 'Hello world' print PɧPЖRLGFϲRRLϴXчВ\YϴXQШXFMЎRVE XLЬRKPɧ QɧRLɳRL 7EYчɹZɧSQɧRLɳRLGSQQERHPMRIHMGLY]ВRчЎRXL QдGGLиEJMPIRɧ]ZɧKɻ $ python helloworld.py 2ЎYXLϴ]\YϴXLMЖRHɸRKGLо Hello world XиGPɧFϰRчɪ LSɧRXLɧRLZMЖGZMЎXиRKHдRKT]XLSRч϶YXMɱR 'LRK'ɾTLɨT &MЎRWР /LEMFɨSFMЎRFЀRKQШXGɩYPЖRLKɨR a = 1 FϰRGɹXLВKɨRRLMАYPSϰMKMɨXVК WРGLYЦM GLSQШXFMЎR a = 1 a = 'Hello World' a = [1, 2, 3] a = [1.2, 'Hello', 'W', 2] 8SɨRXмWРLМG 4]XLSRGˢRKLЦXVвQШXWРXSɨRXмXSɨRLМGXLɺRKHдRK RL + TLɰTGШRK - TLɰTXVк * TLɰTRLɩR / TLɰTGLME % TLɰTGLMEPϴ]H QSHYPS &SSPIERZɧ8SɨRXмPSKMG +MɨXVКчɾRKZɧWEMXRKиRKPɧ True Zɧ False not чВчϲSKMɨXVК and TLɰTXɴRLPSKMGZɧ %2( or TLɰTXɴRLPSKMGLSІG 36 1ШXWРTLɰTWSWɨRLXLɺRKXLЬRKRL < FɰLR <= Fɰ LRLSІGFЀRK > PЪRLR >= PЪRLRLSІGFЀRK == FЀRK != OLɨG чВWSWɨRLKMɨXVК ,ЦXVвHϰRKWSWɨRLOɰTRL x = 2 1 < x < 3 # True 10 < x < 20 # False 3 > x <= 2 # True 2 == x < 4 # True 8SɨRXмOMВQXVETL϶RXмXVSRKQШXXϼTLвT in OMВQXVE GɹXТRXϰM not in OMВQOLɺRKXТRXϰM 'good' in 'this is a greate example' alse 'good' not in 'this is a greate example' # F # True 'ϴYXVɾGчMАYOLMВR 4]XLSRLЦXVвQШXWРGϴYXVɾGчMАYOLMВRXLɺRKHдRK,϶Y LЎXGɨGGϴYXVɾGчMАYOLMВRчАYHрEZɧSXLдXч϶YHɸRK MRHIRXMSR чВXϰSXLɧRLQШXFPSGO\мPʁXLE]ZɳWмHдRK { ŷ } RLGɨGRKɺRRKоOLɨG 4,4.EZEWGVMTX -JŷIPMJŷIPWI if condition1 : indentedStatementBlockForTrueCondition1 elif condition2 : indentedStatementBlockForFirstTrueCondition2 elif condition3 : indentedStatementBlockForFirstTrueCondition3 elif condition4 : indentedStatementBlockForFirstTrueCondition4 else: indentedStatementBlockForEachConditionFalse 7[MXGLŷGEWI 4]XLSROLɺRKGɹGϴYXVɾG switch ŷ case *SVŷMR for iterating_var in sequence: statements(s) :ɴHд for letter in 'Python': # First Example print 'Current Letter :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # Second Example print 'Current fruit :', fruit print "Good bye!" /ЎXUYϲLMВRXLКGжEZɴHдXVɱR Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Current fruit : banana Current fruit : apple Current fruit : mango Good bye! ;LMPI while expression: statement(s) :ɴHд count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!" /ЎXUYϲLMВRXLКGжEZɴHдXVɱR The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 The count is: 5 The count is: 6 The count is: 7 The count is: 8 Good bye! ,ɧQ /LEMFɨSLɧQXLISGɾTLɨT def functionname(param, param2,..): statements(s) ,ɧQRЎYOLɺRKXVϲHоPMЖYXLɳQІGчКRLWЌXVϲZАKMɨXVК None :ɴHдOLEMFɨSLɧQXɴRLZɧXVϲZАKMɨXVКXФRKGжEXLEQ WРч϶YZɧS def sum(a, b): return (a+b) 'ɨGLKМMLɧQ sum(1, 2) (trҥ vӃ giá trӍ là 3) ,ɧQGɹLЦXVвKMɨXVКQІGчКRLGLSXLEQWРOLMOLɺRK XVY]АRZɧS:ɴHдLɧQWEY def plus(c, d = 10): return (c+d) 2ЎYKМMLɧQXVɱRRLWEY plus(2) (kӁt quҥ trҥ vӃ là 12) 1ШXOLɨGFMЖXXVSRKGɨGLKМMLɧQGжE4]XLSRWSZЪM4,4 PɧGLɾRKXEGɹXLВXLE]чФMXLиXрXLEQWРXVY]АRZɧSFЀRK GɨGLчІXXɱRXLEQWРOLMKМMLɧQ:ɴHдXEGɹXLВKМMLɧQ sum(a,b) ЮZɴHдXVɱRFЀRKGɨGLXVY]АRXLEQWР b XVЪG a RLWEY sum(b = 1, a = 10) <мPʁGLYЦM 1ШXGLYЦMGɹXLВOLEMFɨSFЀRKHϴYRLɨ]чɺM " LSІGчR ' :ɴHдGɨGGLYЦMWEY str1 = "Hello" str2 = 'world' 'ɹXLВXVY]\YϴXXкRKOʁXрXVSRKQШXGLYЦMXLISLɳRLXLиG MRHI\ZɴHд str1[0] str1[1] ŷ 'ɹXLВWмHдRKHϴYRLɨ] чɺMLSІGчR чВOLEMFɨS GLYЦMXVɱRRLMАYHɸRK:ɴHд paragraph = """This is line 1 This is line 2 This is line 3""" 2РMGLYЦM 'ɹXLВXϰSQШXGLYЦMHɧMXкZMЖGRРMGɨGGLYЦMPϰMXLISGɾ TLɨT str = str1 + " " + str2 8VɴGL\YϴXGLYЦMGSR 'ɹXLВXϰSGɨGGLYЦMGSRXLɺRKUYEXSɨRXмPϴ]OLSϲR [start:end] VERKI 1ІGчКRL start PɧXкZКXVɴч϶YGLYЦM 0 Zɧ end PɧчЎRZКXVɴGYРMGLYЦM:ɴHд str = 'Hello world' print str[0:4] (HiӅn thӍ "Hell") print str[:4] (HiӅn thӍ "Hell") print str[-3:] (HiӅn thӍ "rld") print str[6:-3] (HiӅn thӍ "wo") 0ϴ]чШHɧMGжEGLYЦM 7мHдRKLɧQ len(...) чВXVϲZАчШHɧMGжEGLYЦM:ɴHд count = len("Hello world") (count có giá trӍ 11) 8ɳQ XLE]XLЎRШMHYRK 'ɹXLВXɳQZɧXLE]XLЎXVSRKGLYЦMFЀRKGɨGLKМMTLRK XLиG replace(search, replace[, max]) GжEQШXGLYЦM:ɴ Hд str = 'Hello world' newstr = str.replace('Hello', 'Bye') print newstr (Sҿ hiӅn thӍ chuәi "Bye world" trên màn hình) 8ɳQZКXVɴGLYЦMGSR 'ɹXLВXɳQZКXVɴGжEQШXGLYЦMGSRXVSRKGLYЦMPЪRFЀRK GɨGLKМMTLRKXLиG find(str, beg=0 end=len(string)) &ϾXч϶YPɧZКXVɴ 0 RЎYOLɺRKXɳQVEXLɳ XVϲZА -1 :ɴHд str = 'Hello world' print str.find('world') (hiӅn thӍ 6) print str.find('Bye'); (hiӅn thӍ -1) ,ɧQ find() WЌXɳQXLISXLиXрXкXVɨMUYETLϲMGжEGLYЦM XиGPɧXкP϶R\YϴXLMЖRч϶YXMɱR'ɹXLВHɽRKLɧQ rfind() чВXɳQXLISZКXVɴXкGYРMGLYЦMZАTLɴEXVЪG 8ɨGLGLYЦM 'ɹXLВXɨGLGLYЦMHрEXLISQШXGLYЦMHIPMQIXIVFЀRKGɨGL KМMTLRKXLиG split(str="", num=string.count(str)) :ɴHд str = 'Hello world' print str.split(' ') (Trҥ vӃ mӛt mҥng có 2 phҩn tӯ là 2 chuәi "Hello" và "world") 'ɹXLВWмHдRKLɧQ splitlines() чВXɨGLGLYЦMXLIS XкRKLɧRKZɧPSϰMFОOʁXр2);0-2) 8VMQOʁXрOLSЂRKXVϾRK 'ɹXLВPSϰMFОGɨGOʁXр QІGчКRLPɧOʁXрOLSϲRKXVϾRK XVЪGZɧWEYQШXGLYЦMFЀRKGɨGLKМMGɨGTLRKXLиG WEY strip([chars]) PSϰMFОXVЪGZɧWEYGLYЦM lstrip([chars]) PSϰMFОTLɴEXVЪGGLYЦM rstrip([chars]) PSϰMFОTLɴEWEYGLYЦM 1ШXWРLɧQ\мPʁGLYЦM isnumeric() /MВQXVEQШXGLYЦMGɹTLϲMPɧGLYЦMWР lower() 'LY]ВRGLYЦMLЎXXLɧRLGLоXLЬRK upper() 'LY]ВRGLYЦMLЎXXLɧRLGLо,3% 0MWX 0MWXXVSRK4]XLSRPɧGϴYXVɾGQϲRKZɧGɨGTL϶RXмGɹMRHI\ GɹXLиXр/LɺRKRL4,4OI]GжEQШXQϲRKGɹXLВZкE PɧWРZкEPɧGLYЦM EWWSGMEXIHEVVE] 8VSRK4]XLSRQYРRXϰSQШXQϲRKGɹOI]PɧGLYЦMXLɳWЌ WмHдRKGϴYXVɾG(MGXMSREV] TL϶RXMЎTXMЎT 8VSRKTL϶R Rɧ]GLɾRKXEWЌRɹMчЎR0MWX1ШX0MWXчвGOLEMFɨSRL QϲRKXVSRK.7327мHдRK [..] чВOLEMFɨSQШXQϲRK :ɴHд numbers = [1, 2, 3, 4, 5] names = ['Marry', 'Peter'] 'ɹXLВXVY]\YϴXXкRKTL϶RXмGжEQϲRKFЀRKMRHI\TL϶R Xмч϶YXMɱRGɹXLиXрPɧ 0 :ɴHд print numbers[0] (HiӅn thӍ 1) print numbers[-3] (HiӅn thӍ 3) print names[1] (HiӅn thӍ 'Peter') ɇВFMЎXчвGWРPвRKTL϶RXмGжE0MWXGɹXLВWмHдRK LɧQ len(array) чВPϴ]WРPвRKTL϶RXмGжEQϲRKXLEQ WРXVY]АRZɧS /MВQXVEWрXТRXϰMGжEQШXTL϶RXм /MВQXVEXLIS-RHI\ 8VSRKRLMАYXVЬRKLвTFϰRQYРRXVY]\YϴXQШXTL϶RXм FϴXOΧ HрEZɧSMRHI\ GжEQϲRKXLɳRЎYXVY]\YϴXчЎRQШX TL϶RXмOLɺRKXТRXϰMXLɳиRKHдRKWЌFɨSPЦM(SчɹXVЪG OLMXVY]\YϴXQШXTL϶RXмFϰRG϶ROMВQXVE\IQTL϶RXм Rɧ]чɪXТRXϰMLE]GLE,MЖRXϰMT]XLSROLɺRKLЦXVвLɧQ RɧSчВOMВQXVEWрXТRXϰMGжEQШXTL϶RXмXVSRKQϲRK 'ɹGɨGLXLЬRKXLϴ]чВOMВQXVEчɹPɧŰ0SSOFIJSVI]SY PIETű 0&=0 ZɧŰ)EWMIVXSEWOJSVKMZIRIWWXLER TIVQMWWMSRű )%*4 :ɴHдZАŰ0SSOFIJSVI]SYPIET 0&=0 ű if index < len(array): array[index] else: # handle this :ɴHдZАŰ)EWMIVXSEWOJSVKMZIRIWWXLERTIVQMWWMSRű )%*4 try: array[index] except IndexError: # handle this /MВQXVEXLISKMɨXVК ɇВOMВQXVEQШXKMɨXVКGɹXТRXϰMOLɺRKXТRXϰMXVSRK QϲRKLE]OLɺRKXLɳGɹXLВWмHдRKXSɨRXм in not in :ɴ Hд mylist = ['a', 'b', 'c'] print 'a' in mylist (HiӅn thӍ True) print 'b' not in mylist (HiӅn thӍ False) 8VɴGL\YϴXQϲRKGSR 8RKXрRLGLYЦMXɹXLВXϰSGɨGQϲRKGSRXLɺRKUYE XSɨRXмPϴ]OLSϲR [start:end] VERKI 1ІGчКRL start Pɧ XкZКXVɴч϶YGLYЦM 0 Zɧ end PɧчЎRZКXVɴGYРMGLYЦM:ɴHд numbers = ['a', 'b', 'c', 'd'] print numbers[:2] (HiӅn thӍ ['a', 'b']) print numbers[-2:] (HiӅn thӍ ['c', 'd']) <ɹETL϶RXмGжEQϲRK 'ɹXLВ\ɹEQШXTL϶RXмXLɺRKUYEXSɨRXм del 8LиXрGжE GɨGTL϶RXмWЌHКGLGLY]ВRXɽ]ZɧSZКXVɴGжETL϶RXмFК \ɹE:ɴHд numbers = [1, 2, 3, 4, 5] del numbers[0] print numbers (HiӅn thӍ [2, 3, 4, 5]) &ϰRGɹXLВ\ɹEQШXOLSϲRHрEZɧSXSɨRXмPϴ]OLSϲR [start:end] :ɴHд numbers = [1, 2, 3, 4, 5, 6, 7] del numbers[2:4] print numbers (HiӅn thӍ [1, 2, 5, 6, 7]) 2РMQϲRK &ϰRGɹXLВWмHдRKXSɨRXм + чВRРMKMɨXVКGжEQϲRKZɧ XϰSVEQШXQϲRKPЪRGɹWРPвRKTL϶RXмPɧXФRKWРPвRK TL϶RXмGжEQϲRKGSR:ɴHд a = [1, 2] b = [1, 3] print a + b (HiӅn thӍ [1, 2, 1, 3]) 8LɱQTL϶RXмZɧSQϲRK 2ЎYFϰRQYРRXLɱQTL϶RXмZɧSQШXQϲRKчɪXТRXϰMLɪ] HɽRKTLRKXLиG list.append(newvalue) чВXLɱQTL϶R XмGɹKMɨXVК newvalue ZɧSGYРMQϲRK list :ɴHд numbers = [1, 2, 3] numbers.append(4) print numbers (HiӅn thӍ [1, 2, 3, 4] 0ϴ]TL϶RXмGYРMQϲRK 2ЎYQYРRPϴ]TL϶RXмGYРMGɽRKGжEQϲRKVEOLОMQϲRK GɹXLВWмHдRKTLRKXLиG list.pop() WЌXVϲZАKMɨXVК GжETL϶RXмGYРMGɽRKZɧQϲRKFɩ]KMЬWЌOLɺRKGɸRTL϶R XмRɧ] numbers = [1, 2, 3] mynumber = numbers.pop() print mynumber (HiӅn thӍ 3) print numbers (HiӅn thӍ [1, 2]) 8ɳQQШXKMɨXVКXVSRKQϲRK 2ЎYFϰRQYРRXɳQZКXVɴ MRHI\ GжEQШXKMɨXVКXVSRKQШX QϲRKGɹXLВHɽRKTLRKXLиG list.index(obj) 2ЎY XɳQXLϴ]WЌXVϲZАMRHI\GжETL϶RXмч϶YXMɱRXɳQXLϴ]2ЎY OLɺRKXɳQXLϴ]WЌUYʆRK)\GITXMSR:ɴHд aList = [123, 'xyz', 'zara', 'abc']; print "Index for xyz : ", aList.index('xyz') print "Index for zara : ", aList.index('zara') /LMGLϰ]WЌLMВRXLКOЎXUYϲ Index for xyz : 1 Index for zara : 2 ɇϲSRKвGKMɨXVКGжEQϲRK ɇВчϲSRKвGXLиXрGɨGKMɨXVКGжEQШXQϲRKWмHдRK TLRKXLиG list.reverse() 4LRKXLиGRɧ]OLɺRKXVϲ ZАOЎXUYϲQɧXLE]чФMXVрGXMЎTQϲRK list :ɴHд numbers = [1, 2, 3, 4] numbers.reverse() print numbers (HiӅn thӍ [4, 3, 2, 1]) 7ϾT\ЎTKMɨXVКGɨGTL϶RXм ɇВWϾT\ЎTXLиXрGжEKMɨXVКXVSRKQϲRKWмHдRKTLRK XLиG list.sort([func]) чВWϾT\ЎT2ЎYXLEQWРч϶Y ZɧSPɧLɧQ func OLɺRKXVY]АRZɧSXLɳQІGчКRLPɧWϾT\ЎT XLISKMɨXVКXʆRKH϶R4LRKXLиGRɧ]OLɺRKXVϲZАOЎX UYϲQɧXLE]чФMXVрGXMЎTQϲRK list :ɴHд aList = [123, 'xyz', 'zara', 'abc', 'xyz'] aList.sort() print "List : ", aList (HiӅn thӍ List : [123, 'abc', 'xyz', 'xyz', 'zara' ]) 'ɨGLXVMВROLEMLɧQGSQTEVI func() GˢRKKMРRKRLLɧQ YWSVXXVSRK4,4,ɧQXVϲZАGɨGKMɨXVК 0 -1 Zɧ 1 8YTPI 8YTPIGˢRKPɧQШXGϴYXVɾGQϲRKXRKXрRLGϴYXVɾG 0MWX1ШXWРчMВQOLɨGRLEYGFϲRPɧOLEMFɨS8YTPIWм HдRKGІTHϴYRKSІG (...) ZɧQШXXYTPIчɪчвGOLEMFɨS VТMXLɳOLɺRKXLE]чФMчвGKMɨXVК MQQYXEFPI ZɧOLɺRKLЦ XVвGɨGTLRKXLиGRL append() pop() ŷ:ɴHд mytuple = ('x', 'y', 'z') print mytuple (HiӅn thӍ ('x', 'y', 'z')) :ϺRLЦXVвGɨGGɨGLчВXVY]\YϴXTL϶RXмKMРRK0MWXRLPɧ XVY]\YϴXXLISMRHI\VERKIXɳQOMЎQŷ (MGXMSREV] (MGXMSREV]GˢRKPɧQШXGϴYXVɾGQϲRKRLRKGɨGTL϶RXм FESKТQOI]ZɧZEPYI2ЎYFϰRGɹFMЎX.732XLɳGϴYXVɾG (MGXMSREV]XRKXрRLQШXSFNIGXNWSR1ШX(MGXMSREV] чвGOLEMFɨSFЀRKGІTHϴYRKSІG {...} :ɴHд point = {'x': 1, 'y': 2} 8VY]\YϴXQШXKMɨXVКHрEZɧSOI]GжEчРMXвRK:ɴHд point = {'x': 3, 'y': 6, 'z' : 9} print point[x] (HiӅn thӍ 3) 8LɱQQШXTL϶RXм ɇВXLɱQQШXTL϶RXмZɧSчРMXвRKчɪOLEMFɨSWмHдRK GϴYXVɾG dict[key] = value :ɴHд user = {'name': 'Jone', 'age': 30} user['country'] = 'Vietnam' print user (HiӅn thӍ {'country': 'Vietnam', 'age': 30, 'name': 'Jone'}) 1ШXWРLɧQTLRKXLиGXLɺRKHдRK dict.clear() <ɹEXSɧRFШHоPMЖYFɱRXVSRKчРM XвRK dict.copy() 8VϲZАQШXFϲRGST]GжEчРMXвRK dict.fromkeys(seq[, value]) 8ϰSQШXчРMXвRKZЪM HERLWɨGLOI]XкWIUZɧRЎYGɹXVY]АR value XLɳPϴ] чɹPɧQKMɨXVКGLSGɨGTL϶RXм dict.has_key(key) OMВQXVEQШXOI]GɹXТRXϰMXVSRK чРMXвRKLE]OLɺRK dict.keys() 8VϲZАQШX0MWXGLиEGɨGOI] dict.values() 8VϲZАQШX0MWXGLиEGɨGZEPYI 'LRK4LɩRGLMEQSHYPI 8ϴXGϲZɴHдGLSчЎRXLЬMчMВQRɧ]чАYчвGXLрGXLMXVSRK GSQQERHPMRILSІGXкQШXJMPIT]XLSR .py 8Y]RLMɱRчРM ZЪMGɨGиRKHдRKPЪRGɹRLMАYGLиGRʆRKXLɳTLɩRGLMERLО HрɨRXLɧRLGɨGJMPIOLɨGRLEYWЌKMɾTHДFϲSXVɳZɧXɨMWм HдRKGɨGXLɧRLTL϶RчɪXLMЎXOЎ 'LRKRɧ]WЌKMɾTFϰRXLMЎXOЎGɨGXɴRLRʆRKXLISQɺ LɳRLGɨGQSHYPIZɧOLMG϶RXLɳWЌKМMJMPIXRKиRKZɧWм HдRK 'ɨGPSϰMQSHYPIXLZMЖR 'ɹPSϰMQSHYPIXLЬRKXLϴ]Pɧ :MЎXFЀRK4]XLSRGɹTL϶RQЮVШRKPɧ .py 'ɨGXLZMЖRPMɱROЎXчШRKGɹTL϶RQЮVШRKPɧ .dll .pyd .so .sl ŷ '1SHYPIPMɱROЎXZЪMXVɳRLTLMɱRHКGL ɇЬRKHϺRXɳQчВPSEHQSHYPI ɇВXϲMQШXQSHYPIZɧSWGVMTXGжEFϰRWмHдRKGɾTLɨT чRKMϲR import modulename OLMKІTGɩYPЖRLXVɱRXLɳXVɳRLFMɱRHКGLWЌXMЎRLɧRLXɳQ OMЎQJMPIQSHYPIXRKиRKXLISXLиXрXLQдGWEY 8LQдGLMЖRLɧRLQɧWGVMTXчERKKМM 'ɨGXLQдGXVSRK4=8,324%8, RЎYGɹWIX 'ɨGXLQдGGɧMчІXGLYϸRXVɱR0MRY\9RM\ 'ɹXLВFMЎXчвGчЬRKHϺRQɧQШXQSHYPIчɪчвGPSEH FЀRKчSϰRGSHIHЪMчɩ] import math math.__file__ (Ví dӧ trҥ vӃ '/usr/lib/python2.5/lib-dynload/math. so') import random random.__file__ (Ví dӧ trҥ vӃ '/usr/lib/python2.5/random.pyc') 0ϴ]HERLWɨGLXLYШGXɴRLZɧTLRK XLиGGжEQШXQSHYPI ɇВPϴ]чвGHERLWɨGLGɨGXLYШGXɴRLZɧTLRKXLиGQɧ QSHYPILЦXVвWмHдRKLɧQ dir(modulename) :ɴHд dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degree s', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'fa ctorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma' , 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'lo g', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians ', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] 'ɹXLВKМMLɧQ dir() OLɺRKXVY]АRXLEQWРчВPϴ]GɨG XLYШGXɴRLZɧTLRKXLиGGжEWGSTILMЖRXϰMчERKXLрG XLM 'ɨGLOLEMFɨSZɧWмHдRKQSHYPI +MϲWмFϰRXϰSQШXJMPIT]XLSR mymath.py GɹRШMHYRKRL WEY def cong(a, b): return a + b def tru(a, b): return a - b def nhan(a, b): return a * b 7EYчɹXϰSQШXJMPIGɹXɱR myexample.py XVSRKGɽRKXL QдGZЪMJMPI mymath.py ZкEXϰSЮXVɱRGɹRШMHYRKRL WEY import mymath num1 = 1 num2 = 2 print 'Tong hai so la: ', mymath.cong(num1, num2) :ɧSGSQQERHPMRIXLрGLMЖRKМMJMPIQ]I\EQTPIRLWEY $ python myexample.py 7EYOLMXLрGLMЖRWЌLMВRXLКPɱRQɧRLɳRLPɧ Tong hai so la: 3 4EGOEKIQSHYPI 'ɹXLВKSQRLMАYQSHYPI .py ZɧSQШXXLQдGZɧXɱRXL QдGPɧXɱRGжETEGOEKIZɧXϰSQШXJMPI __init__.py XVSRK XLQдGRɧ] 2LZϼ]GϴYXVɾGXLGжEQШXTEGOEKIWЌRLWEY |-- mypack | |-- __init__.py | |-- mymodule1.py | |-- mymodule2.py | 'ɹXLВWмHдRK mymodule1 XLISGɾTLɨTMQTSVXWEY import mypack.mymodule1 LSІG import mypack.mymodule1 as mymodule1 LSІG import mypack.mymodule1 as mod /LMWмHдRKQШXQSHYPIXLYШGQШXTEGOEKIXLɳGɨGPЖRL XVSRKJMPI __init__.py WЌчвGXLрGLMЖRXVЪG8LɺRK XLЬRKXLɳJMPI __init__.py WЌVЦRK 'ɹXLВXϰSGɨGWYFTEGOEKIFɱRXVSRKQШXTEGOEKIXLIS чɾRKGϴYXVɾGXLQдGGɹJMPI __init__.py :ɴHд import mypack.mysubpack.mysubsubpack.module 'LRK'PEWW 0ϼTXVɳRLLЪRKчРMXвRKPɧQШXOLɨMRMЖQOLɺRKXLВ XLMЎYXVSRKL϶YLЎXGɨGRKɺRRKоXLɺRKHдRKLMЖRRE] 4]XLSRGˢRKLЦXVвPϼTXVɳRLLЪRKчРMXвRKZЪMGɨGOLɨM RMЖQ'PEWW3FNIGX3ZIVVMHIŷ /LEMFɨSQШX'PEWW /LEMFɨSQШXGPEWWXLISGɾTLɨTWEY class myclass([parentclass]): assignments def __init__(self): statements def method(): statements def method2(): statements :ɴHдQШXGPEWW class animal(): name = '' name = '' age = 0 def __init__(self, name = '', age = 0): self.name = name self.age = age def show(self): print 'My name is ', self.name def run(self): print 'Animal is running...' def go(self): print 'Animal is going...' class dog(animal): def run(self): print 'Dog is running...' myanimal = animal() myanimal.show() myanimal.run() myanimal.go() mydog = dog('Lucy') mydog.show() mydog.run() mydog.go() 7EYOLMXLрGXLMWЌGLSVEOЎXUYϲ My Name is Animal is running... Animal is going... My Name is Lucy Dog is running... Animal is going... 8VSRKZɴHдXVɱRXLɳ animal Zɧ dog PɧGPEWW8VSRKчɹGPEWW dog OЎXLкE XкGPEWWGLEPɧ animal RɱRWЌGɹGɨGTLRKXLиGGжE GPEWW animal name Zɧ age PɧXLYШGXɴRL %XXVMFYXI GжEGPEWW 4LRKXLиG __init__(self) PɧLɧQXϰSGжEGPEWW ,ɧQRɧ]WЌчвGKМMQЦMOLMGɹQШXSFNIGXQЪMчвG XϰS XкQШXGPEWW KМMPɧUYɨXVɳRLXϰSMRWXERGI show() run() Zɧ go() PɧTLRKXLиGGжEGPEWW /LMOLEMFɨSTLRKXLиGGɹOɯQXLEQWР self HɽRK чВXVY]GϼTRKвGPϰMSFNIGXчERKKМM0ɾGKМMTLRK XLиGXLɳOLɺRKG϶RXVY]АRXLEQWРRɧ] 4LRKXLиG run() GжEGPEWW dog KМMPɧ override GжETLRKXLиG run() GжEGPEWW animal 'LRK8LESXɨGXVɱRXϼTXMR Zɧ8LQдG 2ШMHYRKGLRKRɧ]WЌLЪRKHϺRGɨGXLESXɨGPMɱRUYER чЎRXϼTXMRZɧXLQдG 8ϼTXMR *MPI 1ЮJMPI 8VЪGOLMQYРRчМGLSІGKLMJMPIFϰRG϶RGɹXLESXɨGQЮ JMPIXLISGɾTLɨT fh = open(filepath, mode) 8VSRKчɹ filepath PɧчЬRKHϺRGжEJMPIWЌQЮZɧ mode PɧGLЎчШчВQЮ'ɹQШXWРGLЎчШPɧ r QЮчВчМGRШMHYRK QІGчКRL w QЮчВKLMRШMHYRK a QЮчВKLMXLɱQRШMHYRKZɧSGYРMJMPI r+ QЮчВчМGZɧKLM'SRXVОRЀQЮч϶YJMPI w+ QЮчВчМGZɧKLM+LMчɯRЎYJMPIчɪXТRXϰMRЎY JMPIGLEXТRXϰMXLɳXϰSJMPIQЪMчВKLM a+ QЮчВчМGZɧXLɱQZɧSGYРMJMPI'SRXVОRЀQЮ GYРMJMPI2ЎYJMPIGLEXТRXϰMXLɳXϰSJMPIQЪMчВKLM 1ІGчКRLPɧQЮJMPIXI\XRЎYQYРRQЮJMPIRLКTLɩR FMREV] XLɳXLɱQ b ZɴHд rb wb ab rb+ wb+ ab+ :ɴHд f1 = open('test.txt', 'r') f2 = open('access_log', 'a+' 7EYOLMKМMLɧQ open() XLɧRLGɺRKXLɳWЌXVϲZАQШX SFNIGXGɹGɨGXLYШGXɴRL closed 8VYIRЎYJMPIчɪчɹRK mode GLЎчШOLMQЮJMPI name XɱRGжEJMPI softspace GЬчɨRLHϴYWSJXWTEGIOLMHɽRKZЪMLɧQ print ɇМGRШMHYRKXкJMPI 7EYOLMJMPIчɪQЮЮGLЎчШчМGXLɳKМMTLRKXLиG read([count]) чВXVϲZАXSɧRFШRШMHYRKGжEJMPI:ɴHд f1 = open('test.txt', 'r') data = f1.read(); ,ɧQ read() GɹRLϼRQШXXLEQWРPɧWРPвRKF]XIQYРR чМG2ЎYOLɺRKXVY]АRZɧSXLɳWЌчМGLЎXRШMHYRKGжEJMPI :ɴHд f2 = open('log.txt', 'r') buffdata = f2.read(1024) +LMRШMHYRKZɧSJMPI 2ЎYJMPIчвGQЮЮGLЎчШGɹXLВKLMXLɳGɹXLВHɽRK TLRKXLиG write() чВKLMQШXRШMHYRKZɧSJMPI:ɴHд f2 = open('access_log', 'a+') f2.write('Attack detected') ɇɹRKJMPIчɪQЮ 7EYOLMLSɧRXϴXGɨGXLESXɨGчМGKLMJMPIXLɳKМMTLRK XLиG close() чВчɹRKJMPIчɪQЮ:ɴHд f1.close() f2.close() ɇФMXɱRJMPI 7мHдRKTLRKXLиG os.rename(old, new) чВчФMXɱR QШXJMPI:ɴHд import os os.rename('test.txt', 'test_new.txt') <ɹEJMPI 7мHдRKTLRKXLиG os.remove(file) чВ\ɹEQШXJMPI OLОMLЖXLРRK:ɴHд import os os.remove('test.txt') 8LQдG (MVIGXSV] 8ϰSXLQдG 7мHдRKTLRKXLиG os.mkdir(dir) чВXϰSXLQдG:ɴ Hд import os os.mkdir('test') <ɹEXLQдG 7мHдRKTLRKXLиG os.rmdir(dir) чВ\ɹEQШXXLQдG :ɴHд import os os.rmdir('test') ɇМGRШMHYRKXLQдG 7мHдRKTLRKXLиG os.listdir(dir) чВPϴ]HERLWɨGL XϼTXMRXLQдGGжEXLQдG dir /LMKМMWЌXVϲZАQШX QϲRKHERLWɨGLGɨGXϼTXMRXLQдG:ɴHд import os allfiles = os.listdir('/root/downloads') print allfiles 1SHYPI os 1SHYPI os PɧQШXQSHYPIGɹRLMАYTLRKXLиGLоYɴGL XVSRKZMЖGPɧQZMЖGZЪMGɨGJMPIZɧHMVIGXSV]RL os.chdir(path) чФMXLQдGLMЖRLɧRL os.getcwd() XVϲZАXLQдGLMЖRLɧRL os.chmod(path, mode) ',13(QШXчЬRKHϺR os.chown(path, uid, gid) ',3;2QШXчЬRKHϺR os.makedirs(path[, mode]) XϰSчЬRKHϺR Gɹ VIGYVWMZI os.removedirs(path) \ɹEQШXчЬRKHϺR Gɹ VIGYVWMZI <IQXLɱQXϰMLXXTWHSGWT]XLSRSVKPMFVEV]SWLXQP 1SHYPI os.path 1SHYPI os.path LЦXVвGɨGTLRKXLиGKMɾTXLESXɨG RLERLGLɹRKZɧXLYϼRXMЖRLRXVɱRчЬRKHϺR os.path.exists(path) OMВQXVEчЬRKHϺRGɹXТR XϰMLE]OLɺRK os.path.getsize(path) Pϴ]JMPIWM^I F]XI os.path.isfile(path) OMВQXVE\IQGɹTLϲMPɧQШX JMPIXLɺRKXLЬRK os.path.isdir(path) OMВQXVE\IQGɹTLϲMPɧQШX XLQдG os.path.dirname(path) XVϲZАXɱRXLQдGGжETEXL os.path.getatime(path) XVϲZАXLЬMKMERXVY]GϼT QЪMRLϴX os.path.getmtime(path) XVϲZАXLЬMKMERGLИRLWмE GYРMGɽRK os.path.getctime(path) XVϲZАXLЬMKMERGLИRLWмE GYРMGжEQIXEHEXEXVɱRQШXWРLЖXLРRK,SІGXVϲZА XLЬMKMERXϰSJMPIXVɱR;MRHS[W <IQXLɱQXϰM LXXTWHSGWT]XLSRSVKPMFVEV]SWTEXLLXQP 'LRK<мPʁLɳRLϲRL 7мHдRKXLZMЖR4MPPS[ 4-0*SVO чВXMЎRLɧRLGɨGXLES XɨG\мPʁLɳRLϲRLчRKMϲRRLVIWM^IGVSTVSXEXIŷ 'ɧMчІX4-0 :ɧSXVERK[IFWEYчВHS[RPSEHGɧMчІXTEGOEKI4-0GLS T]XLSRGжEFϰR LXXTTMPPS[VIEHXLIHSGWSVKIRPEXIWXMRWXEPPEXMSRLXQP 7EYOLMGɧMчІXXLɳGɹXLВWмHдRKGɨGQSHYPIXVSRK TEGOEKI-40 from PIL import Image 1ЮJMPI from PIL import Image im = Image.open("photo.jpg") 7EYOLMQЮJMPILɳRLXLɧRLGɺRKXLɳGɹXLВXLESXɨGXVɱRчРM XвRK im +LMJMPI 8кчРMXвRK Image GɹXLВPYJMPI\YРRKQɨ]XɴRLFЀRK TLRKXLиG save(path, type) :ɴHд ... im.save('photo_new.jpg', 'JPEG') 8ϰSXLYQFREMP 7мHдRKTLRKXLиG thumbnail RLWEY from PIL import Image im = Image.open('photo.jpg') im.thumbnail((100, 100)) im.save('photo_thumbnail.jpg', 'JPEG') thumbnail OLɺRKXVϲZАMQEKIQЪMQɧXLрGLMЖRXVɱR SFNIGXMQEKIчERKKМM 'ɨGXLESXɨG\мPʁLɳRLϲRL 8LEQOLϲSXLɱQXLZMЖR4-0XϰM LXXTTMPPS[VIEHXLIHSGWSVKIRPEXIWXMRHI\LXQP 'LRK<мPʁJMPI.732 .732PɧQШXXVSRKRLоRKчКRLHϰRKJMPIXVESчФMHоPMЖY XLɺRKHдRKRLϴXLMЖRRE]:ЪMOMЎRXVɾGчRKMϲRZɧXRK чТRKZЪMGϴYXVɾGGжE4]XLSRRɱRZMЖGXLESXɨG.732XVɱR 4]XLSRVϴXHДLMВY 0SEHJMPIXк-RXIVRIX 8LɺRKXLЬRKHоPMЖY.732чвGPϴ]XкRKYТROLɨG RL JMPIMRXIVRIX RɱRGLRKRɧ]WЌFϾXч϶YFЀRKGɨGL LЪRKHϺRHS[RPSEHQШXJMPI.732Xк-RXIVRIXZɧWEYчɹ QЪMTEVWMRKRШMHYRK.732HS[RPSEH 7мHдRKQSHYPI urllib2 чВHS[RPSEHJMPIZɧQSHYPI json чВIRGSHIHIGSHI.732HEXE:ɴHд import urllib2 import json response = urllib2.urlopen('https://api.github.com/ users/voduytuan/repos') data = json.load(response) print data :ɴHдXVɱRWЌXVY]ZϴRчЬRKHϺR LXXTWETMKMXLYFGSQYWIVWZSHY]XYERVITSWчВPϴ]HERL WɨGL6ITSWMXSV]XVɱR+MXLYFGжEQɳRLHЪMчКRLHϰRK .7327EYчɹWЌчвG 4EVWMRK.732(EXE 2ЎYRLFϰRчɪGɹ.732HEXEHЪMHϰRKGLYЦMQYРR TEVWMRKGLYЦMRɧ]XLɧRL(EXEXLɳWмHдRKRLGɨGLHЪM чɩ] import json mystring = '{"a":1,"b":2,"c":3,"d":4,"e":5}' data = json.loads(mystring) print data (HiӅn thӍ: {u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd ': 4}) )RGSHMRK.732(EXE 2ЎYRLFϰRчɪGɹQШXFMЎRZɧQYРRIRGSHIXLɧRL.732 WXVMRKXLɳGɹXLВHɽRKXLISGɨGLWEY import json mydata = { 'name': 'John', 'age': 10 } jsonstring = json.dumps(mydata) print jsonstring (hiӅn thӍ: {"age": 10, "name": "John"}) 'LRK<мPʁJMPI<10 8VSRKTL϶RRɧ]GLɾRKXEWЌTEVWMRKRШMHYRK<10XLɧRL HоPMЖYчВ\мPʁɇВ\мPʁ<10XEWЌWмHдRKXLZMЖR &IEYXMJYPWSYTɇɩ]PɧQШXXLZMЖRKMɾTZMЖGXVMВROLEM ZMЖGTEVWMRKLXQP\QPчвGRLERLGLɹRKZɧXMЖRPвM 'ɧMчІX&IEYXMJYPWSYT &ϰRGɹXLВXLEQOLϲSLЪRKHϺRGɨGLGɧMчІXXϰM[IFWMXI LXXT[[[GVYQQ]GSQWSJX[EVI&IEYXMJYP7SYTFWHSGMRW FIEYXMJYPWSYT 8VɱR1EG37GɹXLВGɧMFЀRK pip RLWEY $ sudo pip install beautifulsoup4 'ɧMчІX lxml TEVWIV ɇВTEVWMRK xml XкFIEYXMJYPWSYTXESWмHдRKFШTEVWIV \QPGɹXɱRPɧ lxml <IQLЪRKHϺRGɧMчІXXϰM LXXT[[[GVYQQ]GSQWSJX[EVI&IEYXMJYP7SYTFWHSGMRW ETEVWIV 8VɱR1EG37GɹXLВGɧMFЀRK pip RLWEY sudo pip install lxml :ɴHдZАTEVWMRK<10 'LSZɴHдWEY from bs4 import BeautifulSoup as Soup note = ''' <?xml version="1.0" encoding="UTF-8"?> <breakfast_menu> <food> <name>Belgian Waffles</name> <price>$5.95</price> <description>Two of our famous Belgian Waff les with plenty of real maple syrup</description> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name> <name>Strawberry Belgian Waffles</name> <price>$7.95</price> <description>Light Belgian waffles covered with strawberries and whipped cream</description> <calories>900</calories> </food> </breakfast_menu> ''' soup = Soup(note, 'xml') foods = soup.findAll('food') for x in foods: print x.find('name').string, ': ', x.price.stri ng /LMGLϰ]XLɳWЌLMВRXLКVEQɧRLɳRLRLWEY Belgian Waffles : $5.95 Strawberry Belgian Waffles : $7.95 ɇРMXвRKXLYШGGPEWW Soup &IEYXMJYP7SYT WЌKMɾTXVY] \YϴXGɨGXLɧRLTL϶RGжEJMPI\QPRLERLGLɹRKZɧXMЖRPвM 8VSRKZɴHдGɹQШXWРGɨGLXVY]\YϴXчЎRGɨGTL϶RXмRL findAll() XVϲZАQϲRKGɨGXLЊGɹXɱRG϶RXɳQ find() XVϲZАTL϶RXмч϶YXMɱRGɹXɱRG϶RXɳQ 8VY]\YϴXXVрGXMЎTXLɺRKUYEXɱRXLЊRL x.price.string 4EVWMRK,810 8RKXрRL xml &IEYXMJYP7SYTGɹXLВTEVWMRKRШMHYRK ,810XLɺRKUYELɧQOLЮMXϰSZɧGLМR html ЮXLEQWР XLи ... soup = Soup(websitehtml, 'html') 'LRK/ЎXRРM1]750 1]750PɧQШXLЖGWЮHоPMЖYUYERLЖTLФFMЎRRLϴXLMЖR RE]6ϴXRLMАYRKɺRRKоGɹXLВOЎXRРMчЎR1]750Zɧ 4]XLSRGˢRKOLɺRKRKSϰMPЖ 1ІGчКRL4]XLSROLɺRKGɹXLZMЖRчВOЎXRРMчЎR1]750 WIVZIV8VSRKTL϶RRɧ]чВOЎXRРMчЎR1]7507IVZIVXк 4]XLSRGLɾRKXEWЌWмHдRKQSHYPI MySQLdb 'ɧMчІX1]750HF 'ɧMчІXXLɺRKUYE pip RLWEY $ sudo pip install MySQL-python 8LEQOLϲSXLɱQXϰMLXXTWT]TMT]XLSRSVKT]TM1]750 T]XLSR /LEMFɨSQSHYPI1]750HFPɧGɹXLВWмHдRK import MySQLdb 8VSRKQШXWРXVЬRKLвTчɪGɧM1]750HFRLRKMQTSVX FɨSPЦMXLMЎYJMPI libmysqlclient.18.dylib 2KY]ɱRRLɩR GɹXLВPɧHSLMЖRXϰMчЬRKHϺRчЎRJMPIOLɺRKXТRXϰM8Lм XϰSW]QPMROLSІGWмHдRKGɩYPЖRLWEYчВXϰSW]QPMROXк JMPI libmysqlclient.18.dylib чЎRXLQдG /usr/lib/ $ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18 .dylib /usr/lib/libmysqlclient.18.dylib /ЎXRРMчЎR1]7507IVZIV &ϰRG϶RGɹQШX1]750WIVZIVчERKGLϰ]ZɧGLSOЎXRРM чЎR8VSRKXVЬRKLвTRɧ]PɧPSGEPLSWXRɱROLɺRKG϶RGϴY LɳRLчІGFMЖXGLИG϶RGYRKGϴTYWIVREQIZɧTEWW[SVHPɧ GɹXLВOЎXRРMчЎR1]7507IVZIV 8LрGLMЖRKМMLɧQRLWEYчВXVϲZАOЎXRРM import MySQLdb dbcon = MySQLdb.connect(host = 'localhost', user = 'myusername', passwd = 'mypassword', db = 'mydbname ') 2ЎYOЎXRРMOLɺRKXLɧRLGɺRKXLɳWЌFɨSPЦMZɧRKRK GLRKXVɳRL'ɨGLOЎXRРMERXSɧRPɧчEZɧSXVSRK try чВFϾXPЦMRLWEY import MySQLdb db = None try: db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = 'root', db = 'mysql') except MySQLdb.Error, e: print "Error %d: %s" % (e.args[0],e.args[1]) sys.exit(1) if db: cur = db.cursor() cur.execute("SELECT VERSION()") ver = cur.fetchone() print "Database version : %s " % ver /ЎXRРMZЪM charset utf8 1ІGчКRLOЎXRРMчЎR1]750WIVZIVPɧGLEVWIX latin RɱR OLMPϴ]HоPMЖYYRMGSHIXLɳLMВRXLК8MЎRK:MЖXOLɺRKчɾRK FϰRG϶RTLϲMGLМRGLEVWIXPɧ utf8 OLMXϰSOЎXRРM'ɾTLɨT RLWEY ... db = MySQLdb.connect(host = 'localhost', user = 'ro ot', passwd = 'root', db = 'test', charset = 'utf8' ) 5YIV]HоPMЖY ɇВXVY]ZϴRHоPMЖY GLϰ]GɩYPЖRL750 XLɳWмHдRK cursor GжE1]750HF:ɴHд import MySQLdb db = MySQLdb.connect(host = 'localhost', user = 'ro ot', passwd = 'root', db = 'mysql'); cursor = db.cursor() sql = 'SELECT * FROM user' cursor.execute(sql) myusers = cursor.fetchall() :ɴHдHоPMЖYFMЎR myusers Pɧ ((1, 'John'), (2, 'Doe')) 1ІGчКRL cursor WЌXVϲZАQЦMHɸRKHоPMЖYXк1]750 XLISOMВY tuple XиGPɧOLɺRKGɹOI]2ЎYFϰRQYРRXVϲZА OMВY Dictionary XLɳGɹXLВOLEMFɨS import MySQLdb db = MySQLdb.connect(host = 'localhost', user = 'ro ot', passwd = 'root', db = 'mysql') cursor = db.cursor(MySQLdb.cursors.DictCursor) ... *IXGLHоPMЖY 'ɹQШXWРGɨGLчВJIXGLHоPMЖYXLɺRKHдRKXк cursor WEY OLMчɪ exectute(sql) Pɧ fetchone() Zɧ fetchall() fetchone() GLИJIXGLQШXHɸRKHоPMЖY2ЎYQYРR JIXGLRLMАYHɸRKHоPMЖYXLɳGɹXLВKМMRLMАYP϶RQЦM P϶RWЌXVϲZАQШXHɸRKHоPMЖY8РXGLSXVЬRKLвTXVY] ZϴRVϴXRLMАYHоPMЖYQШXPɾG2ЎYXVϲZА None XиGPɧ чɪJIXGLLЎXHоPMЖYXкGɩYXVY]ZϴR fetchall() JIXGLXSɧRFШHоPMЖYXVY]ZϴRчвGXк GɩYXVY]ZϴRZɧXVϲZАQШXXYTPIGLиEGɨGHɸRKHо PMЖY1ЦMTL϶RXмGжE8YTPIGɹXLВPɧQШX8YTPIOLɨG LSІGPɧQШX(MGXMSREV]Xɽ]XLISGɧMчІXЮFЪGPϴ] GYVWSV <IQTL϶R fetchmany(size) RЀQЮKMоEOMВYJIXGLXVɱRGɹXLВ UY]чКRLWРPвRKVS[XVSRKQЦMP϶RJIXGL2ЎYJIXGL LЎXXLɳXVϲZА8YTPIVЦRK ɇɹRKOЎXRРM 7EYOLMOЎXRРMZɧXVY]ZϴRXLɳGɹXLВчɹRKOЎXRРMXLISZɴ HдWEY import MySQLdb db = MySQLdb.connect(...) db.close() 2KSɧMVEFϰRGˢRKRɱRчɹRK cursor OLMOLɺRKGɸRWм HдRKXLISZɴHд import MySQLdb db = MySQLdb.connect(...) cursor = db.cursor() cursor.close() db.close() 4VITEVIH7XEXIQIRX 4VITEVIHWXEXIQIRXPɧOцXLYϼXXLEQWРLɹEGɨGHоPMЖY XVY]АRZɧSGɩYXVY]ZϴRXLE]ZɳRРMGLYЦMXVрGXMЎTчВ\ɩ] HрRKQШXGLYЦMXVY]ZϴRHɧM/цXLYϼXRɧ]чвGɨTHдRK RLMАYZɧKMɾTXʆRKLMЖYUYϲZɧXɴRLFϲSQϼXGжEGɩYXVY] ZϴR:ɴHд ... cur.execute("UPDATE Writers SET Name = %s WHERE Id = %s", ("John", "4")) ... 1ЦMXLEQWРXVY]ZϴRWЌчвGXLE]XLЎFЀRK %s ZɧTLRK XLиG execute() WЌGɹXLEQWРXLиPɧQШX8YTPIGɹKMɨXVК XRKиRKZЪMXLиXр\YϴXLMЖRGжEGɨGXLɧRLTL϶R %s 'LRK/ЎXRРM6IHMW 6IHMWPɧQШXQIQSV]GEGLIWIVZIVLЦXVвTIVWMWXERXHEXE XLɺRKHдRKRLϴXLMЖRRE]2ШMHYRKGLRKRɧ]WЌLЪRK HϺRFϰROЎXRРMчЎRQШX6IHMWWIVZIV чɪчвGGɧMчІX WЄR XLɺRKUYEXLZMЖRVIHMWT] 'ɧMчІX 'ɹXLВ\IQXLɱQZАLЪRKHϺRGɧMчІXXLZMЖRRɧ]XϰM LXXTWKMXLYFGSQERH]QGGYVH]VIHMWT] ɇRKMϲRGɧMXLɺRKUYE pip Pɧ $ sudo pip install redis /ЎXRРMчЎR6IHMW ɇВOЎXRРMчЎR6IHMWWIVZIVXLɳFϰRGɹXLВ\IQZɴHдWEY import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) 8LрGLMЖRPЖRL 8LрGLMЖRGɨGPЖRLFɳRLXLЬRKXVɱRчРMXвRKVIHMW:ɴHд import redis r = redis.StrictRedis(...) r.set('foo', 'bar') print r.get('foo') (HiӅn thӍ 'bar') 4MTIPMRI 4MTIPMRIPɧOцXLYϼXчвGHɽRKXVSRKXVЬRKLвTFϰRQYРR XʆRKTIVJSVQERGIFЮMKШTRLMАYPЖRLZɧSQШXVIUYIWXXLE] ZɳQЦMPЖRLPɧQШXVIUYIWXRLXLɺRKXLЬRK<IQZɴHд WEYчВLMВYGɨGLWмHдRKTMTIPMRIFЀRK redis-py import redis r = redis.StrictRedis(...) r.set('foo', 'bar') pipe = r.pipeline() pipe.set('a', 1) pipe.set('b', 2) pipe.set('c', 3) pipe.get('foo') pipe.execute() 7EYOLMKМMTLRKXLиG execute() XLɳWЌXVϲZА0MWXXRK иRKZЪMGɨGOЎXUYϲGжEXкRKPЖRL:ɴHдOЎXUYϲXкчSϰR GSHIXVɱR [True, True, True, 'bar'] 'LRK/ЎXRРM 1IQGEGLIH 1IQGEGLIHPɧQШXQIQSV]GEGLIWIVZIVXLɺRKHдRKLMЖR RE]2ШMHYRKGLRKRɧ]WЌLЪRKHϺRFϰROЎXRРMчЎR QШX1IQGEGLIHWIVZIV чɪчвGGɧMчІXWЄR XLɺRKUYE XLZMЖR pylibmc 'ɧMчІX 'ɹXLВ\IQXLɱQZАLЪRKHϺRGɧMчІXXLZMЖRRɧ]XϰM LXXTWIRHETEXGLWITVSNIGXWT]PMFQGMRWXEPPLXQP ɇRKMϲRGɧMXLɺRKUYE pip Pɧ $ sudo pip install pylibmc /ЎXRРMчЎR1IQGEGLIH7IVZIV ɇВOЎXRРMчЎR1IQGEGLIHWIVZIVXLɳFϰRGɹXLВ\IQZɴHд WEY import pylibmc mc = pylibmc.Client(["127.0.0.1"], binary=True, beh aviors={"tcp_nodelay": True, "ketama": True}) 8LрGLMЖRPЖRL 8LрGLMЖRGɨGPЖRLFɳRLXLЬRKXVɱRчРMXвRKQIQGEGLI :ɴHд import pylibmc mc = pylibmc.Client(...) mc.set('foo', 'bar') print mc.get('foo') (HiӅn thӍ 'bar') 'LRK/ЎXRРM6EFFMX15 6EFFMX15PɧQШXTL϶RQАQGLSTLɰT\ɩ]HрRK1IWWEKI 5YIYIXLISTVSXSGSP%154ZɧOLɨXLɺRKHдRKXVɱRXLЎ KMЪMɇВOЎXRРMчЎR6EFFMX15XVɱR4]XLSRXEWЌWмHдRK XLZMЖR pika 'ɧMчІX 'ɹXLВ\IQXLɱQZАLЪRKHϺRGɧMчІXXLZMЖRRɧ]XϰM LXXTWTMOEVIEHXLIHSGWSVKIR ɇRKMϲRGɧMXLɺRKUYE pip Pɧ $ sudo pip install pika +ЮMQШXQIWWEKIчЎR7IVZIV 4VSZMHIV :ɴHдчВKЮMQШXQIWWEKIчЎRWIVZIV import pika connection = pika.BlockingConnection(pika.Connectio nParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hel lo', body='Hello World!') print " [x] Sent 'Hello World!'" connection.close() ɇВKЮMQШXQIWWEKIGLɾRKXEG϶ROЎXRРMчЎRWIVZIVZɧ OLEMFɨSQШXGLERRIPЮчɩ]PɧGLERRIPGɹXɱRPɧ hello 7EYOLMOLEMFɨSGLERRIPXESXMЎRLɧRLKЮMQIWWEKIGɹ RШMHYRK Hello World! XLɺRKUYEGLERRIPRɧ]OɯQXLIS OLEMFɨS routing_key Pɧ hello 6SYXMRK/I]WЌKMɾTчMАY LЪRKQIWWEKIRɧ]чЎRчɾRKGɨG[SVOIVчвGOLEMFɨS RLϼRQIWWEKIXLISVSYXMRKOI] 'SRWYQIV 2LϼRQIWWEKI'SRWYQIV ЭFЪGXVЪGXEчɪXϰSQШXQIWWEKIPɱRUYIYIЭFЪG Rɧ]XEWЌOLEMFɨSQШX[SVOIV\мPʁGɨGQIWWEKIRLϼR чвGXкGLERRIP hello import pika connection = pika.BlockingConnection(pika.Connectio nParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='hello') print ' [*] Waiting for messages. To exit press CTR L+C' def callback(ch, method, properties, body): print " [x] Received %r" % (body,) channel.basic_consume(callback, queue='hello', no_a ck=True) channel.start_consuming() ɇSϰRGSHIRɧ]GˢRKGɹTL϶ROLEMFɨS connection channel 8Y]RLMɱRZɳPɧGSRWYQIVRɱRWЌWмHдRK TLRKXLиG basic_consume чВPϾRKRKLIXVɱRUYIYI hello OLMGɹQIWWEKIчЎRWЌKМMLɧQ callback() чВ\м Pʁ8VSRKXVЬRKLвTZɴHдRɧ]XLɳGEPPFEGOGLИчRKMϲRPɧ LMВRXLКGLYЦMXLɺRKFɨSчɪRLϼRчвGQIWWEKI 8ɳQLMВYXLɱQZА6EFFMX15Zɧ4MOE 2ШMHYRKGLRKRɧ]OLɺRKGɹʁчКRLKMЪMXLMЖYXϴXGϲOLɨM RMЖQGжE%154GˢRKRL6EFFMX15QɧGLж]ЎYKMЪMXLMЖY XLZMЖR pika чВPɧQZMЖGZЪM6EFFMX15&ϰRGɹXLВXMЎT XдGXLISHɻMGɨGLЪRKHϺRZАOLɨMRMЖQGжE6EFFMX15Zɧ 4MOEXϰM[IFWMXIGLɴRLXLиGGжE6EFFMX15 LXXTW[[[VEFFMXQUGSQXYXSVMEPWXYXSVMEPSRI T]XLSRLXQP 'LRK6IWXJYPGPMIRX 2Kɧ]RE]ZЪMWрTLSRKTLɾGжEGɨGиRKHдRKZɧRLYG϶Y OЎXRРMRKɧ]GɧRKPЪRXLɳ6IWXJYPPɧQШXXVSRKRLоRKQɺ LɳRL[IFWIVZMGIчвGRLMАYGɺRKX]WмHдRK(SчɹZMЖG GɹXLВOЎXRРMчЎRGɨG6IWXJYP[IFWIVZMGIPɧQШXOцRʆRK G϶RXLMЎXGLSGɨGPϼTXVɳRLZMɱR 'LRKRɧ]WЌKMЪMXLMЖYZАQШXXVSRKRLоRKXLZMЖRRФM XMЎRKRLϴXXVSRK4]XLSRчВPɧQZMЖGZЪMGɨG6IWXJYP[IF WIVZMGIчɹPɧ requests ;IFWMXIGLɴRLXLиGZɧGɨGQɺXϲч϶]чжчАYчвGчАGϼT XϰMLXXT[[[T]XLSRVIUYIWXWSVK 'ɧMчІX 'ɧMчІXRLERLGLɹRKXLɺRKUYE pip RLWEY $ sudo pip install requests 6IUYIWX ,ЦXVвWЄRGɨGTLRKXLиGXRKиRKGLS,XXTVIUYIWX RL+)84378498()0)8)ŷ import requests r = requests.get('https://api.github.com/events') r = requests.post("http://httpbin.org/post") r = requests.put("http://httpbin.org/put") r = requests.delete("http://httpbin.org/delete") r = requests.head("http://httpbin.org/get") r = requests.options("http://httpbin.org/get") +)85YIV]WXVMRK ɇРMZЪMGɨGVIUYIWX GET GɹXLВXVY]АRXLEQWРчЬRKHϺR XLɺRKUYEXLEQWР params OLMKМMTLRKXLиG get() :ɴ Hд import requests payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("http://httpbin.org/get", params = payload) print(r.url) (HiӅn thӍ: http://httpbin.org/get?key2=value2&key1= value1) 6IUYIWX&SH] 8VSRKL϶YLЎXXVЬRKLвTGɨGVIUYIWXRL4378498 XLRKG϶RXVY]АRHоPMЖYOLMVIUYIWXGɹXLВWмHдRKXLEQ WР data чВXVY]АRHEXEPɱROɯQVIUYIWX:ɴHд import requests payload = {'key1': 'value1', 'key2': 'value2'} r = requests.post("http://httpbin.org/post", data = payload) 9TPSEHJMPI 'ɹXLВKЮMXLɱQXLEQWР files чВYTPSEHJMPIOɯQXLIS VIUYIWX:ɴHд import requests url = 'http://httpbin.org/post' files = {'file': open('report.xls', 'rb')} r = requests.post(url, files=files) 6IWTSRWI 7EYOLMKМMGɨGTLRKXLиGXRKиRKчВVIUYIWXFϰRWЌ GɹчРMXвRKXLYШGGPEWW Response ɇРMXвRKRɧ]GɹQШX WРXLɺRKXMRRLWEY status_code ,8847XEXYWWIVZIVXVϲZА headers 'ɨGXLɺRKXMRLIEHIVQɧWIVZIVXVϲZАHЪM HϰRK(MGXMSREV] cookies 2ЎYWIVZIVGɹXVϲZАGSSOMIXLɳGɹXLВWм HдRKXLYШGXɴRLRɧ]чВPϴ]GɨGGSSOMI text 8VϲZАRШMHYRKVIWTSRWI 8LEQOLϲSZАGɨGXɴRLRʆRKOLɨGGжEXLZMЖR requests XϰM[IFWMXIGLɴRLXLиGLXXTHSGWT]XLSRVIUYIWXWSVK 'LRK+ЮMIQEMPZЪM7184 7184PɧKMESXLиGKЮMQEMPXLɺRKHдRKLMЖRRE]4]XLSRLЦ XVвQІGчКRLXLZMЖR smtplib HɽRKчВOЎXRРMчЎRQШX 71847IVZIVZɧKЮMIQEMP8Y]RLMɱRZMЖGWмHдRKXL ZMЖRRɧ]WЌKɩ]OLɹOLʆRGLSZMЖGчКRLHϰRKZɧWмHдRK RɱRGLɾRKXEWЌWмHдRKXLZMЖR sender PɧQШXXLZMЖR KMɾTчКRLHϰRKZɧKЮMIQEMPчRKMϲRLR 'ɧMчІX sender 'ɧMчІXXк pip RLWEY $ sudo pip install sender +ЮMIQEMPчRKMϲR ɇВKЮMIQEMPZЪM sender FϰRG϶RGɹXɧMOLSϲRZɧQШXWР XLɺRKXMRGжE71847IVZIVXVЪGOLMKЮM:ɴHдчSϰRGSHI чВKЮMIQEMPXк71847IVZIVGжE%QE^SR from sender import Mail, Message mail = Mail( "smtp.gmail.com", port = 465, username = "example@gmail.com", password = "yourpassword", use_tls = False, use_ssl = True, debug_level = False ) msg = Message("msg subject") msg.fromaddr = ("Vo Duy Tuan", "example@gmail.com") msg.to = "destuser@gmail.com" msg.body = "this is a msg plain text body" msg.html = "<b>this is a msg text body</b>" msg.reply_to = "example@gmail.com" msg.charset = "utf-8" msg.extra_headers = {} msg.mail_options = [] msg.rcpt_options = [] # Send message mail.send(msg) +ЮMIQEMPGɹчɴRLOɯQJMPI &ϰRG϶RWмHдRKXLɱQGPEWW%XXEGLQIRXчВXϰS EXXEGLQIRX from sender import Mail, Message, Attachment mail = Main(...) msg = Message(..) ... # Open attached file and create Attachment object with open("photo01.jpg") as f: file01 = Attachment("photo01.jpg", "image/jpeg" , f.read()) msg.attach(file01) # Send message mail.send(msg) 8ɳQLMВYXLɱQ &ϰRGɹXLВXɳQLMВYXLɱQZАXLZMЖR sender XϰM[IFWMXI GLɴRLXLиGXϰMчКEGLИLXXTWIRHIVVIEHXLIHSGWSVK 'LRK7SGOIX TVSKVEQQMRK 'LRKRɧ]WЌZɴHдZMЖG\ɩ]HрRKQШXQɺMXVЬRK'PMIRX 7IVZIVWмHдRK7SGOIX7IVZIVWЌPϾRKRKLIXVɱRQШXTSVX ZɧOLMGPMIRXOЎXRРMZɧSWЌXLɺRKFɨSLMВRXLК XLɺRKXMRGжEGPMIRX -4Zɧ4SVX ZɧKЮMQIWWEKI\YРRK GLSGPMIRX 7IVZIVWMHI 8ϰSJMPI server.py ZЪMRШMHYRKFɱRHЪM import socket s = socket.socket() host = socket.gethostname() port = 12345 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept() print 'Got connection from', addr c.send('Thank you for connecting') c.close() ɇSϰRGSHIXVɱROLMXLрGXLMWЌGLϰ]ZɧPϾRKRKLIЮTSVX 8'41ЦMOLMGɹQШXOЎXRРMXкGPMIRXWЌLMЖRVE XLɺRKFɨSOЎXRРMXк-4Zɧ4SVXRɧSZɴHд Got connection from Got connection from ('192.168.1.104', 60018) 7EYчɹKЮMXVϲQШXQIWWEKIZЪMRШMHYRK Thank you for connecting ZАGLSGPMIRX7EYчɹчɹRKOЎXRРMZЪMGPMIRX 'PMIRXWMHI 8ϰSJMPI client.py ZЪMRШMHYRKFɱRHЪM import socket s = socket.socket() host = '127.0.0.1' port = 12345 s.connect((host, port)) print s.recv(1024) s.close ɇSϰRGSHIXVɱRWЌOЎXRРMчЎRQШXWSGOIXWIVZIVXLɺRK UYELSWXREQIPϴ]чвGXкTLRKXLиG socket.gethostname() ZɧTSVX7EYOLMOЎXRРMWЌ LMВRXLКVEOЎXUYϲXVϲZАXкWIVZIV7EYчɹXLɳчɹRKOЎXRРM 8ɨGKMϲ 8ɱR:ɻ(Y]8YϴR )QEMPXYERQEWXIV$KQEMPGSQ *EGIFSSOLXXTW[[[JEGIFSSOGSQZSHY]XYER