Sunday, March 9, 2014

Python Study Note: Function

Although Python is an object-oriented programming language, function still play quite large role in data analysis. Usually we need to write a customized function to run some simulation, refine the data set, etc. This post is a brief summary about the Python defined function.

1. How to define a function

    def function_name(x):
        a = 10
        return a

    function_name(x);

There is nothing much to say about how to define a function ... what's more interesting is about how the Python function differentiated from traditional C or other low-level language's functions

2. Default argument value

    def func_name(parm_1, parm_2=10, parm_3='one string'):
        return 0

3. Keyword argument

    func_name(parm_1 = 100)

4. Arbitrary argument list

    def func_name (parm_1, *parm_list, **parm_dict):
        for arg in parm_list:
            print arg
        for kw in parm_dict:
            print kw, ':', parm_dict[kw]

    If the parameter list is already exist as in the "list", one can pass it to the function as:  a = [2,3,4,5]; func_name(parm_1, *a)

5. Lambda expressions
    This one has confused me for months since I started to use Python. Now it is the time to unravel the mistery.
    "Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition."
    It is just a short version for defining function, and it could be quite convenient.

6. Pass parameter by reference or by Value?
    I will refer to this Link, it has a quite detailed discussion on this topic. A rule in thumb would be: if pass parameter as list, then you can directly modify the entries in the list; else, no direct modification.

Now this seems like what I need to know about Python Function. Once a function is written, it is always nice to add comment lines for this function's usage. Here is a guideline about that:

1. The first line should always be a short, concise summary of the object’s purpose.
2. If there are more lines in the documentation string, the second line should be blank
3. Lines that are indented less should not occur

Ex.
---
>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything.
...     """
...     pass
...

No comments:

Post a Comment