Introducing Python © Chirag Wazir 2002 Prev   Index   Next

Functions

Parameters are passed by object reference

Functions must be declared before being called

docstrings can be used to provide in-built documentation & even testing, see __doc__

def fib(n):
    """Return a list containing the Fibonacci series up to n."""
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    return result

print fib(1000)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]

Since parameters are not specifically typed, polymorphic functions are possible using type()

Default argument values:

    def ask_ok(prompt, retries=4)

Keyword arguments:

    def circle(x, y, radius=100, color='blue')
    circle(30, 20, 10, 'red')
    circle(color='green', x=150, y=270)

Variable arguments:

import sys

def fprintf(file, format, *args):
    file.write(format % args)

fprintf(sys.stdout, "%s = %5.3f\n", 'e', 2.71828)
e = 2.718
def show(**keywords):
    for kw in keywords.keys():
        print kw, ':', keywords[kw]

show(a=5, b='hello')
a : 5
b : hello