O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Functions

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required