Till now, we have used various functions - built-in functions, as well as methods inside objects.

It is time to write our own now. Functions in python exist for the same reason that they exist in other languages. Functions provide modularity and reduce code duplication.

A basic function in Python looks like:


In [ ]:
def fnname(parameter_list):
    stmt1
    stmt2
    ...
    stmtN

Functions may take any number of arguments (including None). This is specified in the comma separated parameter list. The "return" statement is used to exit the function, and optionally return a value as a result of the function.


In [1]:
def factorial(n):
    if n>0:
        return n*factorial(n-1)
    return 1

# function usage
print factorial(5)


120

Functions can call themselves - called recursion -- like above !


In [2]:
def sum2(x, y):
    return x + y

print sum2(5,6)


11

Functions can take default arguments:


In [3]:
def sum2(x, y=100):
    return x+y

print sum2(5)


105