In [4]:
# functions are defined with def and indented
def hello():
    print 'hello'

hello()


hello

In [5]:
# a function accepts zero or more arguments (parameters)
def hello(person):
    print 'hello, ' + person

hello('joe')
hello('stace')


hello, joe
hello, stace

In [6]:
# functions are called by name with a tuple of arguments
def hello(person,greeting):
    print greeting + person

hello('everyone','greetings, ')


greetings, everyone

In [7]:
# arguments can have default values that are used if the caller does not specify
def hello(person,greeting='hello, '):
    print greeting + person

# this function prints something, but does not return a value
a = hello('everyone','goodbye ')
a is None


goodbye everyone
Out[7]:
True

In [8]:
# functions return value(s)
# if a function calls return with no value, None is returned
# if a function "falls off" the end of its definition, None is returned

def addone(x):
    return x + 1

def addn(x,n=1):
    return x + n

def addsub(x,n=1):
    return x + n, x - n

a, b = addsub(7)
a, b


Out[8]:
(8, 6)

In [9]:
# functions are "first-class" objects
## a variable can have a function as a value
## a function can return another function
## a function can be a member of a tuple, list, or the value associated with a 
## dict key

l =[ -4, -2, -3, 8, 0, 4 ]

def sq(x):
    return x**2

sorted(l,key=sq)


Out[9]:
[0, -2, -3, -4, 4, 8]

In [10]:
def call_add_one(fn,x):
    return fn(x) + 1

call_add_one(sq,7)


Out[10]:
50