My Octopress Blog

A blogging framework for hackers.

Python Tutorial, Release 2.7: Abridged (Heavily!)

This tutorial is originally written by Guido van Rossum, and edited by Fred
L. Drake, Jr. . It is an excellent one, excluding some specific portions.

I felt the urge to keep a record of all the key points regarding Python, that
i grasped from this tutorial. So here goes..

1. The Python Interpreter
    Interactive mode: Ctrl + D, primary prompt, secondary prompt
    Non-interactive mode: ‘python’ command, sys.argv[ ]
    /usr/lib/python2.6 or /usr/lib/python3.1
2. Executable Python Script
    #! /usr/bin/ python
    $ chmod +x 
3. The  Startup File
    PYTHONSTARTUP environment variable 
    os.path(), os.environ.get(), execfile(), .join()
    sys.ps1, sys.ps2
4. Basics 
    #, numbers, , docstring (“”’ or “”“),
    sequence data types: str, unicode, list, tuple, buffer, xrange
    string (effects ofand “), list  (don’t ever forget slicing!)
    Mechanism of  slicing:
Courtesy: Python Tutorial, Release 2.7
    be wary of short circuit nature (e.g. and)
    if, elif, else, for in , range, break, continue, pass
5. Functions In Python
    def <function_name>(<argument(s)>): body
    call by value, first class, scope
    built-in higher order functions: map, filter, reduce, etc
    default argument values (evaluated only once!)
    keyword arguments: function (arg1, *arg2, **arg3)
                   *arg2  -> receives a tuple, **arg3 -> receives a dictionary
                    positional arguments before keyword arguments
    unpacking argument lists: *list_object or **dictionary_object
    lambda
6. Intermezzo Coding Style
    a, b = 10, 20 is valid (swapping is unimaginably easy!) 
    4-space indentation
    blanklines, comments, docstrings 
    spacing: a = f(1, 2) + g(3, 4) 
    self as name for first method argument
7. Functional Programming Tools
    list comprehension: >>> vec = [2, 4, 6]
                                        >>> 3*x for x in vec if x > 3   
                                        >>> [12, 18]
    del (for lists), push(), pop() and collections.deque (for strings)
    set (use it to eliminate duplicates on the fly !, thanks to Sumith) 
    dictionaries (.append(), .extend(), .keys(), .values(), .items())  
8. Modules 
    import <module_name>, 
    from <module> import <method>
    from <module> import * (not advised)
    the [if__name__ == “__main__”:] clause
    PYTHONPATH, sys.path, dir() function, packages 
9. Input and Output
    regular expressions (regex)
    sys.stdin(), sys.stdout()
    repr(), str(), str.format()
    open(), close(), read(), readline(), readlines(), seek(), write()
    pickling: pickle.dump(), pickle.load()  
10. Error Handling
    try: … except: …, try: … except: … else: …, try: except: finally: …,
    try clause: if functions present, tries inside it too
    else clause: to prevent except from catching the error caused
                          by some other piece of code
    finally clause: always executed
                   1. on leaving the try: except:, 
                   2. when error raised by try: not handled by any except:
                   3. when there is an error in the except: itself       
    class MyClass (Exception): pass
    raise Exception (arguments)
    except Exception as inst: (arguments stored in instance.args),
    with open (’’,’’) as :
11. Classes
     class <class_name>[(<baseclass(es)>)]:pass
     Python classes are objects
     both class and its objects are concrete
     no sense in concept of ‘declaration’
     each function attribute has at least one argument named ’self’
                                                       by convention 
     __init__, __str__, __eq__, __iter__
     isinstance()
12. Mechanism of for
     this idea can be applied to any iterable in Python
Courtesy: Python Tutorial, Release 2.7

13. Concept of Generators
     yield -> return, THEN FREEZE THEN AND THERE UNTIL next()
Courtesy: Python Tutorial, Release 2.7
     “genex” -> generator expression
                           (e.g. generator in a list comprehension.
                               then replace [] with ())
                           >>> sum(i * i for i in range(0, 10))