Python Functions

Introduction

  • Python does not have separate header files. It's simple to declare a function:
  • The keyword def introduces a function definition.
def functionExample(params):
  • The function doesn't define a return datatype. return without an expression argument returns None.
  • The arguments do not need datatypes.

Documenting Functions

You can document a Python function by giving it a doc string. Doc strings are not mandatory but useful because they document the function.
Example:

del functionExample(params):
    """Build a connection string from a dictionary of parameters.
 
    Returns string."""

Defining Functions

Default Argument Values

  • You can specify a default value for one or more arguments. This way the function can be called with fewer arguments.

Keyword Arguments

  • Functions can be called using keyword arguments of the form {{keyword = value}.

Arbitrary Argument Lists

  • Functions that can be called with an arbitrary number of arguments.
  • These arguments will be wrapped up in a tuple.

Variable number of parameters

A function can take additional optional arguments by prefixing the last parameter with an * (asterix). Optional arguments are then available in the tuple referenced by this parameter.

Examples

  • A Python function can return multiple values by returning a tuple.
>>> def quadcube (x):
...     return x**2, x**3
... 
>>> a, b = quadcube(3)
>>> print a
9
>>> print b
27
  • Fibonacci series 1
def fib1(n):
        if n == 0:
                return 0
        elif n == 1:
                return 1
        else:
                return fib1(n-1) + fib1(n-2)
  • Fibonacci series 2
def fib(n):
        a, b = 0, 1
        while b < n:
                print b
                a,b = b, a+b

Dynamic Typing

  • A function can examine its own arguments and do different things depending on their types.

Example

>>> from types import *
>>> 
>>> def what (x):
...     if type(x) == IntType:
...             print "This is an int."
...     else:
...             print "This is something else."
... 
>>> what(4)
This is an int.
>>> 
>>> what("4")
This is something else.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.