Vous êtes sur la page 1sur 23

PythonQuickGuide

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:

>>> print "Hello, Python!";

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.

and exec not

assert finally or

break for pass

class from print

continue global raise

def if return

del import try

elif in while

else is with

except lambda yield

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:

name = "Madisetti" # This is again comment

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:

import sys; x = 'foo'; sys.stdout.write(x + '\n')

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:

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

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:

int long float complex

10 51924361L 0.0 3.14j

100 0x19323L 15.20 45.j

786 0122L 21.9 9.322e36j

080 0xDEFABCECBDAECBFBAEL 32.3+e18 .876j

0490 535633629843L 90. .6545+0J

0x260 052318172735L 32.54e100 3e+26J

0x69 4721885298529L 70.2E12 4.53e7j

PythonStrings:
StringsinPythonareidentifiedasacontiguoussetofcharactersinbetweenquotationmarks.

Example:
str = 'Hello World!'

print str # Prints complete string


print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 6th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

PythonLists:
ListsarethemostversatileofPython'scompounddatatypes.Alistcontainsitemsseparatedbycommasandenclosedwithinsquare
brackets([]).

#!/usr/bin/python

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd to 4th
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

PythonTuples:
Atupleisanothersequencedatatypethatissimilartothelist.Atupleconsistsofanumberofvaluesseparatedbycommas.Unlike
lists,however,tuplesareenclosedwithinparentheses.

Tuplescanbethoughtofasreadonlylists.

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print tuple # Prints complete list


print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd to 4th
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists

PythonDictionary:
Python'sdictionariesarehashtabletype.TheyworklikeassociativearraysorhashesfoundinPerlandconsistofkeyvaluepairs.

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

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.

> Checksifthevalueofleftoperandisgreaterthanthevalueofrightoperand, (a>b)isnottrue.


ifyesthenconditionbecomestrue.

< Checksifthevalueofleftoperandislessthanthevalueofrightoperand,if (a<b)istrue.


yesthenconditionbecomestrue.

>= Checksifthevalueofleftoperandisgreaterthanorequaltothevalueof (a>=b)isnottrue.


rightoperand,ifyesthenconditionbecomestrue.

<= Checksifthevalueofleftoperandislessthanorequaltothevalueofright (a<=b)istrue.


operand,ifyesthenconditionbecomestrue.

= 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

**= ExponentANDassignmentoperator,Performsexponential(power) c**=aisequivalenttoc=c**a


calculationonoperatorsandassignvaluetotheleftoperand

//= FloorDividionandassignsavalue,Performsfloordivisiononoperatorsand c//=aisequivalenttoc=c//a


assignvaluetotheleftoperand

& BinaryANDOperatorcopiesabittotheresultifitexistsinbothoperands. (a&b)willgive12whichis00001100

| BinaryOROperatorcopiesabitifitexistsineatheroperand. (a|b)willgive61whichis00111101

^ BinaryXOROperatorcopiesthebitifitissetinoneoperandbutnotboth. (a^b)willgive49whichis00110001

~ BinaryOnesComplementOperatorisunaryandhastheefectof'flipping' (~a)willgive61whichis11000011in2's
bits. complementformduetoasignedbinarynumber.

<< BinaryLeftShiftOperator.Theleftoperandsvalueismovedleftbythe a<<2willgive240whichis11110000


numberofbitsspecifiedbytherightoperand.

>> BinaryRightShiftOperator.Theleftoperandsvalueismovedrightbythe a>>2willgive15whichis00001111


numberofbitsspecifiedbytherightoperand.

and CalledLogicalANDoperator.Ifboththeoperandsaretruethenthen (aandb)istrue.


conditionbecomestrue.

or CalledLogicalOROperator.Ifanyofthetwooperandsarenonzerothen (aorb)istrue.
thenconditionbecomestrue.

not CalledLogicalNOTOperator.Usetoreversesthelogicalstateofitsoperand. not(a&&b)isfalse.


IfaconditionistruethenLogicalNOToperatorwillmakefalse.

in Evaluatestotrueifitfindsavariableinthespecifiedsequenceandfalse xiny,hereinresultsina1ifxisamemberof
otherwise. sequencey.

notin Evaluatestotrueifitdoesnotfindavariableinthespecifiedsequenceand xnotiny,herenotinresultsina1ifxisnota


falseotherwise. memberofsequencey.

is Evaluatestotrueifthevariablesoneithersideoftheoperatorpointtothe xisy,hereisresultsin1ifid(x)equalsid(y).
sameobjectandfalseotherwise.

isnot Evaluatestofalseifthevariablesoneithersideoftheoperatorpointtothe xisnoty,hereisnotresultsin1ifid(x)isnot


sameobjectandtrueotherwise. equaltoid(y).

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:

while expression : statement

TheforLoop:
TheforLoop:
Thesyntaxofthelooplookis:

for iterating_var in sequence:


statements(s)

IteratingbySequenceIndex:
Analternativewayofiteratingthrougheachitemisbyindexoffsetintothesequenceitself:

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)):
print 'Current fruit :', fruits[index]

print "Good bye!"

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.

for letter in 'Python': # First Example


if letter == 'h':
break
print 'Current Letter :', letter

var = 10 # Second Example


while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
break

print "Good bye!"

ThecontinueStatement:
The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the
remainingstatementsinthecurrentiterationoftheloopandmovesthecontrolbacktothetopoftheloop.

Thecontinuestatementcanbeusedinbothwhileandforloops.

for letter in 'Python': # First Example


if letter == 'h':
continue
print 'Current Letter :', letter

var = 10 # Second Example


while var > 0:
print 'Current variable value :', var
var = var -1
if var == 5:
continue

print "Good bye!"

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

for letter in 'Python':


if letter == 'h':
pass
print 'This is pass block'
print 'Current Letter :', letter

print "Good bye!"

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.

def printme( str ):


"This prints a passed string into this function"
print str
return

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

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str;
return;

# Now you can call printme function


printme("I'm first call to user defined function!");
printme("Again second call to the same function");

Thiswouldproducefollowingresult:

I'm first call to user defined function!


Again second call to the same function

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

def print_func( par ):


print "Hello : ", par
return

TheimportStatement:
You can use any Python source file as a module by executing an import statement in some other Python source file. importhasthe
followingsyntax:

import module1[, module2[,... moduleN]

Whentheinterpreterencountersanimportstatement,itimportsthemoduleifthemoduleispresentinthesearchpath.Asearchpath
isalistofdirectoriesthattheinterpretersearchesbeforeimportingamodule.

Example:
Toimportthemodulehello.py,youneedtoputthefollowingcommandatthetopofthescript:

#!/usr/bin/python

# Import module hello


import hello

# Now you can call defined function that module as follows


hello.print_func("Zara")

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.

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)

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:

class SubClassName (ParentClass1[, ParentClass2, ...]):


'Optional class documentation string'
class_suite

OverridingMethods:
Youcanalwaysoverrideyourparentclassmethods.Onereasonforoverridingparent'smethodsisbecauseyoumaywantspecialor
differentfunctionalityinyoursubclass.

class Parent: # define parent class


def myMethod(self):
print 'Calling parent method'

class Child(Parent): # define child class


def myMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.myMethod() # child calls overridden method

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:

re.match(pattern, string, flags=0)

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:

re.string(pattern, string, flags=0)

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

Write for us FAQ's Helping Contact


Copyright 2017. All Rights Reserved.

Enter email for newsletter go

Vous aimerez peut-être aussi