Tailieuhay 247compython Rat La Co Ban Vo Duy Tuan

Download as pdf or txt
Download as pdf or txt
You are on page 1of 93

lOMoARcPSD|35016901

[ Tailieuhay 247.COM]Python rat la co ban - Vo Duy Tuan

Nhập môn lập trình Python cho phân tích (Trường Đại học Sư phạm Kỹ Thuật Thành
phố Hồ Chí Minh)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Duong Tran Huu ([email protected])
lOMoARcPSD|35016901

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

+MЪMXLMЖY
,MЖRRE]4]XLSRPɧQШXXVSRKRLоRKRKɺRRKоPϼTXVɳRL
чERKчšвGGLɾʁFЮMXɴRLчEHϰRKZАиRKHдRKXLšZMЖ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РMšYчšв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ɨRG˜Fϲ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ɧQGLš˜RKQЦMGLš˜RKWЌXVɳRLFɧ]
OLɴEGϰRLGжE4]XLSRQɧQɳRLWЌKІTTLϲMZɧWЌLоYɴGL

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

OLMFMЎXGɨGOMЎRXLиGRɧ]XVSRKZMЖGɨTHдRK4]XLSRZɧS
GɺRKZMЖGXVSRKXš˜RKPEM

 ,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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

8ɨGKMϲ
8ɱR:ɻ(Y]8YϴR
)QEMPXYERQEWXIV$KQEMPGSQ
*EGIFSSOLXXTW[[[JEGIFSSOGSQZSHY]XYER

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK,IPPS[SVPH
4]XLSRPɧQШXRKɺRRKоTLMɱRHКGL -RXIVTVIXIV0ERKYEKI 
XиGPɧOLɺRKG϶RFYMPHXLɧRLJMPIXLрGXLMQɧGLϰ]XVрGXMЎT
RLš4,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ɧRLRLš1EG37ŷ

ɇВFMЎXPɧLЖXLРRKGжEFϰRчɪGɧM4]XLSRGLšEGɹXLВZɧS
QɧRLɳRLGSQQERHPMRIZɧKɻ

$ python --version

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

2ЎYчɪGɧMчІXT]XLSRXLɳWЌLMВRXLКXLɺRKXMRTLMɱRFϲR
T]XLSR2ЎYFɨSPЦMXLɳчТRKRKLʨEZЪMFϰRGLšEGɧ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ϴTL˜R -()
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'

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

print PɧPЖRLG˜Fϲ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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK'ɾ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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

- TLɰTXVк

* TLɰTRLɩR

/ TLɰTGLME

% TLɰTGLMEPϴ]Hš QSHYPS

&SSPIERZɧ8SɨRXмPSKMG
+MɨXVКчɾRKZɧWEMXš˜RKи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ɰL˜R  <=  Fɰ


L˜RLSІGFЀRK  >  PЪRL˜R  >=  PЪRL˜RLSІGFЀRK  ==
FЀRK  !=  OLɨG чВWSWɨRLKMɨXVК

,ЦXVвHϰRKWSWɨRLOɰTRLš

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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' # F


alse
'good' not in 'this is a greate example' # 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
{ ŷ } RLšGɨGRKɺRRKоOLɨG 4,4.EZEWGVMTX 
-JŷIPMJŷIPWI

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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д

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ɱRRLšWEY

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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
RLšWEY

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д

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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д

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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МMTLš˜RK

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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МMTLš˜RKXLи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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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МMTLš˜RKXLи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ɨGTLš˜RKXLиG
WEY

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ɺRKRLš4,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д

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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\

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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]GLšE,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 

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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

8š˜RKXрRLšGLYЦMXɹXLВXϰSGɨGQϲRKGSRXLɺRKUYE
XSɨRXмPϴ]OLSϲR [start:end]  VERKI 1ІGчКRL start Pɧ

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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д

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ɽRKTLš˜RKXLиG list.append(newvalue) чВXLɱQTL϶R
XмGɹKMɨXVК newvalue ZɧSGYРMQϲRK list :ɴHд

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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дRKTLš˜RKXLи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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

QϲRKGɹXLВHɽRKTLš˜RKXLи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
TLš˜RKXLиG list.reverse() 4Lš˜RKXLиGRɧ]OLɺRKXVϲ
ZАOЎXUYϲQɧXLE]чФMXVрGXMЎTQϲRK list :ɴHд

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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дRKTLš˜RK
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϶R4Lš˜RKXLи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РRKRLšLɧQ


YWSVXXVSRK4,4,ɧQXVϲZАGɨGKMɨXVК 0  -1 Zɧ 1 

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

8YTPI
8YTPIGˢRKPɧQШXGϴYXVɾGQϲRKXš˜RKXрRLšGϴYXVɾG
0MWX1ШXWРчMВQOLɨGRLEYG˜Fϲ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ɨGTLš˜RKXLи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РRK0MWXRLšPɧ
XVY]\YϴXXLISMRHI\VERKIXɳQOMЎQŷ

(MGXMSREV]
(MGXMSREV]GˢRKPɧQШXGϴYXVɾGQϲRKRLšRKGɨGTL϶RXм
FESKТQOI]ZɧZEPYI2ЎYFϰRGɹFMЎX.732XLɳGϴYXVɾG
(MGXMSREV]Xš˜RKXрRLšQШXSFNIGXNWSR1ШX(MGXMSREV]
чšвGOLEMFɨSFЀRKGІTHϴYRKSІG {...} :ɴHд

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ɧQTLš˜RKXLиGXLɺRKHдRK

dict.clear() <ɹEXSɧRFШHоPMЖYFɱRXVSRKчРM

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK4Lɩ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Ў

'Lš˜RKRɧ]WЌKMɾTFϰRXLMЎXOЎGɨGXɴRLRʆRKXLISQɺ
LɳRLGɨGQSHYPIZɧOLMG϶RXLɳWЌKМMJMPIXš˜RKиRKZɧWм
HдRK

'ɨGPSϰMQSHYPIXLšZMЖR
'ɹPSϰMQSHYPIXLšЬRKXLϴ]Pɧ

 :MЎXFЀRK4]XLSRGɹTL϶RQЮVШRKPɧ .py


 'ɨGXLšZMЖRPMɱROЎXчШRKGɹTL϶RQЮVШRKPɧ .dll 
.pyd  .so  .sl ŷ

 '1SHYPIPMɱROЎXZЪMXVɳRLTLMɱRHКGL

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

ɇšЬ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ЎQJMPIQSHYPIXš˜RKиRKXLISXLиXрXLšQдGWEY

 8LšQдGLMЖRLɧRLQɧWGVMTXчERKKМM
 'ɨGXLšQдGXVSRK4=8,324%8, RЎYGɹWIX
 'ɨGXLšQдGGɧMчІXGLYϸRXVɱR0MRY\9RM\

'ɹXLВFMЎXчšвGчšЬRKHϺRQɧQШXQSHYPIчɪчšвGPSEH
FЀRKчSϰRGSHIHšЪMчɩ]

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ɧTLš˜RK
XLиGGжEQШXQSHYPI
ɇВPϴ]чšвGHERLWɨGLGɨGXLYШGXɴRLZɧTLš˜RKXLиGQɧ
QSHYPILЦXVвWмHдRKLɧQ dir(modulename) :ɴHд

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ɧTLš˜RKXLи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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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\EQTPIRLšWEY

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

$ python myexample.py

7EYOLMXLрGLMЖRWЌLMВRXLКPɱRQɧRLɳRLPɧ

Tong hai so la: 3

4EGOEKIQSHYPI
'ɹXLВKSQRLMАYQSHYPI .py ZɧSQШXXLšQдGZɧXɱRXLš
QдGPɧXɱRGжETEGOEKIZɧXϰSQШXJMPI __init__.py XVSRK
XLšQдGRɧ]

2LšZϼ]GϴYXVɾGXLšGжEQШXTEGOEKIWЌRLšWEY

|-- mypack
| |-- __init__.py
| |-- mymodule1.py
| |-- mymodule2.py
|

'ɹXLВWмHдRK mymodule1 XLISGɾTLɨTMQTSVXWEY

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ɾGXLšQдGGɹJMPI __init__.py :ɴHд

import mypack.mysubpack.mysubsubpack.module

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK'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 = ''

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ɨGTLš˜RKXLиGGжE


GPEWW animal 
name Zɧ age PɧXLYШGXɴRL %XXVMFYXI GжEGPEWW
4Lš˜RKXLи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ɧTLš˜RKXLиGGжEGPEWW

/LMOLEMFɨSTLš˜RKXLиGGɹOɯQXLEQWР self HɽRK


чВXVY]GϼTRKšвGPϰMSFNIGXчERKKМM0ɾGKМMTLš˜RK

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

XLиGXLɳOLɺRKG϶RXVY]АRXLEQWРRɧ]
4Lš˜RKXLиG run() GжEGPEWW dog KМMPɧ override
GжETLš˜RKXLиG run() GжEGPEWW animal 

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK8LESXɨGXVɱRXϼTXMR
Zɧ8LšQдG
2ШMHYRKGLš˜RKRɧ]WЌLšЪRKHϺRGɨGXLESXɨGPMɱRUYER
чЎRXϼTXMRZɧXLšQд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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

r+ QЮчВчМGZɧKLM'SRXVОRЀQЮч϶YJMPI

w+ QЮчВчМGZɧKLM+LMчɯRЎYJMPIчɪXТRXϰMRЎY

JMPIGLšEXТRXϰMXLɳXϰSJMPIQЪMчВKLM
a+ QЮчВчМGZɧXLɱQZɧSGYРMJMPI'SRXVОRЀQЮ

GYРMJMPI2ЎYJMPIGLšEXТ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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

print

ɇМGRШMHYRKXкJMPI

7EYOLMJMPIчɪQЮЮGLЎчШчМGXLɳKМMTLš˜RKXLи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
TLš˜RKXLиG write() чВKLMQШXRШMHYRKZɧSJMPI:ɴHд

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

f2 = open('access_log', 'a+')
f2.write('Attack detected')

ɇɹRKJMPIчɪQЮ

7EYOLMLSɧRXϴXGɨGXLESXɨGчМGKLMJMPIXLɳKМMTLš˜RK
XLиG close() чВчɹRKJMPIчɪQЮ:ɴHд

f1.close()
f2.close()

ɇФMXɱRJMPI

7мHдRKTLš˜RKXLиG os.rename(old, new) чВчФMXɱR


QШXJMPI:ɴHд

import os
os.rename('test.txt', 'test_new.txt')

<ɹEJMPI

7мHдRKTLš˜RKXLиG os.remove(file) чВ\ɹEQШXJMPI

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

OLОMLЖXLРRK:ɴHд

import os
os.remove('test.txt')

8LšQдG (MVIGXSV]
8ϰSXLšQдG

7мHдRKTLš˜RKXLиG os.mkdir(dir) чВXϰSXLšQдG:ɴ


Hд

import os
os.mkdir('test')

<ɹEXLšQдG

7мHдRKTLš˜RKXLиG os.rmdir(dir) чВ\ɹEQШXXLšQдG


:ɴHд

import os
os.rmdir('test')

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

ɇМGRШMHYRKXLšQдG

7мHдRKTLš˜RKXLиG os.listdir(dir) чВPϴ]HERLWɨGL


XϼTXMRXLšQдGGжEXLšQдG dir /LMKМMWЌXVϲZАQШX
QϲRKHERLWɨGLGɨGXϼTXMRXLšQдG:ɴHд

import os
allfiles = os.listdir('/root/downloads')
print allfiles

1SHYPI os
1SHYPI os PɧQШXQSHYPIGɹRLMАYTLš˜RKXLиGLоYɴGL
XVSRKZMЖGPɧQZMЖGZЪMGɨGJMPIZɧHMVIGXSV]RLš

os.chdir(path) чФMXLšQдGLMЖRLɧRL

os.getcwd() XVϲZАXLšQд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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

os.removedirs(path) \ɹEQШXчšЬRKHϺR Gɹ
VIGYVWMZI

<IQXLɱQXϰMLXXTWHSGWT]XLSRSVKPMFVEV]SWLXQP

1SHYPI os.path
1SHYPI os.path LЦXVвGɨGTLš˜RKXLиGKMɾTXLESXɨG
RLERLGLɹRKZɧXLYϼRXMЖRL˜RXVɱ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

XLšQдG
os.path.dirname(path) XVϲZАXɱRXLšQдGGжETEXL

os.path.getatime(path) XVϲZАXLЬMKMERXVY]GϼT

QЪMRLϴX

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK<мPʁLɳRLϲRL
7мHдRKXLšZMЖR4MPPS[ 4-0*SVO чВXMЎRLɧRLGɨGXLES
XɨG\мPʁLɳRLϲRLч˜RKMϲRRLšVIWM^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")

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

7EYOLMQЮJMPILɳRLXLɧRLGɺRKXLɳGɹXLВXLESXɨGXVɱRчРM
XšвRK im 

+LMJMPI
8кчРMXšвRK Image GɹXLВPšYJMPI\YРRKQɨ]XɴRLFЀRK
TLš˜RKXLиG save(path, type) :ɴHд

...
im.save('photo_new.jpg', 'JPEG')

8ϰSXLYQFREMP
7мHдRKTLš˜RKXLиG thumbnail RLšWEY

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'ɨGXLESXɨG\мPʁLɳRLϲRL
8LEQOLϲSXLɱQXLšZMЖR4-0XϰM
LXXTTMPPS[VIEHXLIHSGWSVKIRPEXIWXMRHI\LXQP

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK<мPʁJMPI.732
.732PɧQШXXVSRKRLоRKчКRLHϰRKJMPIXVESчФMHоPMЖY
XLɺRKHдRKRLϴXLMЖRRE]:ЪMOMЎRXVɾGч˜RKMϲRZɧXš˜RK
чТ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ɱRGLš˜RKRɧ]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д

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ЎYRLšFϰRчɪGɹ.732HEXEHšЪMHϰRKGLYЦMQYРR
TEVWMRKGLYЦMRɧ]XLɧRL(EXEXLɳWмHдRKRLšGɨGLHšЪM
чɩ]

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ЎYRLšFϰ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"})

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK<мPʁJMPI<10
8VSRKTL϶RRɧ]GLɾRKXEWЌTEVWMRKRШMHYRK<10XLɧRL
HоPMЖYчВ\мPʁɇВ\мPʁ<10XEWЌWмHдRKXLšZMЖR
&IEYXMJYPWSYTɇɩ]PɧQШXXLšZMЖ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 RLšWEY

$ 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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

LXXT[[[GVYQQ]GSQWSJX[EVI&IEYXMJYP7SYTFWHSGMRW
ETEVWIV

8VɱR1EG37GɹXLВGɧMFЀRK pip RLšWEY

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>

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

<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ɳRLRLšWEY

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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
8š˜RKXрRLš xml &IEYXMJYP7SYTGɹXLВTEVWMRKRШMHYRK
,810XLɺRKUYELɧQOLЮMXϰSZɧGLМR html ЮXLEQWР
XLи

...
soup = Soup(websitehtml, 'html')

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK/ЎXRРM1]750
1]750PɧQШXLЖG˜WЮ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ɹXLšZMЖ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 RLšWEY

$ sudo pip install MySQL-python

8LEQOLϲSXLɱQXϰMLXXTWT]TMT]XLSRSVKT]TM1]750
T]XLSR

/LEMFɨSQSHYPI1]750HFPɧGɹXLВWмHдRK

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

import MySQLdb

8VSRKQШXWРXVšЬRKLвTчɪGɧM1]750HFRLšRKMQTSVX
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 чЎRXLšQд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ɧQRLšWEYчВXVϲZАOЎXRРM

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

import MySQLdb

dbcon = MySQLdb.connect(host = 'localhost', user =


'myusername', passwd = 'mypassword', db = 'mydbname
')

2ЎYOЎXRРMOLɺRKXLɧRLGɺRKXLɳWЌFɨSPЦMZɧRKšRK
GLš˜RKXVɳRL'ɨGLOЎXRРMERXSɧRPɧчšEZɧSXVSRK try
чВFϾXPЦMRLšWEY

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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
RLšWEY

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

...
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А

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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о

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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д

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ɧTLš˜RK
XLиG execute() WЌGɹXLEQWРXLиPɧQШX8YTPIGɹKMɨXVК

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

Xš˜RKиRKZЪMXLиXр\YϴXLMЖRGжEGɨGXLɧRLTL϶R %s

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK/ЎXRРM6IHMW
6IHMWPɧQШXQIQSV]GEGLIWIVZIVLЦXVвTIVWMWXERXHEXE
XLɺRKHдRKRLϴXLMЖRRE]2ШMHYRKGLš˜RKRɧ]WЌLšЪRK
HϺRFϰROЎXRРMчЎRQШX6IHMWWIVZIV чɪчšвGGɧMчІX
WЄR XLɺRKUYEXLšZMЖRVIHMWT]

'ɧMчІX
'ɹXLВ\IQXLɱQZАLšЪRKHϺRGɧMчІXXLšZMЖ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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ШXVIUYIWXRLšXLɺRKXLšЬRK<IQZɴHд
WEYчВLMВYGɨGLWмHдRKTMTIPMRIFЀRK redis-py 

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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МMTLš˜RKXLиG execute() XLɳWЌXVϲZА0MWXXš˜RK


иRKZЪMGɨGOЎXUYϲGжEXкRKPЖRL:ɴHдOЎXUYϲXкчSϰR
GSHIXVɱR

[True, True, True, 'bar']

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK/ЎXRРM
1IQGEGLIH
1IQGEGLIHPɧQШXQIQSV]GEGLIWIVZIVXLɺRKHдRKLMЖR
RE]2ШMHYRKGLš˜RKRɧ]WЌLšЪRKHϺRFϰROЎXRРMчЎR
QШX1IQGEGLIHWIVZIV чɪчšвGGɧMчІXWЄR XLɺRKUYE
XLšZMЖR pylibmc 

'ɧMчІX
'ɹXLВ\IQXLɱQZАLšЪRKHϺRGɧMчІXXLšZMЖ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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK/Ў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
XLšZMЖR pika 

'ɧMчІX
'ɹXLВ\IQXLɱQZАLšЪRKHϺRGɧMчІXXLšZMЖRRɧ]XϰM
LXXTWTMOEVIEHXLIHSGWSVKIR

ɇ˜RKMϲRGɧMXLɺRKUYE pip Pɧ

$ sudo pip install pika

+ЮMQШXQIWWEKIчЎR7IVZIV
4VSZMHIV
:ɴHдчВKЮMQШXQIWWEKIчЎRWIVZIV

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

Э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 

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

channel 8Y]RLMɱRZɳPɧGSRWYQIVRɱRWЌWмHдRK
TLš˜RKXLи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ШMHYRKGLš˜RKRɧ]OLɺRKGɹʁчКRLKMЪMXLMЖYXϴXGϲOLɨM
RMЖQGжE%154GˢRKRLš6EFFMX15QɧGLж]ЎYKMЪMXLMЖY
XLšZMЖ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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK6IWXJYPGPMIRX
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

'Lš˜RKRɧ]WЌKMЪMXLMЖYZАQШXXVSRKRLоRKXLšZMЖ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 RLšWEY

$ sudo pip install requests

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

6IUYIWX
,ЦXVвWЄRGɨGTLš˜RKXLиGXš˜RKи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МMTLš˜RKXLиG get() :ɴ
Hд

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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ɨGVIUYIWXRLš4378498
XLš˜RKG϶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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'ɹ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ɨGTLš˜RKXLиGXš˜RKиRKчВVIUYIWXFϰRWЌ
GɹчРMXšвRKXLYШGGPEWW Response ɇРMXšвRKRɧ]GɹQШX
WРXLɺRKXMRRLšWEY

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

8LEQOLϲSZАGɨGXɴRLRʆRKOLɨGGжEXLšZMЖR requests
XϰM[IFWMXIGLɴRLXLиGLXXTHSGWT]XLSRVIUYIWXWSVK

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK+ЮMIQEMPZЪM7184
7184PɧKMESXLиGKЮMQEMPXLɺRKHдRKLMЖRRE]4]XLSRLЦ
XVвQІGчКRLXLšZMЖ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дRKXLšZMЖR sender PɧQШXXLšZMЖR
KMɾTчКRLHϰRKZɧKЮMIQEMPч˜RKMϲRL˜R

'ɧMчІX sender
'ɧMчІXXк pip RLšWEY

$ 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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

from sender import Mail, Message

mail = Mail(
"smtp.gmail.com",
port = 465,
username = "[email protected]",
password = "yourpassword",
use_tls = False,
use_ssl = True,
debug_level = False
)

msg = Message("msg subject")


msg.fromaddr = ("Vo Duy Tuan", "[email protected]")
msg.to = "[email protected]"
msg.body = "this is a msg plain text body"
msg.html = "<b>this is a msg text body</b>"
msg.reply_to = "[email protected]"
msg.charset = "utf-8"
msg.extra_headers = {}
msg.mail_options = []
msg.rcpt_options = []

# Send message
mail.send(msg)

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

+Ю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АXLšZMЖR sender XϰM[IFWMXI

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

GLɴRLXLиGXϰMчКEGLИLXXTWIRHIVVIEHXLIHSGWSVK

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

'Lš˜RK7SGOIX
TVSKVEQQMRK
'Lš˜RKRɧ]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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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

Downloaded by Duong Tran Huu ([email protected])


lOMoARcPSD|35016901

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кTLš˜RKXLиG
socket.gethostname() ZɧTSVX7EYOLMOЎXRРMWЌ
LMВRXLКVEOЎXUYϲXVϲZАXкWIVZIV7EYчɹXLɳчɹRKOЎXRРM

Downloaded by Duong Tran Huu ([email protected])

You might also like