Académique Documents
Professionnel Documents
Culture Documents
Advertisements
PreviousPage NextPage
PythonOverview:
Pythonisahighlevel,interpreted,interactiveandobjectorientedscriptinglanguage.
PythonisInterpreted
PythonisInteractive
PythonisObjectOriented
PythonisBeginner'sLanguage
PythonwasdevelopedbyGuidovanRossuminthelateeightiesandearlyninetiesattheNationalResearchInstituteforMathematics
andComputerScienceintheNetherlands.
Python'sfeaturehighlightsinclude:
Easytolearn
Easytoread
Easytomaintain
Abroadstandardlibrary
InteractiveMode
Portable
Extendable
Databases
GUIProgramming
Scalable
GettingPython:
Themostuptodateandcurrentsourcecode,binaries,documentation,news,etc.isavailableattheofficialwebsiteofPython:
PythonOfficialWebsite:https://www.python.org/
You can download the Python documentation from the following site. The documentation is available in HTML, PDF, and PostScript
formats.
PythonDocumentationWebsite:www.python.org/doc/
FirstPythonProgram:
InteractiveModeProgramming:
Invokingtheinterpreterwithoutpassingascriptfileasaparameterbringsupthefollowingprompt:
root# python
Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more info.
>>>
TypethefollowingtexttotherightofthePythonpromptandpresstheEnterkey:
Thiswillproducefollowingresult:
Hello, Python!
PythonIdentifiers:
APythonidentifierisanameusedtoidentifyavariable,function,class,module,orotherobject.AnidentifierstartswithaletterAtoZ
oratozoranunderscore(_)followedbyzeroormoreletters,underscores,anddigits(0to9).
Pythondoesnotallowpunctuationcharacterssuchas@,$,and%withinidentifiers.Pythonisacasesensitiveprogramminglanguage.
ThusManpowerandmanpoweraretwodifferentidentifiersinPython.
HerearefollowingidentifiernamingconventionforPython:
Classnamesstartwithanuppercaseletterandallotheridentifierswithalowercaseletter.
Startinganidentifierwithasingleleadingunderscoreindicatesbyconventionthattheidentifierismeanttobeprivate.
Startinganidentifierwithtwoleadingunderscoresindicatesastronglyprivateidentifier.
Iftheidentifieralsoendswithtwotrailingunderscores,theidentifierisalanguagedefinedspecialname.
ReservedWords:
The following list shows the reserved words in Python. These reserved words may not be used as constant or variable or any other
identifiernames.
assert finally or
def if return
elif in while
else is with
LinesandIndentation:
OneofthefirstcaveatsprogrammersencounterwhenlearningPythonisthefactthattherearenobracestoindicateblocksofcodefor
classandfunctiondefinitionsorflowcontrol.Blocksofcodearedenotedbylineindentation,whichisrigidlyenforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. Both
blocksinthisexamplearefine:
if True:
print "True"
else:
print "False"
However,thesecondblockinthisexamplewillgenerateanerror:
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
MultiLineStatements:
StatementsinPythontypicallyendwithanewline.Pythondoes,however,allowtheuseofthelinecontinuationcharacter(\)todenote
thatthelineshouldcontinue.Forexample:
total = item_one + \
item_two + \
item_three
Statementscontainedwithinthe[],{},or()bracketsdonotneedtousethelinecontinuationcharacter.Forexample:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
QuotationinPython:
Pythonacceptssingle('),double(")andtriple('''or""")quotestodenotestringliterals,aslongasthesametypeofquotestartsand
endsthestring.
Thetriplequotescanbeusedtospanthestringacrossmultiplelines.Forexample,allthefollowingarelegal:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
CommentsinPython:
Ahashsign(#)thatisnotinsideastringliteralbeginsacomment.Allcharactersafterthe#anduptothephysicallineendarepartof
thecomment,andthePythoninterpreterignoresthem.
#!/usr/bin/python
# First comment
print "Hello, Python!"; # second comment
Thiswillproducefollowingresult:
Hello, Python!
Acommentmaybeonthesamelineafterastatementorexpression:
Youcancommentmultiplelinesasfollows:
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
UsingBlankLines:
Alinecontainingonlywhitespace,possiblywithacomment,isknownasablankline,andPythontotallyignoresit.
Inaninteractiveinterpretersession,youmustenteranemptyphysicallinetoterminateamultilinestatement.
MultipleStatementsonaSingleLine:
Thesemicolon()allowsmultiplestatementsonthesinglelinegiventhatneitherstatementstartsanewcodeblock.Hereisasample
snipusingthesemicolon:
MultipleStatementGroupsasSuites:
GroupsofindividualstatementsmakingupasinglecodeblockarecalledsuitesinPython.
Compoundorcomplexstatements,suchasif,while,def,andclass,arethosewhichrequireaheaderlineandasuite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which
makeupthesuite.
Example:
if expression :
suite
elif expression :
suite
else :
suite
PythonVariableTypes:
Variablesarenothingbutreservedmemorylocationstostorevalues.Thismeansthatwhenyoucreateavariableyoureservesome
spaceinmemory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.
Therefore,byassigningdifferentdatatypestovariables,youcanstoreintegers,decimals,orcharactersinthesevariables.
AssigningValuestoVariables:
AssigningValuestoVariables:
Theoperandtotheleftofthe=operatoristhenameofthevariable,andtheoperandtotherightofthe=operatoristhevaluestored
inthevariable.Forexample:
print counter
print miles
print name
StandardDataTypes:
Pythonhasfivestandarddatatypes:
Numbers
String
List
Tuple
Dictionary
PythonNumbers:
Numberobjectsarecreatedwhenyouassignavaluetothem.Forexample:
var1 = 1
var2 = 10
Pythonsupportsfourdifferentnumericaltypes:
int(signedintegers)
long(longintegers[canalsoberepresentedinoctalandhexadecimal])
float(floatingpointrealvalues)
complex(complexnumbers)
Herearesomeexamplesofnumbers:
PythonStrings:
StringsinPythonareidentifiedasacontiguoussetofcharactersinbetweenquotationmarks.
Example:
str = 'Hello World!'
PythonLists:
ListsarethemostversatileofPython'scompounddatatypes.Alistcontainsitemsseparatedbycommasandenclosedwithinsquare
brackets([]).
#!/usr/bin/python
PythonTuples:
Atupleisanothersequencedatatypethatissimilartothelist.Atupleconsistsofanumberofvaluesseparatedbycommas.Unlike
lists,however,tuplesareenclosedwithinparentheses.
Tuplescanbethoughtofasreadonlylists.
PythonDictionary:
Python'sdictionariesarehashtabletype.TheyworklikeassociativearraysorhashesfoundinPerlandconsistofkeyvaluepairs.
PythonBasicOperators:
Operator Description Example
+ AdditionAddsvaluesoneithersideoftheoperator a+bwillgive30
SubtractionSubtractsrighthandoperandfromlefthandoperand abwillgive10
* MultiplicationMultipliesvaluesoneithersideoftheoperator a*bwillgive200
/ DivisionDivideslefthandoperandbyrighthandoperand b/awillgive2
% ModulusDivideslefthandoperandbyrighthandoperandandreturns b%awillgive0
remainder
** ExponentPerformsexponential(power)calculationonoperators a**bwillgive10tothepower20
// FloorDivisionThedivisionofoperandswheretheresultisthequotientin 9//2isequalto4and9.0//2.0isequalto4.0
whichthedigitsafterthedecimalpointareremoved.
== Checksifthevalueoftwooperandsareequalornot,ifyesthencondition (a==b)isnottrue.
becomestrue.
!= Checksifthevalueoftwooperandsareequalornot,ifvaluesarenotequal (a!=b)istrue.
thenconditionbecomestrue.
= Simpleassignmentoperator,Assignsvaluesfromrightsideoperandstoleft c=a+bwillassignevalueofa+bintoc
sideoperand
+= AddANDassignmentoperator,Itaddsrightoperandtotheleftoperandand c+=aisequivalenttoc=c+a
assigntheresulttoleftoperand
= SubtractANDassignmentoperator,Itsubtractsrightoperandfromtheleft c=aisequivalenttoc=ca
operandandassigntheresulttoleftoperand
*= MultiplyANDassignmentoperator,Itmultipliesrightoperandwiththeleft c*=aisequivalenttoc=c*a
operandandassigntheresulttoleftoperand
/= DivideANDassignmentoperator,Itdividesleftoperandwiththeright c/=aisequivalenttoc=c/a
operandandassigntheresulttoleftoperand
%= ModulusANDassignmentoperator,Ittakesmodulususingtwooperands c%=aisequivalenttoc=c%a
andassigntheresulttoleftoperand
| BinaryOROperatorcopiesabitifitexistsineatheroperand. (a|b)willgive61whichis00111101
^ BinaryXOROperatorcopiesthebitifitissetinoneoperandbutnotboth. (a^b)willgive49whichis00110001
~ BinaryOnesComplementOperatorisunaryandhastheefectof'flipping' (~a)willgive61whichis11000011in2's
bits. complementformduetoasignedbinarynumber.
or CalledLogicalOROperator.Ifanyofthetwooperandsarenonzerothen (aorb)istrue.
thenconditionbecomestrue.
in Evaluatestotrueifitfindsavariableinthespecifiedsequenceandfalse xiny,hereinresultsina1ifxisamemberof
otherwise. sequencey.
is Evaluatestotrueifthevariablesoneithersideoftheoperatorpointtothe xisy,hereisresultsin1ifid(x)equalsid(y).
sameobjectandfalseotherwise.
PythonOperatorsPrecedence
Thefollowingtablelistsalloperatorsfromhighestprecedencetolowest.
Operator Description
** Exponentiation(raisetothepower)
~+ Complement,unaryplusandminus(methodnamesforthelasttwoare+@and@)
*/%// Multiply,divide,moduloandfloordivision
+ Additionandsubtraction
>><< Rightandleftbitwiseshift
& Bitwise'AND'
^| Bitwiseexclusive`OR'andregular`OR'
<=<>>= Comparisonoperators
<>==!= Equalityoperators
=%=/=//==+=|=&=>>=<<=*=**= Assignmentoperators
isisnot Identityoperators
innotin Membershipoperators
noteorand Logicaloperators
Theifstatement:
Thesyntaxoftheifstatementis:
if expression:
statement(s)
TheelseStatement:
Thesyntaxoftheif...elsestatementis:
if expression:
statement(s)
else:
statement(s)
TheelifStatement
Thesyntaxoftheif...elifstatementis:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
TheNestedif...elif...elseConstruct
Thesyntaxofthenestedif...elif...elseconstructmaybe:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
ThewhileLoop:
Thesyntaxofthewhilelookis:
while expression:
statement(s)
TheInfiniteLoops:
Youmustusecautionwhenusingwhileloopsbecauseofthepossibilitythatthisconditionneverresolvestoafalsevalue.Thisresults
inaloopthatneverends.Suchaloopiscalledaninfiniteloop.
Aninfiniteloopmightbeusefulinclient/serverprogrammingwheretheserverneedstoruncontinuouslysothatclientprogramscan
communicatewithitasandwhenrequired.
SingleStatementSuites:
Similartotheifstatementsyntax,ifyourwhileclauseconsistsonlyofasinglestatement,itmaybeplacedonthesamelineasthe
whileheader.
Hereisanexampleofaonelinewhileclause:
TheforLoop:
TheforLoop:
Thesyntaxofthelooplookis:
IteratingbySequenceIndex:
Analternativewayofiteratingthrougheachitemisbyindexoffsetintothesequenceitself:
ThebreakStatement:
The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional
breakfoundinC.
Themostcommonuseforbreakiswhensomeexternalconditionistriggeredrequiringahastyexitfromaloop.Thebreakstatement
canbeusedinbothwhileandforloops.
ThecontinueStatement:
The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the
remainingstatementsinthecurrentiterationoftheloopandmovesthecontrolbacktothetopoftheloop.
Thecontinuestatementcanbeusedinbothwhileandforloops.
TheelseStatementUsedwithLoops
Pythonsupportstohaveanelsestatementassociatedwithaloopstatements.
Iftheelsestatementisusedwithaforloop,theelsestatementisexecutedwhentheloophasexhaustediteratingthelist.
Iftheelsestatementisusedwithawhileloop,theelsestatementisexecutedwhentheconditionbecomesfalse.
ThepassStatement:
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to
execute.
The pass statement is a null operation nothing happens when it executes. The pass is also useful in places where your code will
eventuallygo,buthasnotbeenwrittenyet(e.g.,instubsforexample):
#!/usr/bin/python
DefiningaFunction
Youcandefinefunctionstoprovidetherequiredfunctionality.HerearesimplerulestodefineafunctioninPython:
Functionblocksbeginwiththekeyworddeffollowedbythefunctionnameandparentheses(()).
Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these
parentheses.
Thefirststatementofafunctioncanbeanoptionalstatementthedocumentationstringofthefunctionordocstring.
Thecodeblockwithineveryfunctionstartswithacolon(:)andisindented.
Thestatementreturn[expression]exitsafunction,optionallypassingbackanexpressiontothecaller.Areturnstatementwith
noargumentsisthesameasreturnNone.
Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Bydefault,parametershaveapositionalbehavior,andyouneedtoinformtheminthesameorderthattheyweredefined.
Example:
HereisthesimplestformofaPythonfunction.Thisfunctiontakesastringasinputparameterandprintsitonstandardscreen.
CallingaFunction
Definingafunctiononlygivesitaname,specifiestheparametersthataretobeincludedinthefunction,andstructurestheblocksof
code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python
prompt.
Followingistheexampletocallprintme()function:
#!/usr/bin/python
Thiswouldproducefollowingresult:
PythonModules:
AmoduleallowsyoutologicallyorganizeyourPythoncode.Groupingrelatedcodeintoamodulemakesthecodeeasiertounderstand
anduse.
AmoduleisaPythonobjectwitharbitrarilynamedattributesthatyoucanbindandreference.
Simply,amoduleisafileconsistingofPythoncode.Amodulecandefinefunctions,classes,andvariables.Amodulecanalsoinclude
runnablecode.
Example:
The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module,
hello.py
TheimportStatement:
You can use any Python source file as a module by executing an import statement in some other Python source file. importhasthe
followingsyntax:
Whentheinterpreterencountersanimportstatement,itimportsthemoduleifthemoduleispresentinthesearchpath.Asearchpath
isalistofdirectoriesthattheinterpretersearchesbeforeimportingamodule.
Example:
Toimportthemodulehello.py,youneedtoputthefollowingcommandatthetopofthescript:
#!/usr/bin/python
Thiswouldproducefollowingresult:
Hello : Zara
Amoduleisloadedonlyonce,regardlessofthenumberoftimesitisimported.Thispreventsthemoduleexecutionfromhappening
overandoveragainifmultipleimportsoccur.
OpeningandClosingFiles:
TheopenFunction:
Beforeyoucanreadorwriteafile,youhavetoopenitusingPython'sbuiltinopen()function.Thisfunctioncreatesafileobjectwhich
wouldbeutilizedtocallothersupportmethodsassociatedwithit.
Syntax:
file object = open(file_name [, access_mode][, buffering])
Hereisparamtersdetail:
file_name:Thefile_nameargumentisastringvaluethatcontainsthenameofthefilethatyouwanttoaccess.
access_mode: The access_mode determines the mode in which the file has to be opened ie. read, write append etc. A
completelistofpossiblevaluesisgivenbelowinthetable.Thisisoptionalparameterandthedefaultfileaccessmodeisread
(r)
buffering: If the buffering value is set to 0, no buffering will take place. If the buffering value is 1, line buffering will be
performedwhileaccessingafile.Ifyouspecifythebufferingvalueasanintegergreaterthan1,thenbufferingactionwillbe
performedwiththeindicatedbuffersize.Thisisoptionalparamter.
Hereisalistofthedifferentmodesofopeningafile:
Modes Description
r Opensafileforreadingonly.Thefilepointerisplacedatthebeginningofthefile.Thisisthedefaultmode.
rb Opensafileforreadingonlyinbinaryformat.Thefilepointerisplacedatthebeginningofthefile.Thisisthedefaultmode.
r+ Opensafileforbothreadingandwriting.Thefilepointerwillbeatthebeginningofthefile.
rb+ Opensafileforbothreadingandwritinginbinaryformat.Thefilepointerwillbeatthebeginningofthefile.
w Opensafileforwritingonly.Overwritesthefileifthefileexists.Ifthefiledoesnotexist,createsanewfileforwriting.
wb Opensafileforwritingonlyinbinaryformat.Overwritesthefileifthefileexists.Ifthefiledoesnotexist,createsanewfilefor
writing.
w+ Opensafileforbothwritingandreading.Overwritestheexistingfileifthefileexists.Ifthefiledoesnotexist,createsanewfilefor
readingandwriting.
wb+ Opensafileforbothwritingandreadinginbinaryformat.Overwritestheexistingfileifthefileexists.Ifthefiledoesnotexist,
createsanewfileforreadingandwriting.
a Opensafileforappending.Thefilepointerisattheendofthefileifthefileexists.Thatis,thefileisintheappendmode.Ifthefile
doesnotexist,itcreatesanewfileforwriting.
ab Opensafileforappendinginbinaryformat.Thefilepointerisattheendofthefileifthefileexists.Thatis,thefileisintheappend
mode.Ifthefiledoesnotexist,itcreatesanewfileforwriting.
a+ Opensafileforbothappendingandreading.Thefilepointerisattheendofthefileifthefileexists.Thefileopensintheappend
mode.Ifthefiledoesnotexist,itcreatesanewfileforreadingandwriting.
ab+ Opensafileforbothappendingandreadinginbinaryformat.Thefilepointerisattheendofthefileifthefileexists.Thefileopensin
theappendmode.Ifthefiledoesnotexist,itcreatesanewfileforreadingandwriting.
Thefileobjectatrributes:
Onceafileisopenedandyouhaveonefileobject,youcangetvariousinformationrelatedtothatfile.
Hereisalistofallattributesrelatedtofileobject:
Attribute Description
file.closed Returnstrueiffileisclosed,falseotherwise.
file.mode Returnsaccessmodewithwhichfilewasopened.
file.name Returnsnameofthefile.
file.softspace Returnsfalseifspaceexplicitlyrequiredwithprint,trueotherwise.
Theclose()Method:
The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be
done.
fileObject.close();
ReadingandWritingFiles:
Thewrite()Method:
Syntax:
fileObject.write(string);
Theread()Method:
Syntax:
fileObject.read([count]);
FilePositions:
Thetell()methodtellsyouthecurrentpositionwithinthefileinotherwords,thenextreadorwritewilloccuratthatmanybytesfrom
thebeginningofthefile:
Theseek(offset[,from])methodchangesthecurrentfileposition.Theoffsetargumentindicatesthenumberofbytestobemoved.The
fromargumentspecifiesthereferencepositionfromwherethebytesaretobemoved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current position as the
referencepositionandifitissetto2thentheendofthefilewouldbetakenasthereferenceposition.
RenamingandDeletingFiles:
Syntax:
os.rename(current_file_name, new_file_name)
Theremove()Method:
Syntax:
os.remove(file_name)
DirectoriesinPython:
Themkdir()Method:
Youcanusethemkdir()methodoftheosmoduletocreatedirectoriesinthecurrentdirectory.Youneedtosupplyanargumenttothis
method,whichcontainsthenameofthedirectorytobecreated.
Syntax:
os.mkdir("newdir")
Thechdir()Method:
You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the
directorythatyouwanttomakethecurrentdirectory.
Syntax:
os.chdir("newdir")
Thegetcwd()Method:
Thegetcwd()methoddisplaysthecurrentworkingdirectory.
Syntax:
os.getcwd()
Thermdir()Method:
Thermdir()methoddeletesthedirectory,whichispassedasanargumentinthemethod.
Beforeremovingadirectory,allthecontentsinitshouldberemoved.
Syntax:
os.rmdir('dirname')
Handlinganexception:
Ifyouhavesomesuspiciouscodethatmayraiseanexception,youcandefendyourprogrambyplacingthesuspiciouscodeinatry:
block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as
possible.
Syntax:
Hereissimplesyntaxoftry....except...elseblocks:
try:
Do you operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Herearefewimportantpointsabouttheabovementionedsyntax:
A single try statement can have multiple except statements. This is useful when the try block contains statements that may
throwdifferenttypesofexceptions.
Youcanalsoprovideagenericexceptclause,whichhandlesanyexception.
Aftertheexceptclause(s),youcanincludeanelseclause.Thecodeintheelseblockexecutesifthecodeinthetry:blockdoes
notraiseanexception.
Theelseblockisagoodplaceforcodethatdoesnotneedthetry:block'sprotection.
Theexceptclausewithnoexceptions:
Youcanalsousetheexceptstatementwithnoexceptionsdefinedasfollows:
try:
Do you operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
Theexceptclausewithmultipleexceptions:
Youcanalsousethesameexceptstatementtohandlemultipleexceptionsasfollows:
try:
Do you operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
StandardExceptions:
HereisaliststandardExceptionsavailableinPython:StandardExceptions
Thetryfinallyclause:
Youcanuseafinally:blockalongwithatry:block.Thefinallyblockisaplacetoputanycodethatmustexecute,whetherthetry
blockraisedanexceptionornot.Thesyntaxofthetryfinallystatementisthis:
try:
Do you operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
ArgumentofanException:
An exception can have an argument, which is a value that gives additional information about the problem. The contents of the
argumentvarybyexception.Youcaptureanexception'sargumentbysupplyingavariableintheexceptclauseasfollows:
try:
Do you operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
Raisinganexceptions:
Youcanraiseexceptionsinseveralwaysbyusingtheraisestatement.Thegeneralsyntaxfortheraisestatement.
Syntax:
raise [Exception [, args [, traceback]]]
UserDefinedExceptions:
Pythonalsoallowsyoutocreateyourownexceptionsbyderivingclassesfromthestandardbuiltinexceptions.
HereisanexamplerelatedtoRuntimeError.HereaclassiscreatedthatissubclassedfromRuntimeError.Thisisusefulwhenyouneed
todisplaymorespecificinformationwhenanexceptioniscaught.
Inthetryblock,theuserdefinedexceptionisraisedandcaughtintheexceptblock.Thevariableeisusedtocreateaninstanceofthe
classNetworkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
Soonceyoudefinedaboveclass,youcanraiseyourexceptionasfollows:
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
CreatingClasses:
Theclassstatementcreatesanewclassdefinition.Thenameoftheclassimmediatelyfollowsthekeywordclassfollowedbyacolonas
follows:
class ClassName:
'Optional class documentation string'
class_suite
TheclasshasadocumentationstringwhichcanbeaccessviaClassName.__doc__.
Theclass_suiteconsistsofallthecomponentstatements,definingclassmembers,dataattributes,andfunctions.
Creatinginstanceobjects:
Tocreateinstancesofaclass,youcalltheclassusingclassnameandpassinwhateverargumentsits__init__methodaccepts.
Accessingattributes:
Youaccesstheobject'sattributesusingthedotoperatorwithobject.Classvariablewouldbeaccessedusingclassnameasfollows:
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
BuiltInClassAttributes:
EveryPythonclasskeepsfollowingbuiltinattributesandtheycanbeaccessedusingdotoperatorlikeanyotherattribute:
__dict__:Dictionarycontainingtheclass'snamespace.
__doc__:Classdocumentationstring,orNoneifundefined.
__name__:Classname.
__module__:Modulenameinwhichtheclassisdefined.Thisattributeis"__main__"ininteractivemode.
__bases__:Apossiblyemptytuplecontainingthebaseclasses,intheorderoftheiroccurrenceinthebaseclasslist.
DestroyingObjects(GarbageCollection):
Pythondeletesunneededobjects(builtintypesorclassinstances)automaticallytofreememoryspace.TheprocessbywhichPython
periodicallyreclaimsblocksofmemorythatnolongerareinuseistermedgarbagecollection.
Python'sgarbagecollectorrunsduringprogramexecutionandistriggeredwhenanobject'sreferencecountreacheszero.Anobject's
referencecountchangesasthenumberofaliasesthatpointtoitchanges:
Anobject'sreferencecountincreaseswhenit'sassignedanewnameorplacedinacontainer(list,tuple,ordictionary).Theobject's
referencecountdecreaseswhenit'sdeletedwithdel,itsreferenceisreassigned,oritsreferencegoesoutofscope.Whenanobject's
referencecountreacheszero,Pythoncollectsitautomatically.
ClassInheritance:
Insteadofstartingfromscratch,youcancreateaclassbyderivingitfromapreexistingclassbylistingtheparentclassinparentheses
afterthenewclassname:
Thechildclassinheritstheattributesofitsparentclass,andyoucanusethoseattributesasiftheyweredefinedinthechildclass.A
childclasscanalsooverridedatamembersandmethodsfromtheparent.
Syntax:
Derivedclassesaredeclaredmuchliketheirparentclasshowever,alistofbaseclassestoinheritfromaregivenaftertheclassname:
OverridingMethods:
Youcanalwaysoverrideyourparentclassmethods.Onereasonforoverridingparent'smethodsisbecauseyoumaywantspecialor
differentfunctionalityinyoursubclass.
BaseOverloadingMethods:
Followingtablelistssomegenericfunctionalitythatyoucanoverrideinyourownclasses:
SN Method,Description&SampleCall
1 __init__(self[,args...])
Constructor(withanyoptionalarguments)
SampleCall:obj=className(args)
2 __del__(self)
Destructor,deletesanobject
SampleCall:dellobj
3 __repr__(self)
Evaluatablestringrepresentation
SampleCall:repr(obj)
4 __str__(self)
Printablestringrepresentation
SampleCall:str(obj)
5 __cmp__(self,x)
Objectcomparison
SampleCall:cmp(obj,x)
OverloadingOperators:
Suppose you've created a Vector class to represent twodimensional vectors. What happens when you use the plus operator to add
them?MostlikelyPythonwillyellatyou.
Youcould,however,definethe__add__methodinyourclasstoperformvectoraddition,andthentheplusoperatorwouldbehaveas
perexpectation:
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
DataHiding:
Anobject'sattributesmayormaynotbevisibleoutsidetheclassdefinition.Forthesecases,youcannameattributeswithadouble
underscoreprefix,andthoseattributeswillnotbedirectlyvisibletooutsiders:
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
Aregularexpressionisaspecialsequenceofcharactersthathelpsyoumatchorfindotherstringsorsetsofstrings,usingaspecialized
syntaxheldinapattern.RegularexpressionsarewidelyusedinUNIXworld.
ThemodulereprovidesfullsupportforPerllikeregularexpressionsinPython.Theremoduleraisestheexceptionre.errorifanerror
occurswhilecompilingorusingaregularexpression.
Wewouldcovertwoimportantfunctionswhichwouldbeusedtohandleregularexpressions.Butasmallthingfirst:Therearevarious
characters which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with
regularexpressionswewoulduseRawStringsasr'expression'.
ThematchFunction
ThisfunctionattemptstomatchREpatterntostringwithoptionalflags.
Hereisthesyntaxforthisfunction:
Hereisthedescriptionoftheparameters:
Parameter Description
pattern Thisistheregularexpressiontobematched.
string Thisisthestringwhichwouldbesearchedtomatchthepattern
flags YoucanspecifiydifferentflagsusingexclusiveOR(|).Thesearemodifierswhicharelistedinthe
tablebelow.
There.matchfunctionreturnsamatchobjectonsuccess,Noneonfailure.Wewouldusegroup(num)orgroups()functionofmatch
objecttogetmatchedexpression.
MatchObjectMethods Description
group(num=0) Thismethodsreturnsentirematch(orspecificsubgroupnum)
groups() Thismethodreturnallmatchingsubgroupsinatuple(emptyifthereweren'tany)
ThesearchFunction
ThisfunctionsearchforfirstoccurrenceofREpatternwithinstringwithoptionalflags.
Hereisthesyntaxforthisfunction:
Hereisthedescriptionoftheparameters:
Parameter Description
pattern Thisistheregularexpressiontobematched.
string Thisisthestringwhichwouldbesearchedtomatchthepattern
flags YoucanspecifiydifferentflagsusingexclusiveOR(|).Thesearemodifierswhicharelistedinthe
tablebelow.
There.searchfunctionreturnsamatchobjectonsuccess,Noneonfailure.Wewouldusegroup(num)orgroups()functionofmatch
objecttogetmatchedexpression.
MatchObjectMethods Description
group(num=0) Thismethodsreturnsentirematch(orspecificsubgroupnum)
groups() Thismethodreturnallmatchingsubgroupsinatuple(emptyifthereweren'tany)
MatchingvsSearching:
MatchingvsSearching:
Pythonofferstwodifferentprimitiveoperationsbasedonregularexpressions:matchchecksforamatchonlyatthebeginningofthe
string,whilesearchchecksforamatchanywhereinthestring(thisiswhatPerldoesbydefault).
SearchandReplace:
Someofthemostimportantremethodsthatuseregularexpressionsissub.
Syntax:
sub(pattern, repl, string, max=0)
ThismethodreplacealloccurrencesoftheREpatterninstringwithrepl,substitutingalloccurrencesunlessmaxprovided.Thismethod
wouldreturnmodifiedstring.
RegularexpressionModifiersOptionFlags
Regular expression literals may include an optional modifier to control various aspects of matching. The modifier are specified as an
optionalflag.YoucanprovidemultiplemodifiedusingexclusiveOR(|),asshownpreviouslyandmayberepresentedbyoneofthese:
Modifier Description
re.I Performscaseinsensitivematching.
re.L Interpretswordsaccordingtothecurrentlocale.Thisinterpretationaffectsthealphabeticgroup(\wand\W),aswellasword
boundarybehavior(\band\B).
re.M Makes$matchtheendofaline(notjusttheendofthestring)andmakes^matchthestartofanyline(notjustthestartofthe
string).
re.S Makesaperiod(dot)matchanycharacter,includinganewline.
re.U InterpretslettersaccordingtotheUnicodecharacterset.Thisflagaffectsthebehaviorof\w,\W,\b,\B.
re.X Permits"cuter"regularexpressionsyntax.Itignoreswhitespace(exceptinsideaset[]orwhenescapedbyabackslash),and
treatsunescaped#asacommentmarker.
Regularexpressionpatterns:
Exceptforcontrolcharacters,(+?.*^$()[]{}|\),allcharactersmatchthemselves.Youcanescapeacontrolcharacterby
precedingitwithabackslash.
FollowingtableliststheregularexpressionsyntaxthatisavailableinPython.
Pattern Description
^ Matchesbeginningofline.
$ Matchesendofline.
. Matchesanysinglecharacterexceptnewline.Usingmoptionallowsittomatchnewlineaswell.
[...] Matchesanysinglecharacterinbrackets.
[^...] Matchesanysinglecharacternotinbrackets
re* Matches0ormoreoccurrencesofprecedingexpression.
re+ Matches0or1occurrenceofprecedingexpression.
re{n} Matchesexactlynnumberofoccurrencesofprecedingexpression.
re{n,} Matchesnormoreoccurrencesofprecedingexpression.
re{n,m} Matchesatleastnandatmostmoccurrencesofprecedingexpression.
a|b Matcheseitheraorb.
(re) Groupsregularexpressionsandremembersmatchedtext.
(?imx) Temporarilytogglesoni,m,orxoptionswithinaregularexpression.Ifinparentheses,onlythatareais
affected.
(?imx) Temporarilytogglesoffi,m,orxoptionswithinaregularexpression.Ifinparentheses,onlythatareais
affected.
(?:re) Groupsregularexpressionswithoutrememberingmatchedtext.
(?imx:re) Temporarilytogglesoni,m,orxoptionswithinparentheses.
(?imx:re) Temporarilytogglesoffi,m,orxoptionswithinparentheses.
(?#...) Comment.
(?=re) Specifiespositionusingapattern.Doesn'thavearange.
(?!re) Specifiespositionusingpatternnegation.Doesn'thavearange.
(?>re) Matchesindependentpatternwithoutbacktracking.
\w Matcheswordcharacters.
\W Matchesnonwordcharacters.
\s Matcheswhitespace.Equivalentto[\t\n\r\f].
\S Matchesnonwhitespace.
\d Matchesdigits.Equivalentto[09].
\D Matchesnondigits.
\A Matchesbeginningofstring.
\Z Matchesendofstring.Ifanewlineexists,itmatchesjustbeforenewline.
\z Matchesendofstring.
\G Matchespointwherelastmatchfinished.
\b Matcheswordboundarieswhenoutsidebrackets.Matchesbackspace(0x08)wheninsidebrackets.
\B Matchesnonwordboundaries.
\n,\t,etc. Matchesnewlines,carriagereturns,tabs,etc.
\1...\9 Matchesnthgroupedsubexpression.
\10 Matchesnthgroupedsubexpressionifitmatchedalready.Otherwisereferstotheoctalrepresentationofa
charactercode.
RegularexpressionExamples:
Literalcharacters:
Example Description
python Match"python".
Characterclasses:
Example Description
[Pp]ython Match"Python"or"python"
rub[ye] Match"ruby"or"rube"
[aeiou] Matchanyonelowercasevowel
[09] Matchanydigitsameas[0123456789]
[az] MatchanylowercaseASCIIletter
[AZ] MatchanyuppercaseASCIIletter
[azAZ09] Matchanyoftheabove
[^aeiou] Matchanythingotherthanalowercasevowel
[^09] Matchanythingotherthanadigit
SpecialCharacterClasses:
Example Description
. Matchanycharacterexceptnewline
\d Matchadigit:[09]
\D Matchanondigit:[^09]
\s Matchawhitespacecharacter:[\t\r\n\f]
\S Matchnonwhitespace:[^\t\r\n\f]
\w Matchasinglewordcharacter:[AZaz09_]
\W Matchanonwordcharacter:[^AZaz09_]
RepetitionCases:
Example Description
ruby? Match"rub"or"ruby":theyisoptional
ruby* Match"rub"plus0ormoreys
ruby+ Match"rub"plus1ormoreys
\d{3} Matchexactly3digits
\d{3,} Match3ormoredigits
\d{3,5} Match3,4,or5digits
Nongreedyrepetition:
Thismatchesthesmallestnumberofrepetitions:
Example Description
<.*> Greedyrepetition:matches"<python>perl>"
<.*?> Nongreedy:matches"<python>"in"<python>perl>"
Groupingwithparentheses:
Example Description
\D\d+ Nogroup:+repeats\d
(\D\d)+ Grouped:+repeats\D\dpair
([Pp]ython(,)?)+ Match"Python","Python,python,python",etc.
Backreferences:
Thismatchesapreviouslymatchedgroupagain:
Example Description
([Pp])ython&\1ails Matchpython&pailsorPython&Pails
(['"])[^\1]*\1 Singleordoublequotedstring.\1matcheswhateverthe1stgroupmatched.\2matcheswhateverthe
2ndgroupmatched,etc.
Alternatives:
Example Description
python|perl Match"python"or"perl"
rub(y|le)) Match"ruby"or"ruble"
Python(!+|\?) "Python"followedbyoneormore!orone?
Anchors:
Thisneedtospecifymatchposition
Example Description
^Python Match"Python"atthestartofastringorinternalline
Python$ Match"Python"attheendofastringorline
\APython Match"Python"atthestartofastring
Python\Z Match"Python"attheendofastring
\bPython\b Match"Python"atawordboundary
\brub\B \Bisnonwordboundary:match"rub"in"rube"and"ruby"butnotalone
Python(?=!) Match"Python",iffollowedbyanexclamationpoint
Python(?!!) Match"Python",ifnotfollowedbyanexclamationpoint
Specialsyntaxwithparentheses:
Example Description
R(?#comment) Matches"R".Alltherestisacomment
R(?i)uby Caseinsensitivewhilematching"uby"
R(?i:uby) Sameasabove
rub(?:y|le)) Grouponlywithoutcreating\1backreference
PreviousPage NextPage
Advertisements