Anda di halaman 1dari 12

4.

More Control Flow Tools


Besides the while statement just introduced, Python knows the usual control flow
statementsknownfromotherlanguages,withsometwists.

4.1.

if

Statements

Perhapsthemostwellknownstatementtypeisthe if statement.Forexample:
>>>x=int(raw_input("Pleaseenteraninteger:"))
Pleaseenteraninteger:42
>>>ifx<0:
...x=0
...print'Negativechangedtozero'
...elifx==0:
...print'Zero'
...elifx==1:
...print'Single'
...else:
...print'More'
...
More

There can be zero or more elif parts,andthe else part is optional. Thekeyword elif is
short for else if, and is useful to avoid excessive indentation. An if ... elif ... elif ...
sequenceisasubstituteforthe switch or case statementsfoundinotherlanguages.

4.2.

for

Statements

The for statement in Python differs a bit from what you may be used to in C or Pascal.
Ratherthanalwaysiteratingoveranarithmeticprogressionofnumbers(likeinPascal),or
giving the user the ability to define both the iteration step and halting condition (as C),
Pythons for statement iterates over the items of any sequence (a list or a string), in the
orderthattheyappearinthesequence.Forexample(nopunintended):
>>>#Measuresomestrings:
...words=['cat','window','defenestrate']
>>>forwinwords:
...printw,len(w)
...
cat3
window6
defenestrate12

Ifyouneedtomodifythesequenceyouareiteratingoverwhileinsidetheloop(forexample
toduplicateselecteditems),itisrecommendedthatyoufirstmakeacopy.Iteratingovera
sequence does not implicitly make a copy. The slice notation makes this especially
convenient:

>>>forwinwords[:]:#Loopoveraslicecopyoftheentirelist.
...iflen(w)>6:
...words.insert(0,w)
...
>>>words
['defenestrate','cat','window','defenestrate']

4.3. The

range()

Function

Ifyoudoneedtoiterateoverasequenceofnumbers,thebuiltinfunction range() comesin


handy.Itgenerateslistscontainingarithmeticprogressions:
>>>range(10)
[0,1,2,3,4,5,6,7,8,9]

The given end point is never part of the generated list range(10) generates a list of 10
values,thelegalindicesforitemsofasequenceoflength10.Itispossibletolettherange
startatanothernumber,ortospecifyadifferentincrement(evennegativesometimesthisis
calledthestep):
>>>range(5,10)
[5,6,7,8,9]
>>>range(0,10,3)
[0,3,6,9]
>>>range(10,100,30)
[10,40,70]

Toiterateovertheindicesofasequence,youcancombine range() and len() asfollows:


>>>a=['Mary','had','a','little','lamb']
>>>foriinrange(len(a)):
...printi,a[i]
...
0Mary
1had
2a
3little
4lamb

Inmostsuchcases,however,itisconvenienttousethe enumerate() function,seeLooping


Techniques.

4.4. break and


Loops

continue

Statements, and

else

Clauses on

The break statement,likeinC,breaksoutofthesmallestenclosing for or while loop.


Loopstatementsmayhavean else clauseitisexecutedwhentheloopterminatesthrough

exhaustion of the list (with for ) or when the condition becomes false (with while ), but not
whentheloopisterminatedbya break statement.Thisisexemplifiedbythefollowingloop,
whichsearchesforprimenumbers:
>>>forninrange(2,10):
...forxinrange(2,n):
...ifn%x==0:
...printn,'equals',x,'*',n/x
...break
...else:
...#loopfellthroughwithoutfindingafactor
...printn,'isaprimenumber'
...
2isaprimenumber
3isaprimenumber
4equals2*2
5isaprimenumber
6equals2*3
7isaprimenumber
8equals2*4
9equals3*3

(Yes,thisisthecorrectcode.Lookclosely:the else clausebelongstothe for loop,notthe


if statement.)
Whenusedwithaloop,the else clausehasmoreincommonwiththe else clauseofa try
statement than it does that of if statements: a try statements else clause runs when no
exceptionoccurs,andaloops else clauserunswhenno break occurs.Formoreonthe try
statementandexceptions,seeHandlingExceptions.
The continue statement,alsoborrowedfromC,continueswiththenextiterationoftheloop:
>>>fornuminrange(2,10):
...ifnum%2==0:
...print"Foundanevennumber",num
...continue
...print"Foundanumber",num
Foundanevennumber2
Foundanumber3
Foundanevennumber4
Foundanumber5
Foundanevennumber6
Foundanumber7
Foundanevennumber8
Foundanumber9

4.5.

pass

Statements

The pass statementdoesnothing.Itcanbeusedwhenastatementisrequiredsyntactically


buttheprogramrequiresnoaction.Forexample:
>>>whileTrue:

...pass#Busywaitforkeyboardinterrupt(Ctrl+C)
...

Thisiscommonlyusedforcreatingminimalclasses:
>>>classMyEmptyClass:
...pass
...

Anotherplace pass canbeusedisasaplaceholderforafunctionorconditionalbodywhen


youareworkingonnewcode,allowingyoutokeepthinkingatamoreabstractlevel.The
pass issilentlyignored:
>>>definitlog(*args):
...pass#Remembertoimplementthis!
...

4.6. Defining Functions


WecancreateafunctionthatwritestheFibonacciseriestoanarbitraryboundary:
>>>deffib(n):#writeFibonacciseriesupton
..."""PrintaFibonacciseriesupton."""
...a,b=0,1
...whilea<n:
...printa,
...a,b=b,a+b
...
>>>#Nowcallthefunctionwejustdefined:
...fib(2000)
011235813213455891442333776109871597

Thekeyword def introducesafunctiondefinition.Itmustbefollowedbythefunctionname


andtheparenthesizedlistofformalparameters.Thestatementsthatformthebodyofthe
functionstartatthenextline,andmustbeindented.
Thefirststatementofthefunctionbodycanoptionallybeastringliteralthisstringliteralis
thefunctionsdocumentationstring,ordocstring.(Moreaboutdocstringscanbefoundinthe
section Documentation Strings.) There are tools which use docstrings to automatically
produce online or printed documentation, or to let the user interactively browse through
codeitsgoodpracticetoincludedocstringsincodethatyouwrite,somakeahabitofit.
Theexecutionofafunctionintroducesanewsymboltableusedforthelocalvariablesofthe
function.More precisely, all variable assignments in a function store the value in the local
symbol table whereas variable references first look in the local symbol table, then in the
localsymboltablesofenclosingfunctions,thenintheglobalsymboltable,andfinallyinthe
tableofbuiltinnames.Thus,globalvariablescannotbedirectlyassignedavaluewithina
function(unlessnamedina global statement),althoughtheymaybereferenced.

Theactualparameters(arguments)toafunctioncallareintroducedinthelocalsymboltable
of the called function when it is called thus, arguments are passed using call by value
(where the value is always an object reference, not the value of the object). [1] When a
functioncallsanotherfunction,anewlocalsymboltableiscreatedforthatcall.
Afunctiondefinitionintroducesthefunctionnameinthecurrentsymboltable.Thevalueof
the function name has a type that is recognized by the interpreter as a userdefined
function. This value can be assigned to another name which can then also be used as a
function.Thisservesasageneralrenamingmechanism:
>>>fib
<functionfibat10042ed0>
>>>f=fib
>>>f(100)
01123581321345589

Coming from other languages, you might object that fib is not a function but a procedure
sinceitdoesntreturnavalue.Infact,evenfunctionswithouta return statementdoreturna
value,albeitaratherboringone.Thisvalueiscalled None (itsabuiltinname).Writingthe
value None isnormallysuppressedbytheinterpreterifitwouldbetheonlyvaluewritten.You
canseeitifyoureallywanttousing print :
>>>fib(0)
>>>printfib(0)
None

It is simple to write a function that returns a list of the numbers of the Fibonacci series,
insteadofprintingit:
>>>deffib2(n):#returnFibonacciseriesupton
..."""ReturnalistcontainingtheFibonacciseriesupton."""
...result=[]
...a,b=0,1
...whilea<n:
...result.append(a)#seebelow
...a,b=b,a+b
...returnresult
...
>>>f100=fib2(100)#callit
>>>f100#writetheresult
[0,1,1,2,3,5,8,13,21,34,55,89]

Thisexample,asusual,demonstratessomenewPythonfeatures:
The return statement returns with a value from a function. return without an
expressionargumentreturns None .Fallingofftheendofafunctionalsoreturns None .
Thestatement result.append(a) callsamethodofthelistobject result .A method is a
function that belongs to an object and is named obj.methodname , where obj is some
object (this may be an expression), and methodname is the name of a method that is
defined by the objects type. Different types define different methods. Methods of

differenttypesmayhavethesamenamewithoutcausingambiguity.(Itispossibleto
defineyourownobjecttypesandmethods,usingclasses,seeClasses)Themethod
append() shownintheexampleisdefinedforlistobjectsitaddsanewelementatthe
end of the list. In this example it is equivalent to result = result + [a] , but more
efficient.

4.7. More on Defining Functions


Itisalsopossibletodefinefunctionswithavariablenumberofarguments.Therearethree
forms,whichcanbecombined.

4.7.1. Default Argument Values


Themostusefulformistospecifyadefaultvalueforoneormorearguments.Thiscreatesa
functionthatcanbecalledwithfewerargumentsthanitisdefinedtoallow.Forexample:
defask_ok(prompt,retries=4,complaint='Yesorno,please!'):
whileTrue:
ok=raw_input(prompt)
ifokin('y','ye','yes'):
returnTrue
ifokin('n','no','nop','nope'):
returnFalse
retries=retries1
ifretries<0:
raiseIOError('refusenikuser')
printcomplaint

Thisfunctioncanbecalledinseveralways:
givingonlythemandatoryargument: ask_ok('Doyoureallywanttoquit?')
givingoneoftheoptionalarguments: ask_ok('OKtooverwritethefile?',2)
orevengivingallarguments: ask_ok('OKtooverwritethefile?',2,'Comeon, only yes
orno!')

This example also introduces the


containsacertainvalue.

in

keyword. This tests whether or not a sequence

Thedefaultvaluesareevaluatedatthepointoffunctiondefinitioninthedefiningscope,so
that
i=5
deff(arg=i):
printarg
i=6
f()

willprint 5 .
Important warning: The default value is evaluated only once. This makes a difference
whenthedefaultisamutableobjectsuchasalist,dictionary,orinstancesofmostclasses.
Forexample,thefollowingfunctionaccumulatestheargumentspassedtoitonsubsequent
calls:
deff(a,L=[]):
L.append(a)
returnL
printf(1)
printf(2)
printf(3)

Thiswillprint
[1]
[1,2]
[1,2,3]

If you dont want the default to be shared between subsequent calls, you can write the
functionlikethisinstead:
deff(a,L=None):
ifLisNone:
L=[]
L.append(a)
returnL

4.7.2. Keyword Arguments


Functionscanalsobecalledusingkeywordargumentsoftheform kwarg=value .Forinstance,
thefollowingfunction:
defparrot(voltage,state='astiff',action='voom',type='NorwegianBlue'):
print"Thisparrotwouldn't",action,
print"ifyouput",voltage,"voltsthroughit."
print"Lovelyplumage,the",type
print"It's",state,"!"

accepts one required argument ( voltage ) and three optional arguments ( state , action , and
type ).Thisfunctioncanbecalledinanyofthefollowingways:
parrot(1000)#1positionalargument
parrot(voltage=1000)#1keywordargument
parrot(voltage=1000000,action='VOOOOOM')#2keywordarguments
parrot(action='VOOOOOM',voltage=1000000)#2keywordarguments
parrot('amillion','bereftoflife','jump')#3positionalarguments
parrot('athousand',state='pushingupthedaisies')#1positional,1keyword

butallthefollowingcallswouldbeinvalid:
parrot()#requiredargumentmissing
parrot(voltage=5.0,'dead')#nonkeywordargumentafterakeywordargument
parrot(110,voltage=220)#duplicatevalueforthesameargument
parrot(actor='JohnCleese')#unknownkeywordargument

In a function call, keyword arguments must follow positional arguments. All the keyword
argumentspassedmustmatchoneoftheargumentsacceptedbythefunction(e.g. actor is
not a valid argument for the parrot function), and their order is not important. This also
includes nonoptional arguments (e.g. parrot(voltage=1000) is valid too). No argument may
receiveavaluemorethanonce.Heresanexamplethatfailsduetothisrestriction:
>>>deffunction(a):
...pass
...
>>>function(0,a=0)
Traceback(mostrecentcalllast):
File"<stdin>",line1,in?
TypeError:function()gotmultiplevaluesforkeywordargument'a'

When a final formal parameter of the form **name is present, it receives a dictionary (see
MappingTypesdict)containingallkeywordargumentsexceptforthosecorrespondingto
a formal parameter. This may be combined with a formal parameter of the form *name
(described in the next subsection) which receives a tuple containing the positional
argumentsbeyondtheformalparameterlist.( *name mustoccurbefore **name .)Forexample,
ifwedefineafunctionlikethis:
defcheeseshop(kind,*arguments,**keywords):
print"Doyouhaveany",kind,"?"
print"I'msorry,we'realloutof",kind
forarginarguments:
printarg
print""*40
keys=sorted(keywords.keys())
forkwinkeys:
printkw,":",keywords[kw]

Itcouldbecalledlikethis:
cheeseshop("Limburger","It'sveryrunny,sir.",
"It'sreallyvery,VERYrunny,sir.",
shopkeeper='MichaelPalin',
client="JohnCleese",
sketch="CheeseShopSketch")

andofcourseitwouldprint:
DoyouhaveanyLimburger?
I'msorry,we'realloutofLimburger
It'sveryrunny,sir.

It'sreallyvery,VERYrunny,sir.

client:JohnCleese
shopkeeper:MichaelPalin
sketch:CheeseShopSketch

Note that the list of keyword argument names is created by sorting the result of the
keywordsdictionarys keys() methodbeforeprintingitscontentsifthisisnotdone,theorder
inwhichtheargumentsareprintedisundefined.

4.7.3. Arbitrary Argument Lists


Finally, the least frequently used option is to specify that a function can be called with an
arbitrarynumberofarguments.Theseargumentswillbewrappedupinatuple(seeTuples
andSequences).Beforethevariablenumberofarguments,zeroormorenormalarguments
mayoccur.
defwrite_multiple_items(file,separator,*args):
file.write(separator.join(args))

4.7.4. Unpacking Argument Lists


Thereversesituationoccurswhentheargumentsarealreadyinalistortuplebutneedto
be unpacked for a function call requiring separate positional arguments. For instance, the
builtin range() functionexpectsseparatestartandstoparguments.Iftheyarenotavailable
separately,writethefunctioncallwiththe * operatortounpacktheargumentsoutofalistor
tuple:
>>>range(3,6)#normalcallwithseparatearguments
[3,4,5]
>>>args=[3,6]
>>>range(*args)#callwithargumentsunpackedfromalist
[3,4,5]

Inthesamefashion,dictionariescandeliverkeywordargumentswiththe ** operator:
>>>defparrot(voltage,state='astiff',action='voom'):
...print"Thisparrotwouldn't",action,
...print"ifyouput",voltage,"voltsthroughit.",
...print"E's",state,"!"
...
>>>d={"voltage":"fourmillion","state":"bleedin'demised","action":"VOOM"}
>>>parrot(**d)
Thisparrotwouldn'tVOOMifyouputfourmillionvoltsthroughit.E'sbleedin'demised!

4.7.5. Lambda Expressions

Small anonymous functions can be created with the lambda keyword. This function returns
the sum of its two arguments: lambda a, b: a+b . Lambda functions can be used wherever
function objects are required. They are syntactically restricted to a single expression.
Semantically, they are just syntactic sugar for a normal function definition. Like nested
functiondefinitions,lambdafunctionscanreferencevariablesfromthecontainingscope:
>>>defmake_incrementor(n):
...returnlambdax:x+n
...
>>>f=make_incrementor(42)
>>>f(0)
42
>>>f(1)
43

Theaboveexampleusesalambdaexpressiontoreturnafunction.Anotheruseistopassa
smallfunctionasanargument:
>>>pairs=[(1,'one'),(2,'two'),(3,'three'),(4,'four')]
>>>pairs.sort(key=lambdapair:pair[1])
>>>pairs
[(4,'four'),(1,'one'),(3,'three'),(2,'two')]

4.7.6. Documentation Strings


Thereareemergingconventionsaboutthecontentandformattingofdocumentationstrings.
The first line should always be a short, concise summary of the objects purpose. For
brevity,itshouldnotexplicitlystatetheobjectsnameortype,sincetheseareavailableby
other means (except if the name happens to be a verb describing a functions operation).
Thislineshouldbeginwithacapitalletterandendwithaperiod.
Iftherearemorelinesinthedocumentationstring,thesecondlineshouldbeblank,visually
separatingthesummaryfromtherestofthedescription.Thefollowinglinesshouldbeone
ormoreparagraphsdescribingtheobjectscallingconventions,itssideeffects,etc.
ThePythonparserdoesnotstripindentationfrommultilinestringliteralsinPython,sotools
that process documentation have to strip indentation if desired. This is done using the
followingconvention.Thefirstnonblanklineafterthefirstlineofthestringdeterminesthe
amountofindentationfortheentiredocumentationstring.(Wecantusethefirstlinesinceit
isgenerallyadjacenttothestringsopeningquotessoitsindentationisnotapparentinthe
stringliteral.)Whitespaceequivalenttothisindentationisthenstrippedfromthestartofall
linesofthestring.Lines that are indented less should not occur, but if they occur all their
leading whitespace should be stripped. Equivalence of whitespace should be tested after
expansionoftabs(to8spaces,normally).
Hereisanexampleofamultilinedocstring:

>>>defmy_function():
..."""Donothing,butdocumentit.
...
...No,really,itdoesn'tdoanything.
..."""
...pass
...
>>>printmy_function.__doc__
Donothing,butdocumentit.
No,really,itdoesn'tdoanything.

4.8. Intermezzo: Coding Style


Nowthatyouareabouttowritelonger,morecomplexpiecesofPython,itisagoodtimeto
talk about coding style. Most languages can be written (or more concise, formatted) in
differentstylessomearemorereadablethanothers.Makingiteasyforotherstoreadyour
codeisalwaysagoodidea,andadoptinganicecodingstylehelpstremendouslyforthat.
ForPython,PEP8hasemergedasthestyleguidethatmostprojectsadheretoitpromotes
a very readable and eyepleasing coding style. Every Python developer should read it at
somepointherearethemostimportantpointsextractedforyou:
Use4spaceindentation,andnotabs.
4 spaces are a good compromise between small indentation (allows greater nesting
depth)andlargeindentation(easiertoread).Tabsintroduceconfusion,andarebest
leftout.
Wraplinessothattheydontexceed79characters.
Thishelpsuserswithsmalldisplaysandmakesitpossibletohaveseveralcodefiles
sidebysideonlargerdisplays.
Use blank lines to separate functions and classes, and larger blocks of code inside
functions.
Whenpossible,putcommentsonalineoftheirown.
Usedocstrings.
Use spaces around operators and after commas, but not directly inside bracketing
constructs: a=f(1,2)+g(3,4) .
Name your classes and functions consistently the convention is to use CamelCase for
classesand lower_case_with_underscores forfunctionsandmethods.Alwaysuse self as
the name for the first method argument (see A First Look at Classes for more on
classesandmethods).

Dont use fancy encodings if your code is meant to be used in international


environments.PlainASCIIworksbestinanycase.
Footnotes
[1] Actually,callbyobjectreferencewouldbeabetterdescription,sinceifamutable
objectispassed,thecallerwillseeanychangesthecalleemakestoit(itemsinserted
intoalist).

Anda mungkin juga menyukai