Lập trình Python cơ bản - pyqt5.files.wordpress.com · Comments Comments là một đoạn...
Transcript of Lập trình Python cơ bản - pyqt5.files.wordpress.com · Comments Comments là một đoạn...
1. Introduction2. CàiđặtPython3. Bắtđầu4. Biếnvàkiểudữliệu5. Toántửvàbiểuthức6. CâulệnhđiềukhiểnIfelse7. Vònglặp8. Cấutrúcdữliệu9. Chuỗi10. Hàm11. Xửlýtậptin12. Exceptions13. Class
MụcLục
LậptrìnhPythoncơbản
2
Chàocácbạn,
NgônngữlậptrìnhPythonngàycàngđượcphổbiếnvàứngdụngrộngrãitrongIT.Nắmbắtđượcxuhướngđóvànhằmtạođiềukiệnnghiêncứuchocácsinhviên,ngườimớibắtđầutiếpxúcvớiPython,cộngđồngPythonViệtNamsưutầmvàbiêntậplạigiớithiệucàinhìntổngquannhấtvềPython.
Trongquátrìnhsưutâm,biêndịchchắcchắnkhôngthểtránhkhỏicácthiếusót,rấtmongđượcsựđónggóphơnnữacủacácđồngnghiệp,anhembạnbèđểhoànthiệnhơnnữa.
Mọiýkiếnđónggópxingửivề:
NguyễnNgọcKhánh
Email:[email protected]
Skype/Yahoo:khanhnnvn
http://pythonvietnam.info
http://pythonvietnam.com
Facebook:FanPage,Group
Cảmơnsựquantâm,ủnghộcủacácbạn!
Nhómdịchgiả.
Giớithiệuchung
LậptrìnhPythoncơbản
3Introduction
Trongphầnnày,chúngtasẽnóivềvấnđềcàiđặtPython.
a.CàiđặtPythontrênWindows:
Bước1:Thựchiệntảibảncàiđặttừtrangchủ:http://www.python.org.ChúýphiênbảnđượcchúngtôisửdụngtrongtàiliệunàylàPython2.xvìvậybạnnênlựachọnphiênbảnphùhợpchoviệcthựchành.
Bước2:TiếnhànhcàiđặtPythonnhưmộtchươngtrìnhtrênWindowsbìnhthường.
Bước3:ĐểcóthểlàmviệcvớiPythonởcửasổcmdmàkhôngcầntrỏrõthưmụccàiđặt,bạncầnthiếtlậpbiếnmôitrườngbằngcách:
ClickchuộtphảivàoMycomputerchọnProperties
ClickchọnAdvancedsystemsettting.
ChọnEnvironmentVariables
SauđóthêmđườngdẫncàiđặtPythonvàobiếnPATH
Sauđóbạngõpythontạicủasổcmd,nếuhiểnthịnhưsaulàbạnđãthànhcông.
Python2.7.6(default,Nov102013,19:24:18)[MSCv.150032bit(Intel)]onwin32
Type"copyright","credits"or"license()"formoreinformation.
>>>
b.CàiđặttrênHĐHLinux
HầunhưcáchệđiềuhànhđềuhỗtrợPython,bạncóthểcàiđặtonline,hoặcoffline.Chúngtasẽthấycáccáchphổbiếnsau:
TrênDebian(Ubuntu,LinuxMint,...)chúngtasửdụng
apt-getinstallpython
TrênRedHat(CentOS,RedHat,Asianux,...)
yuminstallpython
Saukhicàiđặtxong,bạncũngcóthểsửdụngPythonbằngcáchgõpythonvàocửasổdònglệnh.
Chúccácbạnthànhcông!
CàiđặtPython
LậptrìnhPythoncơbản
4CàiđặtPython
Pythonlàngônngữlậptrìnhthôngdịch,điềuđócónghĩalàbạncóthểviếtcodengaytrêntrìnhthôngdịchhoặcviếtvàofilesauđóchạychúng.Đầutiênchúngtasẽsửdụngtrìnhthôngdịchđểbắtđầuviếtmộtchươngtrìnhđầutiên(bạncóthểsửdụngshelltrênWindowshoặcTerminaltrênLinux)
$python
Python2.5.1(r251:54863,Oct302007,13:54:11)
q[GCC4.1.220070925(RedHat4.1.2-33)]onlinux2
Type"help","copyright","credits"or"license"formoreinformation.
>>>
Đểcóthểinradòngchữ"XinchàoPythonVietNam"bạncóthểlàmnhưsau:
>>>print"XinchàoPythonVietNam!"
HelloWorld!
helloworld.py
Bâygiờtasẽlàmcáchmàlậptrìnhviênhaylàm,bạnsẽtạomộtfilehelloworld.py,bạncóthểsửdụngbấtcứmộttrìnhsoạnthảomàbạnbiếtđểtạorafilenày.Chúýđuôimởrộnglà.py
#!/usr/bin/envpython
print"HelloWorld!"
Đểthựchiệnchạy,bạncầntraoquyềnchofileđóđượcthựcthi.Bạndùnglệnhsau:
$chmod+xhelloworld.py
Sauđóchạy
$./helloworld.py
HelloWorld!
Trongdòngđầutiêncódấu#!,chúngtagọinólàsha-bang.SửdụngđểthôngbáochotrìnhthôngdịchPythonchạyđoạncode.Dòngtiếptheotrongđoạncodetrênchúngtainrathôngbáo.TrongPythonchúngtagọicácdòngvănbảnlàchuỗi.
Khoảngtrắngvàthụtđầudòng
TrongPythonkhoảngtrắngrấtquantrọng.Chúngtaphânbiệtcáchsửdụngdấukhoảngtrắng.Khoảngtrắngtrongdòngđầutiênđượcxemnhưdấuthụtđầudòng.Nhưngnếusửdụngsaithìsẽbáolỗi.
Vídụnhưsau:
>>>a=12
>>>a=12
File"<stdin>",line1
a=12
IndentationError:unexpectedindent
Bắtđầu
LậptrìnhPythoncơbản
5Bắtđầu
^
Chúý:Cómộtdấucáchđầutiêngâyralỗitrongđoạncodetrên,dođóchúngtacầnđặtdấuthụtđầudòngthíchhợp.
Chúngtacómộtsốchúýchoviệcsửdụngdấukhoảngtrắngvàđịnhdanh
Use4spacesforindentation.
Nevermixtabandspaces.
Oneblanklinebetweenfunctions.
Twoblanklinesbetweenclasses.
Cónhiềunơitrongđoạncodemàbạnphảiáodụngcáchdùngdấucách,vídụnhư:
Addaspaceafter”,”indicts,lists,tuples,andargumentlistsandafter”:”indicts.
Spacesaroundassignmentsandcomparisons(exceptinargumentlist)
Nospacesjustinsideparentheses.
CommentsCommentslàmộtđoạnvănbảnđượcviếttrongcode,chúngđượcsửdụngđểgiảithíchhoặcchúthíchchongườikháchiểuvềđoạncodeđó.Mộtđoạncommentbắtđầubằngdấu#,mọithứsaudấucommentkhôngđượcthựcthitrongchươngtrình.
>>>#Thisisacomment
>>>#Thenextlinewilladdtwonumbers
>>>a=12+34
>>>printc#thisisacommenttoo:)
Commentsgiúpcholậptrìnhviêndễdàngcảitiếnmãnguồn,ghichúcácchứcnăngcủađoạncodethựchiện,nócóthểlàngườiviết,ngàyviết.
#FIXME--fixthesecodelater
#TODO--infutureyouhavetodothis
ModulesModulestrongPythonlàcáctậptinchưacáchàmđượcđịnhnghĩasẵn,biếncáimàchúngtacóthểsửdụnglại,nócũngcóđuôimởrộnglà.py.Pythonđãcungcấpsẵnmộtsốmodulemặcđịnh.Chúngtacóthểsửdụngchúng.Đểsửdụngchúngtacầndùnglệnhimport.Vídụnhưsau:
>>>importmath
>>>printmath.e
2.71828182846
ChúngtasẽtìmhiểuchitiếtvềcácModuletrongcácphầnsau.Chúccácbạnthànhcông!
LậptrìnhPythoncơbản
6Bắtđầu
Từkhóavàđịnhdanh
CodePythoncóthểđượcchiathànhcácđịnhdanh.Đinhdanh(haycònđượcgọilàtên)đượcmôtảbởicácđịnhnghĩatừvựngsauđây:
identifier::=(letter|"_")(letter|digit|"_")*
letter::=lowercase|uppercase
lowercase::="a"..."z"
uppercase::="A"..."Z"
digit::="0"..."9"
Sauđâylàdanhsáchcáctừkhóacủangônngữ,chúngtakhôngthểsửdụngchúngnhưmộtđịnhdanhthôngthường.Chúngtaphảidùngchínhxáccáctừsauđây:
anddelfromnotwhile
aselifglobalorwith
assertelseifpassyield
breakexceptimportprint
classexecinraise
continuefinallyisreturn
defforlambdatry
TrongPythonchúngtakhôngchỉđịnhmộtkiểudữliệutrongmộtbiến.Tuynhiênchúngtacóthểviếtabc=1vàabcsẽtrởthànhdữliệukiểunguyên.Nếuviếtabc=1.0thìabcsẽlàkiểusốthực.Sauđâylàvídụcơbảnvềviệcgángiátrịchobiến:
>>>a=13
>>>b=23
>>>a+b
36
TrongvídụtrênbạnđãhiểucáchkhaibáobiếntrongPython,bạnchỉcầngõtênvàgiátrịcủabiến.Pythoncóthểthaotáctrênchuỗi.Chúngđượcđặttrongdấungoặcđơnhoặcngoặcképnhư:
>>>'India'
'India'
>>>'India\'sbest'
"India'sbest"
>>>"HelloWorld!"
'HelloWorld!'
Nhậndữliệutừbànphím:
TrongPythonbạnkhôngcầnbướcđọcdữliệutừbànphím.Bạncóthểsửdụnghàmraw_inputđểthựchiệnnhậpdữliệu:Vídụnhư:
raw_input("XinchaoPythonVietNam")
vàsẽtrảvềchuỗiđầuvào.Chúngtasẽthửviếtmộtchươngtrìnhđơngiảnchophépđọcsốđượcnhậptừbànphímsauđókiểmtranólớnhơn100hoặckhông.Tênchươngtrìnhnàycótênlàtesthundred.py:
Biếnvàkiểudữliệu
LậptrìnhPythoncơbản
7Biếnvàkiểudữliệu
#!/usr/bin/envpython
number=int(raw_input("Enteraninteger:"))
ifnumber<100:
print"Yournumberissmallerthan100"
else:
print"Yournumberisgreaterthan100"
Kếtquảsẽnhưsau:
$./testhundred.py
Enteraninteger:13
Yournumberissmallerthan100
$./testhundred.py
Enteraninteger:123
Yournumberisgreaterthan100
Trongchươngtrìnhtiếpchúngtasẽlấyvídụvềviệctínhtoáncáckhoảnđầutư:
#!/usr/bin/envpython
amount=float(raw_input("Enteramount:"))
inrate=float(raw_input("EnterInterestrate:"))
period=int(raw_input("Enterperiod:"))
value=0
year=1
whileyear<=period:
value=amount+(inrate*amount)
print"Year%dRs.%.2f"%(year,value)
amount=value
year=year+1
Kếtquảnhưsau:
$./investment.py
Enteramount:10000
EnterInterestrate:0.14
Enterperiod:5
Year1Rs.11400.00
Year2Rs.12996.00
Year3Rs.14815.44
Year4Rs.16889.60
Year5Rs.19254.15
Mộtvàivídụ:
Mộtvàivídụvềbiếnvàkiểudữliệu:
TrungbìnhcủasốN
TrongchươngtrìnhnàychúngtasẽtínhtoántrungbìnhcủasốN
#!/usr/bin/envpython
N=10
sum=0
count=0
whilecount<N:
number=float(raw_input(""))
sum=sum+number
count=count+1
average=float(sum)/N
print"N=%d,Sum=%f"%(N,sum)
print"Average=%f"%average
LậptrìnhPythoncơbản
8Biếnvàkiểudữliệu
Kếtquảnhưsau
$./averagen.py
1
2.3
4.67
1.42
7
3.67
4.08
2.2
4.25
8.21
N=10,Sum=38.800000
Average=3.880000
Chuyểnđổinhiệtđộ:ChươngtrìnhphụcvụviệcchuyểnđổitừđộFsangđộCsửdụngcôngthức:C=(F-32)/1.8
#!/usr/bin/envpython
fahrenheit=0.0
print"FahrenheitCelsius"
whilefahrenheit<=250:
celsius=(fahrenheit-32.0)/1.8#HerewecalculatetheCelsiusvalue
print"%5.1f%7.2f"%(fahrenheit,celsius)
fahrenheit=fahrenheit+25
Kếtquảnhưsau:
[kd@kdlappybook]$./temperature.py
FahrenheitCelsius
0.0-17.78
25.0-3.89
50.010.00
75.023.89
100.037.78
125.051.67
150.065.56
175.079.44
200.093.33
225.0107.22
250.0121.11
Gánnhiềugiátrịchobiếntrênmộtdòng:
Bạncóthểkhaibáonhiềugiátrịchonhiềubiếntrênmộtdòng,vídụnhưsau:
>>>a,b=45,54
>>>a
45
>>>b
54
Bạncũngcóthểchuyểnđổigiữahaigiátrịrấtdễdàng:
>>>a,b=b,a
>>>a
54
>>>b
45
LậptrìnhPythoncơbản
9Biếnvàkiểudữliệu
Đểhiểuhơncáchlàmviệc,chúngtasẽtìmhiểuvềkiểudữliệutuple.Chúngtasẽsửdụngdấuphẩychoviệctạotuple.Ởbênphảichúngtasẽtạomộttuple(chúngtagọichúnglàgóituple)vàphíabêntráichúngtagọilàtuplegiảinénchomộttuplemới.
Dướiđâylàmộtvídụ:
>>>data=("KushalDas","India","Python")
>>>name,country,language=data
>>>name
'KushalDas'
>>>country
'India'
>>>language
'Python'
Chúccácbạnthànhcông!
LậptrìnhPythoncơbản
10Biếnvàkiểudữliệu
TrongPythonbạncóthểviếtbiểuthứctrêncácdòng.
Vídụ:
>>>2+3
5
>>>23-3
20
>>>22.0/12
1.8333333333333333
Đểlấygiátrịthậpphânbạnthựchiệnnhưtrên.Đểlấygiátrịlàmtrongbạnsửdụngtoántử%
>>>14%3
2
Vídụvềsốnguyên
#!/usr/bin/envpython
days=int(raw_input("Enterdays:"))
months=days/30
days=days%30
print"Months=%dDays=%d"%(months,days)
Kếtquảnhưsau:
$./integer.py
Enterdays:265
Months=8Days=25
Trongdòngđầutiênchúngtasẽlấysốngày,sauđólấysốthángvàngàyvàcuốicùnglàinchúngramànhình.Bạncóthểlàmchúngmộtcáchdễdàng.
#!/usr/bin/envpython
days=int(raw_input("Enterdays:"))
print"Months=%dDays=%d"%(divmod(days,30))
Hàmdivmod(num1,num2)trảvềhaigiátrị,firstisthedivisionofnum1andnum2andinsecondthemoduloofnum1andnum2.
RelationalOperators
YoucanusethefollowingoperatorsasrelationaloperatorsRelationalOperatorsOperatorMeaning
<Islessthan<=Islessthanorequalto
Isgreaterthan
Toántửvàbiểuthức
LậptrìnhPythoncơbản
11Toántửvàbiểuthức
=Isgreaterthanorequalto==Isequalto!=Isnotequalto
Vídụ:
>>>1<2
True
>>>3>34
False
>>>23==45
False
>>>34!=323
True
//
>>>4.0//3
1.0
>>>4.0/3
1.3333333333333333
LogicalOperators
TodologicalAND,ORweuseand,orkeywords.xandyreturnsFalseifxisFalseelseitreturnsevaluationofy.IfxisTrue,itreturnsTrue.
>>>1and4
4
>>>1or4
1
>>>-1or4
-1
>>>0or4
4
ShorthandOperator
xop=expressionisthesyntaxforshorthandoperators.Itwillbeevaluatedlikex=xopexpression,Fewexamplesare
>>>a=12
>>>a+=13
>>>a
25
>>>a/=3
>>>a
8
>>>a+=(26*32)
>>>a
840
shorthand.pyexample
#!/usr/bin/envpython
N=100
a=2
whilea<N:
print"%d"%a
a*=a
Theoutput
$./shorthand.py
LậptrìnhPythoncơbản
12Toántửvàbiểuthức
2
4
16
Expressions
Generallywhilewritingexpressionsweputspacesbeforeandaftereveryoperatorsothatthecodebecomesclearertoread,like
a=234*(45-56.0/34)
Oneexamplecodeusedtoshowexpressions
#!/usr/bin/envpython
a=9
b=12
c=3
x=a-b/3+c*2-1
y=a-b/(3+c)*(2-1)
z=a-(b/(3+c)*2)-1
print"X=",x
print"Y=",y
print"Z=",z
Theoutput
$./evaluationexp.py
X=10
Y=7
Z=4
Atfirstxisbeingcalculated.Thestepsarelikethis
9-12/3+3*2-1
9-4+3*2-1
9-4+6-1
5+6-1
11-1
10
Nowforyandzwehaveparentheses,sotheexpressionsevaluatedindifferentway.Dothecalculationyourselftocheckthem.
Chuyểnđổikiểu
Chúngtacóthểthưchiệnchuyểnđổithủcông.Vídụnhư:
float(string)->floatvalue
int(string)->integervalue
str(integer)orstr(float)->stringrepresentation
>>>a=8.126768
>>>str(a)
'8.126768'
evaluateequ.py
LậptrìnhPythoncơbản
13Toántửvàbiểuthức
Sauđâylàchươngtrìnhtínhtoángiátrịcủadãysố1/x+1/(x+1)+1/(x+2)+...+1/nvớintăngdần,trongtrườnghợpx=1vàn=10
#!/usr/bin/envpython
sum=0.0
foriinrange(1,11):
sum+=1.0/i
print"%2d%6.4f"%(i,sum)
Kếtquảnhưsau:
$./evaluateequ.py
11.0000
21.5000
31.8333
42.0833
52.2833
62.4500
72.5929
82.7179
92.8290
102.9290
Dòngcodesum+=1.0/inócónghĩalàsum=sum+1.0/i.
quadraticequation.py
Sauđâylàchươngtrìnhgiảiphươngtrìnhbậc2
#!/usr/bin/envpython
importmath
a=int(raw_input("Entervalueofa:"))
b=int(raw_input("Entervalueofb:"))
c=int(raw_input("Entervalueofc:"))
d=b*b-4*a*c
ifd<0:
print"ROOTSareimaginary"
else:
root1=(-b+math.sqrt(d))/(2.0*a)
root2=(-b-math.sqrt(d))/(2.0*a)
print"Root1=",root1
print"Root2=",root2
salesmansalary.py
Trongvídụnàychúngtasẽthựchiệntínhtoánlươngcủamộtnhânviênkinhdoanhcamera.Lươngcơbảnlà1500,vớimỗimộtcamerabánđượcanhấysẽcó200vàhoahồngcủanhânviênkinhdoanhlà2%.Đầuvàolàsốcameravàtổngsốgiácủacamera.
#!/usr/bin/envpython
basic_salary=1500
bonus_rate=200
commision_rate=0.02
numberofcamera=int(raw_input("Enterthenumberofinputssold:"))
price=float(raw_input("Enterthetotalprices:"))
bonus=(bonus_rate*numberofcamera)
commision=(commision_rate*numberofcamera*price)
print"Bonus=%6.2f"%bonus
print"Commision=%6.2f"%commision
print"Grosssalary=%6.2f"%(basic_salary+bonus+commision)
LậptrìnhPythoncơbản
14Toántửvàbiểuthức
Kếtquảnhưsau:
$./salesmansalary.py
Enterthenumberofinputssold:5
Enterthetotalprices:20450
Bonus=1000.00
Commision=2045.00
Grosssalary=4545.00
LậptrìnhPythoncơbản
15Toántửvàbiểuthức
Mẫucâuđiềukhiểnnhưsau:
Ifstatement
Thesyntaxlookslike
ifexpression:
dothis
Dướiđâylàvídụđểcheckmộtsốlớnhơnhoặcnhỏhơn100:
#!/usr/bin/envpython
number=int(raw_input("Enteranumber:"))
ifnumber<100:
print"Thenumberislessthan100"
Sauđóchạynónhưsau:
$./number100.py
Enteranumber:12
Thenumberislessthan100
Else
Trongtrườnghợpmuốninrasốđólớnhơn100,trườnghợpnàychúngtasửdụngelse.Nósẽthựchiệnkhibiểuthứcifkhônghoànthành.
#!/usr/bin/envpython
number=int(raw_input("Enteranumber:"))
ifnumber<100:
print"Thenumberislessthan100"
else:
print"Thenumberisgreaterthan100"
Kếtquảnhưsau:
$./number100.py
Enteranumber:345
Thenumberisgreaterthan100
Mộtvídụrấtđơngiảnnhưsau:
>>>x=int(raw_input("Pleaseenteraninteger:"))
>>>ifx<0:
...x=0
...print'Negativechangedtozero'
...elifx==0:
...print'Zero'
...elifx==1:
...print'Single'
...else:
...print'More'
CâulệnhđiềukhiểnIfelse
LậptrìnhPythoncơbản
16CâulệnhđiềukhiểnIfelse
Kiểmtragiátrịthật
ifx:
pass
Warning
Don’tdothis
ifx==True:
pass
LậptrìnhPythoncơbản
17CâulệnhđiềukhiểnIfelse
Trongvídụtrước,đôikhinóđượcyêucầulàmvàicôngviệccùngmộtlúc.Chúngtasẽphảithựchiệncodenhiềulầnchoviệcthưcthi.Nóimộtcáchkỹthuậtthìđâylàvònglặp.TrướctiênchúngtasẽxembiểuthứcWilechovònglặp.
VònglặpWhile
CúphápcủavònglặpWhilenhưsau:
whilecondition:
statement1
statement2
Đoạncodechúngtamuốnchạysauvònglặpwhilephảiđượcthụtđầudòng.Chúngtasẽthựchiệnchúngnếubiểuthứclàđúng.Chúngtasẽviếtđoạncodeinrasốtừ0đến10nhưsau:
>>>n=0
>>>whilen<11:
...printn
...n+=1
...
0
1
2
3
4
5
6
7
8
9
10
Trongdòngđầutiêntakhaibáon=0,sauđótrongbiểuthứcwhilekhin<11,điềuđócónghĩalàchúngsẽđượcthựchiệnđếnkhin<11.Trongvònglặpchúngtaingiátrịcủansauđósắpsếpchúng.
DãysốFibonacciChúngtasẽgiảibàitoánFibonacci.Chươngtrìnhnhưsau:
#!/usr/bin/envpython
a,b=0,1
whileb<100:
printb
a,b=b,a+b
Kếtquảnhưsau:
$./fibonacci1.py
1
1
2
3
5
8
13
21
34
55
89
Vònglặp
LậptrìnhPythoncơbản
18Vònglặp
Trongdòngđầutiêncủađoạncodechúngtasẽgánavàb,sauđóvònglặpwhilevớibcógiátrịnhỏhơn100.Tronglặpđầutiênchúngtasẽinragiátrịbsauđótiếptheosẽingiátrịcủabchoavàa+bchobtrongdòngtiếptheo.
#!/usr/bin/envpython
a,b=0,1
whileb<100:
printb,
a,b=b,a+b
Kếtquảsẽnhưsau:
$./fibonacci2.py
1123581321345589
PowerSeries
Chúngtasẽviếtchươngtrìnhđểtínhtoánvídụ:ex=1+x+x2/2!+x3/3!+....+xn/n!where0<x<1
#!/usr/bin/envpython
x=float(raw_input("Enterthevalueofx:"))
n=term=num=1
sum=1.0
whilen<=100:
term*=x/n
sum+=term
n+=1
ifterm<0.0001:
break
print"NoofTimes=%dandSum=%f"%(n,sum)
Kếtquảnhưsau:
$./powerseries.py
Enterthevalueofx:0
NoofTimes=2andSum=1.000000
$./powerseries.py
Enterthevalueofx:0.1
NoofTimes=5andSum=1.105171
$./powerseries.py
Enterthevalueofx:0.5
NoofTimes=7andSum=1.648720
Trongchươngtrìnhchúngtacómộttừkhóamớiđượcgọilàbreak.Từkhóasẽthựchiệndừngkhivònglặpđangchạy.Vídụnhưsau:
ifterm<0.0001:
break
Điềunayfcosnghĩanếugiátrịcủatermnhỏhơn0.0001sauđóthoátkhỏivònglặp.
Phépnhânbảng:
Trongvídụsauchúngtasẽinrabảngphéonhântới10
LậptrìnhPythoncơbản
19Vònglặp
#!/usr/bin/envpython
i=1
print"-"*50
whilei<11:
n=1
whilen<=10:
print"%4d"%(i*n),
n+=1
print""
i+=1
print"-"*50
Kếtquảnhưsau:
$./multiplication.py
--------------------------------------------------
12345678910
2468101214161820
36912151821242730
481216202428323640
5101520253035404550
6121824303642485460
7142128354249566370
8162432404856647280
9182736455463728190
102030405060708090100
--------------------------------------------------
Tronghàmprintởtrênchúngtainchuỗivớisốlầnlàn,chuỗisẽđượcxuấthiệnnlần.Vídụ:
>>>print"*"*10
**********
>>>print"#"*20
####################
>>>print"--"*20
----------------------------------------
>>>print"-"*40
----------------------------------------
Someprinting*examples
Herearesomeexampleswhichyoucanfindveryoftenincollegelabreports
Design1
#!/usr/bin/envpython
row=int(raw_input("Enterthenumberofrows:"))
n=row
whilen>=0:
x="*"*n
printx
n-=1
Kếtquảnhưsau
$./design1.py
Enterthenumberofrows:5
*****
****
***
**
LậptrìnhPythoncơbản
20Vònglặp
*
Design2
#!/usr/bin/envpython
n=int(raw_input("Enterthenumberofrows:"))
i=1
whilei<=n:
print"*"*i
i+=1
Theoutput
$./design2.py
Enterthenumberofrows:5
*
**
***
****
*****
Design3
#!/usr/bin/envpython
row=int(raw_input("Enterthenumberofrows:"))
n=row
whilen>=0:
x="*"*n
y=""*(row-n)
printy+x
n-=1
Kếtquả:
$./design3.py
Enterthenumberofrows:5
*****
****
***
**
*
Danhsách
Danhsáchlàkiểudữliệucócấutrúc.
Chúngtasẽtìmhiểuvềmộtkiểudữliệucócấutrúctrướckhichúngtatìmhiểuthêmvềvònglặp.Danhsáchcóthểviếtnhưmộtdanhsáchcácgiátrịcáchnhaubởidấuphẩy(,)vànằmtrongdấungoặcvuông.
>>>a=[1,342,2233423,'India','Fedora']
>>>a
[1,342,2233423,'India','Fedora']
Danhsáchcóthểchứabấtcứdữliệunàotrongchúng.Nóhoạtđộngliêntiếpcónghĩalà
>>>a[0]
LậptrìnhPythoncơbản
21Vònglặp
1
>>>a[4]
'Fedora'
Bạncóthểchiachúngthànhnhiềuphầnkhácnhauvídụ:
>>>a[4]
'Fedora'
>>>a[-1]
'Fedora'
>>>a[-2]
'India'
>>>a[0:-1]
[1,342,2233423,'India']
>>>a[2:-2]
[2233423]
>>>a[:-2]
[1,342,2233423]
>>>a[0::2]
[1,2233423,'Fedora']
Trongvídụnàydấu:đạidiệnchokhoảngdữliệu,cụthểs[i:j:k]cónghĩalàgiátrịstừjtớijsauđóđếnk.Đểkiểmtranếugiátrịcóhoặctồntạitrongdanhsáchhoặckhôngbạncóthểdùng
>>>a=['Fedora','is','cool']
>>>'cool'ina
True
>>>'Linux'ina
False
Điềuđócónghĩalàbạncóthểsửdụngbiểuthứcnhưmộtmệnhđềif.Hàmlen()cungcấpchochúngtađộdàicủadanhsách.
>>>len(a)
3
Ghichú
Nếubạnkiểmtranếudanhsáchrỗnghoặckhông,bạncóthểlàmnhưsau:
iflist_name:#Thismeansthelistisnotempty
pass
else:#Thismeansthelistisempty
pass
Forloop
Đâycũnglàmộtdạngvònglặpsửdụngbiểuthức.TrongPythonbiểuthứccócáchlàmviệckhácvớitrongC.Vídụ
>>>a=['Fedora','is','powerfull']
>>>forxina:
...printx,
...
Fedoraispowerfull
Chúngtacũngcóthểdùngnhưsau:
LậptrìnhPythoncơbản
22Vònglặp
>>>a=[1,2,3,4,5,6,7,8,9,10]
>>>forxina[::2]:
...printx
...
1
3
5
7
9
Hàmrange()
LàmộthàmđượccungcấpsẵntrongPythonvídụ
range(...)range([start,]stop[,step])->danhsáchsốnguyên
Trảvềdanhsáchcácsốnguyên.range(i,j)trảvề[i,i+1,i+2,...,j-1];bắtđầu(!)đượcgánmặcđịnhlà0.
Ởbướcđưara,nóchỉđịnhtăngdầnhoặcgiảmdần.Vídụ,range(4)sẽtrảvềgiátrị[0,1,2,3].Điểmcuốicùngđượcbỏqua.Đâylàcácgiátrịchínhxáccủadanhsáchgồm4phầntử.
Giờnếuchúngtamuốnnhìnthấythôngđiệpgiữđỡcủahệthốngbạncóthểsửdụnglệnhhelp(range)trongtrìnhthôngdịchPython,lệnhhelp(s)sẽtrảvềdònghướngdẫntrongmộtobjects.Vídụvớihàmrange
>>>range(1,5)
[1,2,3,4]
>>>range(1,15,3)
[1,4,7,10,13]
>>>range(10)
[0,1,2,3,4,5,6,7,8,9]
ContinuestatementNếunhưchúngtacólệnhdừngbiểuthứcbreak,thìcũngsẽcócontinue,cáimàsẽbỏquaviệcthựcthiđoạncodevàquaytrởlạiđiểmxuấtphátcủavònglặp.Điềuđócónghĩanósẽgiúpbạnbỏquamộtphầnvònglặp.Trongvídụdướiđâychúngtasẽthựchiệnlại.
#!/usr/bin/envpython
whileTrue:
n=int(raw_input("PleaseenteranInteger:"))
ifn<0:
continue#thiswilltaketheexecutionbacktothestartingoftheloop
elifn==0:
break
print"Squareis",n**2
print"Goodbye"
Kếtquảlà
$./continue.py
PleaseenteranInteger:34
Squareis1156
PleaseenteranInteger:4
Squareis16
PleaseenteranInteger:-9
PleaseenteranInteger:0
Goodbye
VònglặpElse
Chúngtacótùychọnelsecủabiểuthứcsaubấtcứvònglặpnào.Nósẽđượcthựchiệnsaukhivònglặpdừnglại.
LậptrìnhPythoncơbản
23Vònglặp
>>>foriinrange(0,5):
...printi
...else:
...print"Byebye"
...
0
1
2
3
4
Byebye
Gameofsticks
#!/usr/bin/envpython
sticks=21
print"Thereare21sticks,youcantake1-4numberofsticksatatime."
print"Whoeverwilltakethelaststickwillloose"
whileTrue:
print"Sticksleft:",sticks
sticks_taken=int(raw_input("Takesticks(1-4):"))
ifsticks==1:
print"Youtookthelaststick,youloose"
break
ifsticks_taken>=5orsticks_taken<=0:
print"Wrongchoice"
continue
print"Computertook:",(5-sticks_taken),"n\n"
sticks-=5
LậptrìnhPythoncơbản
24Vònglặp
Pythoncómộtvàicấutrúcdữliệucósẵn.Nếubạnchỉtựhỏicấutrúcdữliệulàgì,sauđókhôngcómộtcáchnàođểlưutrữdữliệuvàcácphươngphápcụthểđểlấylạihoặcchỉnhsửanó.ChúngtađãnghiêncứuvềListvàtrongphầnnàychúngtasẽđinghiêncứusâuhơn
Lists
>>>a=[23,45,1,-3434,43624356,234]
>>>a.append(45)
>>>a
[23,45,1,-3434,43624356,234,45]
Đầutiênchúngtasẽtạomộtdanhsácha.Sauđósẽthêmgiátrị45vàocuốicủadanhsáchchúngtasửdụngphươngthứca.append(45).Bạnsẽthấy45đượcgánvàocuốicủadãy.ĐôikhinócũngcóthểđòihỏichèndữliệuởbấtcứnơinàocủaList(danhsách),bạnsửdụnghàminsert()
>>>a.insert(0,1)#1addedatthe0thpositionofthelist
>>>a
[1,23,45,1,-3434,43624356,234,45]
>>>a.insert(0,111)
>>>a
[111,1,23,45,1,-3434,43624356,234,45]
count(s)willreturnyounumberoftimessisinthelist.Herewearegoingtocheckhowmanytimes45isthereinthelist.count(s)sẽtrảvềsốlầnstronglist.Chúngtasẽđikiểmtraxemsốlầnsố45xuấthiệntrongdanhsách.
>>>a.count(45)
2
Ifyouwanttoremoveanyparticularvaluefromthelistyouhavetouseremove()method.Nếubạnmuốnbỏbấtcứgiátrịnàotừtronglistbạncóthểsửdụnghàmremove().
>>>a.remove(234)
>>>a
[111,1,23,45,1,-3434,43624356,45]
Chúngtacũngcóthểlấylạibằngphươngthức,vídu:
>>>a.reverse()
>>>a
[45,43624356,-3434,1,45,23,1,111]
Chúngtacóthểlưutrữbấtcứgìtrongdanhsách,đầutiênchúngtasẽthêmmộtdanhsáchbvàotronga,sauđóchúngtasẽnghiêncứucáchđểthêmgiátrịcủabvàotronga.
>>>b=[45,56,90]
>>>a.append(b)
>>>a
[45,43624356,-3434,1,45,23,1,111,[45,56,90]]
>>>a[-1]
Cấutrúcdữliệu
LậptrìnhPythoncơbản
25Cấutrúcdữliệu
[45,56,90]
>>>a.extend(b)#Toaddthevaluesofbnotthebitself
>>>a
[45,43624356,-3434,1,45,23,1,111,[45,56,90],45,56,90]
>>>a[-1]
90
Ởtrênbạncóthểthấychúngtasửdụnga.extend()đểmởrộngdanhsách.Việcsắpxếplạibạndùnghàmsort()
>>>a.sort()
>>>a
[-3434,1,1,23,45,45,45,56,90,111,43624356,[45,56,90]]
Bạncũngcóthểxóagiátrịcủabấtcứvịtrínàocủadanhsáchbằngcáchsửdụnglệnhdel.
>>>dela[-1]
>>>a
[-3434,1,1,23,45,45,45,56,90,111,43624356]
SửdụngdanhsáchnhưngănxếpvàhàngđợiNgănxếpthườngđượcbiếtđếnnhưLIFO(LastInFirstOut).Nócónghĩalàdữliệusẽđượcđưavàophầncuối,sauđódữliệucuốicùngsẽđirađầu.
>>>a
[1,2,3,4,5,6]
>>>a.pop()
6
>>>a.pop()
5
>>>a.pop()
4
>>>a.pop()
3
>>>a
[1,2]
>>>a.append(34)
>>>a
[1,2,34]
Welearnedanewmethodabovepop().pop(i)willtakeouttheithdatafromthelist.
Inourdailylifewehavetoencounterqueuesmanytimes,likeinticketcountersorinlibraryorinthebillingsectionofanysupermarket.Queueisthedatastructurewhereyoucanappendmoredataattheendandtakeoutdatafromthebeginning.ThatiswhyitisknownasFIFO(FirstInFirstOut).
>>>a=[1,2,3,4,5]
>>>a.append(1)
>>>a
[1,2,3,4,5,1]
>>>a.pop(0)
1
>>>a.pop(0)
2
>>>a
[3,4,5,1]
Totakeoutthefirstelementofthelistweareusinga.pop(0).ListComprehensions
Listcomprehensionsprovideaconcisewaytocreatelists.Eachlistcomprehensionconsistsofanexpressionfollowedbyaforclause,thenzeroormorefororifclauses.Theresultwillbealistresultingfromevaluatingtheexpressioninthecontext
LậptrìnhPythoncơbản
26Cấutrúcdữliệu
oftheforandifclauseswhichfollowit.
Forexampleifwewanttomakealistoutofthesquarevaluesofanotherlist,then
>>>a=[1,2,3]
>>>[x**2forxina]
[1,4,9]
>>>z=[x+1forxin[x**2forxina]]
>>>z
[2,5,10]
Aboveinthesecondcaseweusedtwolistcomprehensionsinasameline.Tuples
Tuplesaredataseparatedbycomma.
>>>a='Fedora','Debian','Kubuntu','Pardus'
>>>a
('Fedora','Debian','Kubuntu','Pardus')
>>>a[1]
'Debian'
>>>forxina:
...printx,
...
FedoraDebianKubuntuPardus
Youcanalsounpackvaluesofanytupleintovariables,like
>>>divmod(15,2)
(7,1)
>>>x,y=divmod(15,2)
>>>x
7
>>>y
1
Tuplesareimmutable,thatmeansyoucannotdel/add/editanyvalueinsidethetuple.Hereisanotherexample
>>>a=(1,2,3,4)
>>>dela[0]
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
TypeError:'tuple'objectdoesn'tsupportitemdeletion
AboveyoucanseePythonisgivingerrorwhenwearetryingtodeleteavalueinthetuple.
Tocreateatuplewhichcontainsonlyonevalueyouhavetotypeatrailingcomma.
>>>a=(123)
>>>a
123
>>>type(a)
<type'int'>
>>>a=(123,)#Lookatthetrailingcomma
>>>a
(123,)
>>>type(a)
<type'tuple'>
LậptrìnhPythoncơbản
27Cấutrúcdữliệu
Usingthebuiltinfunctiontype()youcanknowthedatatypeofanyvariable.Rememberthelen()functionweusedtofindthelengthofanysequence?
>>>type(len)
<type'builtin_function_or_method'>
Sets
Setsareanothertypeofdatastructurewithnoduplicateitems.Wecanalsomathematicalsetoperationsonsets.
>>>a=set('abcthabcjwethddda')
>>>a
set(['a','c','b','e','d','h','j','t','w'])
Andsomeexamplesofthesetoperations
>>>a=set('abracadabra')
>>>b=set('alacazam')
>>>a#uniquelettersina
set(['a','r','b','c','d'])
>>>a-b#lettersinabutnotinb
set(['r','d','b'])
>>>a|b#lettersineitheraorb
set(['a','c','r','d','b','m','z','l'])
>>>a&b#lettersinbothaandb
set(['a','c'])
>>>a^b#lettersinaorbbutnotboth
set(['r','d','b','m','z','l'])
Toaddorpopvaluesfromaset
>>>a
set(['a','c','b','e','d','h','j','q','t','w'])
>>>a.add('p')
>>>a
set(['a','c','b','e','d','h','j','q','p','t','w'])
Dictionaries
Dictionariesareunorderedsetofkey:valuepairswherekeysareunique.Wedeclaredictionariesusing{}braces.Weusedictionariestostoredataforanyparticularkeyandthenretrievethem.
>>>data={'kushal':'Fedora','kart_':'Debian','Jace':'Mac'}
>>>data
{'kushal':'Fedora','Jace':'Mac','kart_':'Debian'}
>>>data['kart_']
'Debian'
Wecanaddmoredatatoitbysimply
>>>data['parthan']='Ubuntu'
>>>data
{'kushal':'Fedora','Jace':'Mac','kart_':'Debian','parthan':'Ubuntu'}
Todeleteanyparticularkey:valuepair
LậptrìnhPythoncơbản
28Cấutrúcdữliệu
>>>deldata['kushal']
>>>data
{'Jace':'Mac','kart_':'Debian','parthan':'Ubuntu'
Tocheckifanykeyisthereinthedictionaryornotyoucanuseinkeyword.
>>>'Soumya'indata
False
Youmustrememberthatnomutableobjectcanbeakey,thatmeansyoucannotusealistasakey.
dict()cancreatedictionariesfromtuplesofkey,valuepair.
>>>dict((('Indian','Delhi'),('Bangladesh','Dhaka')))
{'Indian':'Delhi','Bangladesh':'Dhaka'}
Ifyouwanttoloopthroughadictuseiteritems()method.
>>>data
{'Kushal':'Fedora','Jace':'Mac','kart_':'Debian','parthan':'Ubuntu'}
>>>forx,yindata.iteritems():
...print"%suses%s"%(x,y)
...
KushalusesFedora
JaceusesMac
kart_usesDebian
parthanusesUbuntu
Manytimesithappensthatwewanttoaddmoredatatoavalueinadictionaryandifthekeydoesnotexiststhenweaddsomedefaultvalue.Youcandothisefficientlyusingdict.setdefault(key,default).
>>>data={}
>>>data.setdefault('names',[]).append('Ruby')
>>>data
{'names':['Ruby']}
>>>data.setdefault('names',[]).append('Python')
>>>data
{'names':['Ruby','Python']}
>>>data.setdefault('names',[]).append('C')
>>>data
{'names':['Ruby','Python','C']}
WhenwetrytogetvalueforakeywhichdoesnotexistswegetKeyError.Wecanusedict.get(key,default)togetadefaultvaluewhentheykeydoesnotexistsbefore.
>>>data['foo']
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
KeyError:'foo'
>>>data.get('foo',0)
0
Ifyouwanttoloopthroughalist(oranysequence)andgetiterationnumberatthesametimeyouhavetouseenumerate().
LậptrìnhPythoncơbản
29Cấutrúcdữliệu
>>>fori,jinenumerate(['a','b','c']):
...printi,j
...
0a
1b
2c
Youmayalsoneedtoiteratethroughtwosequencessametime,forthatusezip()function.
>>>a=['Pradeepto','Kushal']
>>>b=['OpenSUSE','Fedora']
>>>forx,yinzip(a,b):
...print"%suses%s"%(x,y)
...
PradeeptousesOpenSUSE
KushalusesFedora
students.py
Inthisexample,youhavetotakenumberofstudentsasinput,thenaskmarksforthreesubjectsas‘Physics’,‘Maths’,‘History’,ifthetotalmarksforanystudentisless120thenprinthefailed,orelsesaypassed.
#!/usr/bin/envpython
n=int(raw_input("Enterthenumberofstudents:"))
data={}#herewewillstorethedata
languages=('Physics','Maths','History')#alllanguages
foriinrange(0,n):#forthennumberofstudents
name=raw_input('Enterthenameofthestudent%d:'%(i+1))#Getthenameofthestudent
marks=[]
forxinlanguages:
marks.append(int(raw_input('Entermarksof%s:'%x)))#Getthemarksforlanguages
data[name]=marks
forx,yindata.iteritems():
total=sum(y)
print"%s'stotalmarks%d"%(x,total)
iftotal<120:
print"%sfailed:("%x
else:
print"%spassed:)"%x
Theoutput
[kd@kdlappybook]$./students.py
Enterthenumberofstudents:2
Enterthenameofthestudent1:Babai
EntermarksofPhysics:12
EntermarksofMaths:45
EntermarksofHistory:40
Enterthenameofthestudent2:Tesla
EntermarksofPhysics:99
EntermarksofMaths:98
EntermarksofHistory:99
Babai'stotalmarks97
Babaifailed:(
Tesla'stotalmarks296
Teslapassed:)
matrixmul.py
Inthisexamplewewillmultiplytwomatrices.Firstwewilltakeinputthenumberofrows/columnsinthematrix(hereweassumeweareusingnxnmatrix).Thenvaluesofthematrices.
LậptrìnhPythoncơbản
30Cấutrúcdữliệu
#!/usr/bin/envpython
n=int(raw_input("Enterthevalueofn:"))
print"EntervaluesfortheMatrixA"
a=[]
foriinrange(0,n):
a.append([int(x)forxinraw_input("").split("")])
print"EntervaluesfortheMatrixB"
b=[]
foriinrange(0,n):
b.append([int(x)forxinraw_input("").split("")])
c=[]
foriinrange(0,n):
c.append([a[i][j]*b[j][i]forjinrange(0,n)])
print"Aftermatrixmultiplication"
print"-"*10*n
forxinc:
foryinx:
print"%5d"%y,
print""
print"-"*10*n
Theoutput
[kd@kdlappybook]$./matrixmul.py
Enterthevalueofn:3
EntervaluesfortheMatrixA
123
456
789
EntervaluesfortheMatrixB
987
654
321
Aftermatrixmultiplication
------------------------------
9129
322512
49329
------------------------------
Herewehaveusedlistcomprehensionscoupleoftimes.[int(x)forxinraw_input(“”).split(””)]herefirstittakestheinputasstringbyraw_input(),thensplittheresultby””,thenforeachvaluecreateoneint.Wearealsousing[a[i][j]*b[j][i]forjinrange(0,n)]togettheresultantrowinasingleline.
LậptrìnhPythoncơbản
31Cấutrúcdữliệu
Chuỗilàvănbảnđơngian.TrongPythonchúngtakhaibáochuỗigiữacácdấu""hoặc''hoặc'''hoặc""""".Vídụdướiđâysẽgiúpbạnhiểurõhơn.
>>>s="IamIndian"
>>>s
'IamIndian'
>>>s='IamIndian'
>>>s="Hereisaline\
...splittedintwolines"
>>>s
'Hereisalinesplitintwolines'
>>>s="Hereisaline\nsplitintwolines"
>>>s
'Hereisaline\nsplitintwolines'
>>>prints
Hereisaline
splitintwolines
Nếubạnmuốninracácchuỗibạncóthểsửdụngdấubangoặc/haingoặcnhưsau:
>>>s="""Thisisa
...multilinestring,soyoucan
...writemanylines"""
>>>prints
Thisisa
multilinestring,soyoucan
writemanylines
Cácphươngphápcủachuỗi.
Mỗichuỗicócungcấpcácphươngthứclàmviệccósẵn,chúngtasẽnghiêncứuhàms.split("")
>>>s="kushaldas"
>>>s.title()
'KushalDas'
Trongvídụnàyhàmtitle()sẽchuyểncáckýtựđầucủachuỗitừchữthườngthànhchữhoa.
Chúngtacóthểsửdụngđểchuyểnchuỗithànhchữhoahoặcchữthường,vídụnhưsau:
>>>z=s.upper()
>>>z
'KUSHALDAS'
>>>z.lower()
'kushaldas'
upper()trảvềkýtựhoahoặclower()trảvềkýtựthườngnhưvídụtrên.
>>>s="IamApRoGraMMer"
>>s.swapcase()
'iAMaPrOgRAmmER'
Chuỗi
LậptrìnhPythoncơbản
32Chuỗi
swapcase()trảvềchuỗivớichuỗiđãđượchoánđổisovớichuỗibanđầu.
>>>s="jdwb2323bjb"
>>>s.isalnum()
False
Vớilàmisalnum()sẽtrảvềkếtquảFalsedohàmhaysẽkiểmtracáckýtựcóphảilàkýtựhaykhông.
>>>s="jdwb2323bjb"
>>>s.isalnum()
True
Đâylàkếtquảkhikhôngcókýtựtrắng.
>>>s="SankarshanSir"
>>>s.isalpha()
True
>>>s="SankarshanSir"
>>>s.isalpha()
False
isalpha()kiểmtrakýtựtrongbảngchữcái.
>>>s="1234"
>>>s.isdigit()#Tocheckifallthecharactersaredigitsornot
True
>>>s="Fedora9iscoming"
>>>s.islower()#Tocheckifallchractersarelowercaseornot
False
>>>s="Fedora9IsComing"
>>>s.istitle()#Tocheckifitisatitleornot
True
>>>s="INDIA"
>>>s.isupper()#Tocheckifcharactersareinuppercaseornot
True
Đểtáchchuỗichúngtacóthểdùnglàmsplit().Nósẽtrảvềchuỗiđượctáchra.
>>>s="WealllovePython"
>>>s.split("")
['We','all','love','Python']
>>>x="Nishant:is:waiting"
>>>x.split(':')
['Nishant','is','waiting']
Chúngtacũngcóthểdùnglàmjoin()đểthựchiệnghépchuỗi
>>>"-".join("GNU/Linuxisgreat".split(""))
'GNU/Linux-is-great'
Trongvídụtrênchúngtachiachuỗi"GNU/Linuxisgreat"đượcchiarabằngdầucách,vàchúngtasẽthaythếbằngdấu"-".
Dảichuỗi
LậptrìnhPythoncơbản
33Chuỗi
Vídụ:
s="abc\n"s.strip()'abc'
Bạncóthểthựchànhstriptừbênphảihoặcbêntráichuỗisửdụnghaihàmlstrip(chars)hoặcrstrip(chars).
>>>s="www.foss.in"
>>>s.lstrip("cwsd.")
'foss.in'
>>>s.rstrip("cnwdi.")
'www.foss'
Tìmkiếmvănbản:
Pythoncũngcungcấpchochúngtahàmđểtìmkiếmkýtự/hoặcchuỗicontrongmộtchuỗi.Vídụ:
>>>s="faultyforareason"
>>>s.find("for")
7
>>>s.find("fora")
-1
>>>s.startswith("fa")#Tocheckifthestringstartswithfaornot
True
>>>s.endswith("reason")#
True
find()sẽtrảvềchuỗinếunhưcókếtquảvà-1nếunhưkhôngcó.
Palindrome
#!/usr/bin/envpython
s=raw_input("Pleaseenterastring:")
z=s[::-1]
ifs==z:
print"Thestringisapalindrome"
else:
print"Thestringisnotapalindrome"
Kếtquả
$./palindrome.py
Pleaseenterastring:madam1
Thestringisnotapalindrome
$./palindrome.py
Pleaseenterastring:madam
Thestringisapalindrome
Sốtừ
Trongvídụnàychúngtasẽđếmsốtừtrongdòng.Vídụ:
#!/usr/bin/envpython
s=raw_input("Enteraline:")
print"Thenumberofwordsinthelineare%d"%(len(s.split("")))
Kếtquảnhưsau
LậptrìnhPythoncơbản
34Chuỗi
$./countwords.py
Enteraline:Sayaminduisagreatprogrammer
Thenumberofwordsinthelineare5
Chúcbạnthànhcông!
LậptrìnhPythoncơbản
35Chuỗi
Tronglậptrìnhchúngtasẽcólúcsửdụngmộtđoạncodelặpđilặplạinhiềulầntrongchươngtrình.Hàmsẽgiúpchúngtathựchiệnđiềunày.Chúngtacóthểviếttấtcảnhữnggìchúngtamuốnthựchiệntronghàmsauđóchỉcầngọikhisửdụng.Nhưởtrênchúngtađãsửdụngcáchàmcósẵnnhưlen(),divmod().
Địnhnghĩahàm
Chúngtasẽdùngtưkhóadefđểthựchiệnđịnhnghĩahàm.Vídụnhưsau:
deffunctionname(params):
statement1
statement2
Chúngtasẽthửviếtmộtchươngtrìnhnhỏđểthựchiệntínhtổngcủahaisốnguyên.
>>>defsum(a,b):
...returna+b
ởdòngthứhaivớigiátrịtừbànphím,chúngtasẽtrảlạikếtquảcủaa+b.Bạnphảigọilạinónhưsau:
>>>res=sum(234234,34453546464)
>>>res
34453780698L
Trongchươngtrìnhvềsốpalindromởchươngtrước,chúngtahayviếtmộthàmđểkiểmtrachuỗicóphảilàpalindromehaykhôngsauđótrảvềkếtquảTruehoặcFalse
#!/usr/bin/envpython
defpalindrome(s):
returns==s[::-1]
if__name__=='__main__':
s=raw_input("Enterastring:")
ifpalindrome(s):
print"Yes,thisisapalindrome"
else:
print"Ohno,notapalindrome"
Giờbạnkiểmtranào.
Biếncụcbộvàbiếntoàncục
Đểcóthểhiểuthếnàolàbiếncụcbộvàbiếntoàncụcchúngtasẽxemhaivídụsau"
#!/usr/bin/envpython
defchange(b):
a=90
printa
a=9
print"Beforethefunctioncall",a
print"insidechangefunction",change(a)
print"Afterthefunctioncall",a
Hàm
LậptrìnhPythoncơbản
36Hàm
Kếtquảnhưsau:
$./local.py
Beforethefunctioncall9
insidechangefunction90
Afterthefunctioncall9
Giảithích:
Chúngtacóthểthấy,đầutiênchúngtasẽgán9chobiếna,sauđósẽgọihàmchange(),tronghàmchange()chúngtasẽgángiátrị90choavàinrasốa.Saukhihàmđượcgọichúngtasẽinramộtlầnnữagiátrịcủaa.Khichúngtagána=90tronghàm,nósẽtạomộtbiếnmớilàbiếna,nhưngbiếnachỉcógiátrịvàthựcthikhihàmđượcgọivàkếtthúckhihàmthựchiệnxong.Ởđâycùngmộttênnhưngchúngkhácnhaukhiởtrongvàngoàihàm.
#!/usr/bin/envpython
defchange(b):
globala
a=90
printa
a=9
print"Beforethefunctioncall",a
print"insidechangefunction",
change(a)
print"Afterthefunctioncall",a
Ởvídụnàychúngtasẽđịnhnghĩabiếntoàncục,tuynhiênkhithayđổigiátrịatronghàmnóchuyểnđổirabênngoàicủahàm.
Kếtquảvídụtrênnhưsau:
>>>
Beforethefunctioncall9
insidechangefunction90
Afterthefunctioncall90
>>>
Giátrịđốisốmặcđịnh
Tronghàmbiếncóthểcóđốisốmặcđịnh,điềuđócónghĩanếuchúngtakhôngđưabấtkìgiátrịnàochobiếnthìnósẽđượcgánmặcđịnh.
>>>deftest(a,b=-99):
...ifa>b:
...returnTrue
...else:
...returnFalse
Ởvídụtrênchúngtagánb=-99tronghàm.Điềuđócónghĩalàgiátrịcủabsẽlà-99.Vànếukhitruyềngiátrịchobiếncủahàmnếukhôngtruyềngiátrịbthìmặcđịnhsẽlà-99
>>>test(12,23)
False
>>>test(12)
True
Important
LậptrìnhPythoncơbản
37Hàm
Bạnhãyghinhớchúngtakhôngthểcómộtđốisốvớiđốisômặcđịnnếubạnkhôngcómộtgiátrịmặcđịnhtrướcđó.Vídụf(a,b=90,c)thìa,bsẽcógiátrịcònckhôngcógiátrịnào.
Vàbạncũngnênchúýgiátrịmặcđịnhchỉđượctínhtoánmộtlần,nếubạncóbấtcứsựthayđổinàosẽlàmdanhsáchthayđổi.Hãyxemvídụsau:
>>>deff(a,data=[]):
...data.append(a)
...returndata
...
>>>printf(1)
[1]
>>>printf(2)
[1,2]
>>>printf(3)
[1,2,3]
ĐểtránhđiềunàyPythoncungcấpcáchchobạnnhưsau:
>>>deff(a,data=None):
...ifdataisNone:
...data=[]
...data.append(a)
...returndata
...
>>>printf(1)
[1]
>>>printf(2)
[2]
Keywordarguments
>>>deffunc(a,b=5,c=10):
...print'ais',a,'andbis',b,'andcis',c
...
>>>func(12,24)
ais12andbis24andcis10
>>>func(12,c=24)
ais12andbis5andcis24
>>>func(b=12,c=24,a=-1)
ais-1andbis12andcis24
Trongvídụtrênbạncóthểthấychúngtasẽgọihàmvớitênbiến,vídụnhưfunc(12,c=24),bằngcáchđóchúngtasẽgán24chocvàbsẽlấygiátrịmặcđịnh.Bạncũngnênchúýtrườnghợpnhưsau:
>>>deffunc(a,b=13,v):
...printa,b,v
...
File"<stdin>",line1
SyntaxError:non-defaultargumentfollowsdefaultargument
Docstrings
TrongPythonchúngtasửdụngdocstringsđểgiảithíchsửdụngcodenhưthếnào,nósẽhữuíchtrongtrìnhthôngdịchvàtạotàiliệutựđộng.Dướiđâylàvídụvềdocstring
#!/usr/bin/envpython
importmath
LậptrìnhPythoncơbản
38Hàm
deflongest_side(a,b):
"""
Functiontofindthelengthofthelongestsideofarighttriangle.
:arga:Sideaofthetriangle
:argb:Sidebofthetriangle
:return:Lengthofthelongestsidecasfloat
"""
returnmath.sqrt(a*a+b*b)
if__name__=='__main__':
printlongest_side(4,5)
Chúngtasẽtìmhiểuthêmvềdocstringstrongchươngsau.
HàmbậccaoHàmbậccaohaylàfunctorlàhàmcócácchứcnăngsau:
Takesoneormorefunctionsasargument.
Returnsanotherfunctionasoutput.
Vídụ:
>>>defhigh(func,value):
...returnfunc(value)
...
>>>lst=high(dir,int)
>>>printlst[-3:]
['imag','numerator','real']
>>>printlst
mapfunction
maprấthữudụngtronghàmbậccaotrongPython.
Vídụ:
>>>lst=[1,2,3,4,5]
>>>defsquare(num):
..."Returnsthesquareofagivennumber."
...returnnum*num
...
>>>printmap(square,lst)
[1,4,9,16,25]
Chúccácbạnthànhcông!
LậptrìnhPythoncơbản
39Hàm
Mộttậptinchứathôngtinhoặcdữliệuđượclưutrữtrênthiếtbịlưutrữcủamáytính.Nhưbạnđãbiếtvềcáckiểucủatậptinnhưâmnhạc,video,vàtậptinvănbản.Pythonsẽcungcấpchobạncáchđểđiềukhiểncáctậptin.Chúngtasẽtậptrungvàohailoại:tậptinvănbảnvàbinary.
Fileopening
Đểthựchiệnmởmộttậptinchúngtasửdụnghàmopen().Vớihàmnàysẽcóhaithamsốđượctruyềnvàođólàđườngdẫnvàchếđộmở.Cácchếđộnhưsau:
“r”->Chếđộchỉđọc,bạnkhôngthểxóahaychỉnhsửagì.
“w”->Chếđộghi,bạncóthểghidữliệuvàotậptin.
“a”->openinappendmode
Mặcđịnhchếđộreadsẽđươcthiếtlập,vídụ
>>>fobj=open("love.txt")
>>>fobj
<openfile'love.txt',mode'r'at0xb7f2d968>
Đóngtậptin
Saukhibạnmởtậptinđểthaotácbạnnênđóngtậptinđólạisaukhithaotác,bạncóthểsửdụnghàmclose().
>>>fobj=open("love.txt")
>>>fobj
<openfile'love.txt',mode'r'at0xb7f2d968>
>>>fobj.close()
Ghichú
Bạncầnchắcchắnrằngbạnluônđóngsaukhimởmộttậptin,saukhicôngviệcđượcthựchiệnbạnkhôngcònlýdonàođểmởnónữa.Bởivìcógiớihạnsốtậptinmàchươngtrìnhcóthểmở.Nếubạnmởquágiớihạnsẽkhôngcócáchnàokhôiphụcđược,hoặccũngcóthểgặpsựcố.Vớimỗitậptinđượcmởtàinguyênbộnhớsẽđượccungcấpchonónhưmôtảtậptinxửlýhoặckhóatậptin.Vìvậybạncóthểtiếtkiệmđượctàinguyềnkhôngsửdụnghoặcítsửdụng.Mởtậptinliêntụccóthểgâyralỗihoặcmấtdữliệu.
Readingafile
Đểđọctậptinchúngtacóthểsửdụnghàmread().
>>>fobj=open("sample.txt")
>>>fobj.read()
'IlovePython\nPradeeptolovesKDE\nSankarshanlovesOpenoffice\n'
Nếubạngọihàmread()nósẽtrảvềchuỗitrongtậptinmànóđọcđược.readline()cóthểgiúpbạnđọctừngdòngcủatậptin.Vídụ:
>>>fobj=open("sample.txt")
Xửlýtậptin
LậptrìnhPythoncơbản
40Xửlýtậptin
>>>fobj.readline()
'IlovePython\n'
>>>fobj.readline()
'PradeeptolovesKDE\n'
Đểđọctoànbộcácdòngchúngtadùngreadlines().
>>>fobj=open("sample.txt")
>>>fobj.readlines()
['IlovePython\n','PradeeptolovesKDE\n','SankarshanlovesOpenoffice\n']
Youcanevenloopthroughthelinesinafileobject.
>>>fobj=open("sample.txt")
>>>forxinf:
...printx,
...
IlovePython
PradeeptolovesKDE
SankarshanlovesOpenoffice
Chúngtasẽviếtchươngtrìnhnhỏđưatêncủatậptinsauđóđưaramànhìnhnộidungcủatậptinđó.
#!/usr/bin/envpython
name=raw_input("Enterthefilename:")
fobj=open(name)
printfobj.read()
fobj.close()
Cuốichươngtrìnhchúngtasửdụnghàmclose()đểthựchiệnđóngtậptinkhikhôngcònthaotácvớinónữa.
Kếtquảnhưsau:
$./showfile.py
Enterthefilename:sample.txt
IlovePython
PradeeptolovesKDE
SankarshanlovesOpenoffice
Writinginafile(ghinộidunglêntậptin)
Chúngtamởtậptinsauđóghimộtvàithôngtinngẫunhiênvàonósửdụnghàmwrite().
>>>fobj=open("ircnicks.txt",'w')
>>>fobj.write('powerpork\n')
>>>fobj.write('indrag\n')
>>>fobj.write('mishti\n')
>>>fobj.write('sankarshan')
>>>fobj.close()
Giờchúngtasẽđọctậptinchúngtavừatạo
>>>fobj=open('ircnicks.txt')
>>>s=fobj.read()
>>>prints
powerpork
LậptrìnhPythoncơbản
41Xửlýtậptin
indrag
mishti
sankarshan
copyfile.py
Trongvídụnàychúngtasẽsaochéptậptinvănbảnnàysangtậptinkhác.
#!/usr/bin/envpython
importsys
iflen(sys.argv)<3:
print"Wrongparameter"
print"./copyfile.pyfile1file2"
sys.exit(1)
f1=open(sys.argv[1])
s=f1.read()
f1.close()
f2=open(sys.argv[2],'w')
f2.write(s)
f2.close()
Ghinhớ
Đâylàcáchđểđọcmộttậptinnhưngkhôngphảilàmộtýtưởnghay,mộttậptinvớidunglượngrấtlớnđểđọcvàsẽtốnnhiềubộnhớ.Cómộtcáchkháclàtạoramộttậptinmớivớidunglượngnhỏhơnrồithựchiệnđọcchúng.
Bạncóthểthấychúngtamộtmodulemớiởđâylàsys.sys.argvchưatấtcảcáclệnhvềdòng.Ghinhớcâulênhcptrongdònglệnh,saucâulệnhcpchúngtasaochéptậptinvànósẽthànhmộttậptinmới.
Cácgiátrịtrongsys.argvlàcáclệnhđầutiêncủanó.
#!/usr/bin/envpython
importsys
print"Firstvalue",sys.argv[0]
print"Allvalues"
fori,xinenumerate(sys.argv):
printi,x
Kếtquảnhưsau:
$./argvtest.pyHithere
Firstvalue./argvtest.py
Allvalues
0./argvtest.py
1Hi
2there
Trongvídụtrênchúngtasửdụngmộthàmmớienumerate(iterableobject),cáimàsẽtrảvềchỉsốvàgiátrịtừiterable.
Randomseekinginafile(tìmkiếmngẫunhiên)
Bạncóthểsinhngẫunhiênnộidungtrongtậptinsửdụngseek().Nósẽcóhaichiềuoffsetvàwhence.BạncóthểđọcthêmtronghelpcủaPython.
seek(...)seek(offset[,whence])->None.Dichuyênvịchịcủatậptinmới.
Vídụ
LậptrìnhPythoncơbản
42Xửlýtậptin
>>>fobj=open('/tmp/tempfile','w')
>>>fobj.write('0123456789abcdef')
>>>fobj.close()
>>>fobj=open('/tmp/tempfile')
>>>fobj.tell()#tellustheoffsetposition
0L
>>>fobj.seek(5)#Goto5thbyte
>>>fobj.tell()
5L
>>>fobj.read(1)#Read1byte
'5'
>>>fobj.seek(-3,2)#goto3rdbytefromtheend
>>>fobj.read()#Readtilltheendofthefile
'def'
Đếmdấucách,tabvàdòngmớitrongtậptin.
Chúngtasẽviếtmộtchươngtrìnhđếmdấucách,tabs,vàdòngtrongmộttậptincósẵn.
#!/usr/bin/envpython
importos
importsys
defparse_file(path):
"""
Parsesthetextfileinthegivenpathandreturnsspace,tab&newline
details.
:argpath:Pathofthetextfiletoparse
:return:Atuplewithcountofspacaes,tabsandlines.
"""
fd=open(path)
i=0
spaces=0
tabs=0
fori,lineinenumerate(fd):
spaces+=line.count('')
tabs+=line.count('\t')
#Nowclosetheopenfile
fd.close()
#Returntheresultasatuple
returnspaces,tabs,i+1
defmain(path):
"""
Functionwhichprintscountsofspaces,tabsandlinesinafile.
:argpath:Pathofthetextfiletoparse
:return:TrueifthefileexitsorFalse.
"""
ifos.path.exists(path):
spaces,tabs,lines=parse_file(path)
print"Spaces%d.tabs%d.lines%d"%(spaces,tabs,lines)
returnTrue
else:
returnFalse
if__name__=='__main__':
iflen(sys.argv)>1:
main(sys.argv[1])
else:
sys.exit(-1)
sys.exit(0)
Bạncóthểthấychúngtacóhaihàmtrongchươngtrình,hàmchínhvàhàmcótênlàparse_filenơilàchúngtaxửlýtậptinvàtrảvềkếtquảchohàmchính.Bằngcáchchianhỏchứcnănggiúpchúngtatổchứcđượccodevàcóthểviếttestcase
LậptrìnhPythoncơbản
43Xửlýtậptin
dễdànghơn.
Sửdụngstatement
Trongthựctếchúngtanênsửdụngstatement.Chúngsẽđảmnhiệmviệcđóngtậptinchobạn.
>>>withopen('setup.py')asfobj:
...forlineinfobj:
...printline,
...
#!/usr/bin/envpython
"""Factorialproject"""
fromsetuptoolsimportfind_packages,setup
setup(name='factorial',
version='0.1',
description="Factorialmodule.",
long_description="Atestmoduleforourbook.",
platforms=["Linux"],
author="KushalDas",
author_email="[email protected]",
url="http://pymbook.readthedocs.org/en/latest/",
license="http://www.gnu.org/copyleft/gpl.html",
packages=find_packages()
)
Chúccácbạnthànhcông!
LậptrìnhPythoncơbản
44Xửlýtậptin
TrongphầnnàychúngtasẽnghiêncứuvềexceptiontrongPythonvàlàmsaođềxửlýtrongtrongcode.
Mộtsốlỗixảyratrongquátrìnhchạychươngtrìnhđượcgọilàexception.Mỗimộtexceptionđềusinhramộtsốthôngbáolỗi.
NameError
Khichúngtabắtđầuviếtcode,đâysẽlàhầuhếtcácexceoptionmàcácbạncóthểtìmthấy.Vídụnhưchúngtacốgắngtruycậpvàobiếnvànóchưađượckhaibáo.
>>>printkushal
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
NameError:name'kushal'isnotdefined
Dòngcuốicùngchứanộidungcụthểcủathôngbáolỗi,phầncònlạiđưarathôngbáocụthểlàmthếnàođểnóxảyra(hoặcnhữnggìgâyrangoạilệ).
TypeError
TypeErrorlàmộttrongcáclỗiphổbiếnnhấtxuấthiện.Nóthườngxuấthiệnvớicácchươngtrìnhliênquanđếnkiểudữliệu.Vídụ:
>>>print1+"kushal"
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
TypeError:unsupportedoperandtype(s)for+:'int'and'str'
Làmsaođểxửlýexceptions?
Chúngtasửdụngcúpháptry...exceptđểxửlýexception.Cúphápcơbảnnhưsau:
try:
statementstobeinsidetryclause
statement2
statement3
...
exceptExceptionName:
statementstoevaluatedincaseofExceptionNamehappens
Nólàmtheocácbướcsau:
Firstalllinesbetweentryandexceptstatements.
IfExceptionNamehappensduringexecutionofthestatementsthenexceptclausestatementsexecute
Ifnoexceptionhappensthenthestatementsinsideexceptclausedoesnotexecute.
IftheExceptionisnothandledintheexceptblockthenitgoesoutoftryblock.
Vídụsausẽthựchiệnkịchbảntrên.
>>>defget_number():
Exceptions
LậptrìnhPythoncơbản
45Exceptions
..."Returnsafloatnumber"
...number=float(raw_input("Enterafloatnumber:"))
...returnnumber
...
>>>
>>>whileTrue:
...try:
...printget_number()
...exceptValueError:
...print"Youenteredawrongvalue"
...
Enterafloatnumber:45.0
45.0
Enterafloatnumber:24,0
Youenteredawrongvalue
Enterafloatnumber:Traceback(mostrecentcalllast):
File"<stdin>",line3,in<module>
File"<stdin>",line3,inget_number
KeyboardInterrupt
Tronglầnnhậpgiátrịđầutiênchúngtanhậpvàosốthực,vàsauđóinnóramànhình,sauđóchúngtasẽđưavàodấuphẩytrongsốthực,vàsẽcólỗikhichúngtalàmnhưvậy.
Tronglầnthứ3chúngtaấntổhợpphímctrl+CsẽxuấthiệnmộtlỗilàKeyboardInterrupt,sẽkhôngcómộtexceptionnào.
Sẽcómộtcáchđểtổnghợplạitấtcảcácexceptionđó.Vídụcácbạncóthểxemdướiđây:
>>>try:
...raw_input()#PressCtrl+cforaKeyboardInterrupt
...except:
...print"UnknownException"
...
UnknownException
Raisingexceptions
>>>raiseValueError("Avalueerrorhappened.")
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
ValueError:Avalueerrorhappened.
Chúngtacóthểbắtexceptionnhưmộtexceptionbìnhthường.
>>>try:
...raiseValueError("Avalueerrorhappened.")
...exceptValueError:
...print"ValueErrorinourcode."
...
ValueErrorinourcode.
Usingfinallyforcleanup
Nếuchúngtamuốncómộtvàibáocáimỗikhithựchiệntrongmọihoàncảnh,chúngtacóthểsửdụngmệnhđề,nósẽchạytrướckhikếtthúcbiểuthức.
>>>try:
LậptrìnhPythoncơbản
46Exceptions
...fobj=open("hello.txt","w")
...res=12/0
...exceptZeroDivisionError:
...print"Wehaveanerrorindivision"
...finally:
...fobj.close()
...print"Closingthefileobject."
...
Wehaveanerrorindivision
Closingthefileobject.
Trongvídụnàychúngtađảmbảochắcchắnrằngtậptinđượcmở,đóng.Chúcbạnthànhcông!
LậptrìnhPythoncơbản
47Exceptions
Chươngtrìnhđầutiên.
Đểviếtmộtchươngtrìnhđầutiên,bạncầnbiếtcúphápcủaclasstrongchươngtrìnhnhưsau:
classnameoftheclass(parent_class):
statement1
statement2
statement3
Trongstatementbạncóthểviếtbấtcứđiềugì,bạncóthểđịnhnghĩahàm(cáimàchúngtagọilàmethodcủamộtclass)
>>>classMyClass(object):
...a=90
...b=88
...
>>>p=MyClass()
>>>p
<__main__.MyClassinstanceat0xb7c8aa6c>
TrongvídụtrênchúngtacóthểthấyđầutiênchúngtasẽkhaibáomộtclasscótênlàMyClass,chúngtasẽviếtmộtvàibiểuthứcnàođótrongclassđó.Saukhiclassđượcđịnhnghĩa,chúngtasẽtạomộtobjectpcủaclassMyClass.
>>>dir(p)
['__doc__','__module__','a','b']
bạncóthểnhìnthấybiếnavàbtrongnó.initmethod
initislàmộtmethodđặcbiệttrongclassPython,nólàmộtphươngthứcđểkhởitạomộtlớp.Trongvídụsausẽsửdụngnó.
classStudent(object):
"""
Returnsa```Student```objectwiththegivenname,branchandyear.
"""
def__init__(self,name,branch,year):
self.name=name
self.branch=branch
self.year=year
print"Astudentobjectiscreated"
defprint_details(self):
"""
Printsthedetailsofthestudent.
"""
print"Name:",self.name
print"Branch:",self.branch
print"Year:",self.year
initiscalledwheneveranobjectoftheclassisconstructed.Thatmeanswheneverwewillcreateastudentobjectwewillseethemessage“Astudentobjectiscreated”intheprompt.Youcanseethefirstargumenttothemethodisself.Itisaspecialvariablewhichpointstothecurrentobject(likethisinC++).Theobjectispassedimplicitlytoeverymethodavailableinit,butwehavetogetitexplicitlyineverymethodwhilewritingthemethods.Exampleshownbelow.
Class
LậptrìnhPythoncơbản
48Class
>>>std1=Student()
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
TypeError:__init__()takesexactly4arguments(1given)
>>>std1=Student('Kushal','CSE','2005')
Astudentobjectiscreated
InthisexampleatfirstwetriedtocreateaStudentobjectwithoutpassinganyargumentandPythoninterpretercomplainedthatittakesexactly4argumentsbutreceivedonlyone(self).Thenwecreatedanobjectwithproperargumentvaluesandfromthemessageprinted,onecaneasilyunderstandthatinitmethodwascalledastheconstructormethod.
Nowwearegoingtocallprint_details()method.
>>>std1.print_details()
Name:Kushal
Branch:CSE
Year:2005
Inheritance
Ingeneralwehumanbeingsalwaysknowaboutinheritance.Inprogrammingitisalmostthesame.Whenaclassinheritsanotherclassitinheritsallfeatures(likevariablesandmethods)oftheparentclass.Thishelpsinreusingcodes.
InthenextexamplewefirstcreateaclasscalledPersonandcreatetwosub-classesStudentandTeacher.AsbothoftheclassesareinheritedfromPersonclasstheywillhaveallmethodsofPersonandwillhavenewmethodsandvariablesfortheirownpurpose.student_teacher.py
#!/usr/bin/envpython
classPerson(object):
"""
Returnsa```Person```objectwithgivenname.
"""
def__init__(self,name):
self.name=name
defget_details(self):
"Returnsastringcontainingnameoftheperson"
returnself.name
classStudent(Person):
"""
Returnsa```Student```object,takes3arguments,name,branch,year.
"""
def__init__(self,name,branch,year):
Person.__init__(self,name)
self.branch=branch
self.year=year
defget_details(self):
"Returnsastringcontainingstudent'sdetails."
return"%sstudies%sandisin%syear."%(self.name,self.branch,self.year)
classTeacher(Person):
"""
Returnsa```Teacher```object,takesalistofstrings(listofpapers)as
argument.
"""
def__init__(self,name,papers):
Person.__init__(self,name)
self.papers=papers
defget_details(self):
LậptrìnhPythoncơbản
49Class
return"%steaches%s"%(self.name,','.join(self.papers))
person1=Person('Sachin')
student1=Student('Kushal','CSE',2005)
teacher1=Teacher('Prashad',['C','C++'])
printperson1.get_details()
printstudent1.get_details()
printteacher1.get_details()
Kếtquảnhưsau:
$./student_teacher.py
Sachin
KushalstudiesCSEandisin2005year.
PrashadteachesC,C++
InthisexampleyoucanseehowwecalledtheinitmethodoftheclassPersoninbothStudentandTeacherclasses’initmethod.Wealsoreimplementedget_details()methodofPersonclassinbothStudentandTeacherclass.So,whenwearecallingget_details()methodontheteacher1objectitreturnsbasedontheobjectitself(whichisofteacherclass)andwhenwecallget_details()onthestudent1orperson1objectitreturnsbasedonget_details()methodimplementedinit’sownclass.MultipleInheritance
Oneclasscaninheritmorethanoneclasses.Itgetsaccesstoallmethodsandvariablesoftheparentclasses.Thegeneralsyntaxis:
classMyClass(Parentclass1,Parentclass2,...):
def__init__(self):
Parentclass1.__init__(self)
Parentclass2.__init__(self)
...
...
Deletinganobject
Aswealreadyknowhowtocreateanobject,nowwearegoingtoseehowtodeleteanPythonobject.Weusedelforthis.
>>>s="Iloveyou"
>>>dels
>>>s
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
NameError:name's'isnotdefined
delactuallydecreasesreferencecountbyone.Whenthereferencecountofanobjectbecomeszerothegarbagecollectorwilldeletethatobject.GettersandsettersinPython
Onesimpleanswer,don’t.Ifyouarecomingfromotherlanguages(readJava),youwillbetemptedtousegettersorsettersinallyourclasses.Pleasedon’t.Justusetheattributesdirectly.Thefollowingshowsadirectexample.
>>>classStudent(object):
...def__init__(self,name):
...self.name=name
...
>>>std=Student("KushalDas")
>>>printstd.name
LậptrìnhPythoncơbản
50Class
KushalDas
>>>std.name="Python"
>>>printstd.name
Python
Properties
Ifyouwantmorefinetunedcontroloverdataattributeaccess,thenyoucanuseproperties.Inthefollowingexampleofabankaccount,wewillmakesurethatnoonecansetthemoneyvaluetonegativeandalsoapropertycalledinrwillgiveustheINRvaluesofthedollarsintheaccount.
#!/usr/bin/envpython
classAccount(object):
"""TheAccountclass,
Theamountisindollars.
"""
def__init__(self,rate):
self.__amt=0
self.rate=rate
@property
defamount(self):
"Theamountofmoneyintheaccount"
returnself.__amt
@property
definr(self):
"GivesthemoneyinINRvalue."
returnself.__amt*self.rate
@amount.setter
defamount(self,value):
ifvalue<0:
print"Sorry,nonegativeamountintheaccount."
return
self.__amt=value
if__name__=='__main__':
acc=Account(61)#Basedontoday'svalueofINR:(
acc.amount=20
print"Dollaramount:",acc.amount
print"InINR:",acc.inr
acc.amount=-100
print"Dollaramount:",acc.amount
Kếtquảnhưsau:
$pythonproperty.py
Dollaramount:20
InINR:1220
Sorry,nonegativeamountintheaccount.
Dollaramount:20
LậptrìnhPythoncơbản
51Class