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
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]
continue
Statements, and
else
Clauses on
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
4.5.
pass
Statements
...pass#Busywaitforkeyboardinterrupt(Ctrl+C)
...
Thisiscommonlyusedforcreatingminimalclasses:
>>>classMyEmptyClass:
...pass
...
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.
Thisfunctioncanbecalledinseveralways:
givingonlythemandatoryargument: ask_ok('Doyoureallywanttoquit?')
givingoneoftheoptionalarguments: ask_ok('OKtooverwritethefile?',2)
orevengivingallarguments: ask_ok('OKtooverwritethefile?',2,'Comeon, only yes
orno!')
in
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
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.
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!
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')]
>>>defmy_function():
..."""Donothing,butdocumentit.
...
...No,really,itdoesn'tdoanything.
..."""
...pass
...
>>>printmy_function.__doc__
Donothing,butdocumentit.
No,really,itdoesn'tdoanything.