January 2000
Intermediate to advanced
672 pages
21h 46m
English
Functions are
defined by the def
statement and use
return
to exit
immediately from the function and return a value. You can return more
than one value by using a tuple or return no value at all:
>>> def double(x): ... return x * 2 ... >>> double(2) 4 >>> def first_and_last(aList): ... return (aList[0], aList[-1]) ... >>> first_and_last(range(5)) (0, 4) >>> def sayHello(): ... print 'hello' ... >>> sayHello() hello >>>
Functions may have default arguments that allow them to be called in certain ways or allow you to initialize variables:
>>> def makeCoffee(size, milk=None, sugar=None):
... order = 'one ' + size + ' coffee'
... if milk and sugar:
... order = order + ' with milk and sugar'
... elif milk:
... order = order + ' with milk'
... elif sugar:
... order = order + ' with sugar'
... else:
... pass # pass means 'do nothing'
... return order
...
>>> makeCoffee('large')
'one large coffee'
>>> makeCoffee('large', 1)
'one large coffee with milk'
>>> makeCoffee('large', milk=0, sugar=1)
'one large coffee with sugar'
>>>Note that you can name the arguments and that both
0 and the special variable
None
are treated as false.
Read now
Unlock full access