Personal tools
You are here: Home CDAT Tips and Tricks Python Tips Functions in python.
Document Actions

Functions in python.

by Renata McCoy last modified 2007-05-08 10:47

Goal: Learn about functions in python.

 
A function can be created using the def statement as shown below.
def myadd(a, b):
c = a*10 + b
return c
Note once again that the statements inside the function are indented after the "def" statement. To invoke the function we do the following:
addvalue = myadd(2, 5)
It is possible to return multiple values using comma separated names in the return statement inside the function.
def myaddsub(a, b):
c = a*10 + b
d = a*10 - b
return c, d

In this case the function is invoked as follows:

addvalue, subvalue = myaddsub(2, 5)
The function definition can also be done in a way such that default values for input parameters can be set.

def myaddsub(a, b, base=10):
c = a*base + b
d = a*base - b
return c, d
Then, when you need base to take a different value than the default 10, you can:
addvalue, subvalue = myaddsub(2, 5, base=2)


Powered by Plone