Python is dynamically typed (like VBScript) and strongly typed like C++, Java (because once a variable is declared, its datatype matters)

This basic introduction contains the following:

  • Dictionary

    >>> mydict={"foo":"bar",1:"One","sigma":20.21}
    >>> mydict
    {1: 'One', 'foo': 'bar', 'sigma': 20.210000000000001}

    The entry before the ":" is the key, the entry after the ":" value. Keys can be string, integers etc and so can values. NOTE: Keys are case sensitive!

    To replace the value associated with a key

    >>> mydict["sigma"]=21.0
    >>> mydict
    {1: 'One', 'foo': 'bar', 'sigma': 21.0}

    To remove a key

    >>> del mydict[1]
    >>> mydict
    {'rate': 0.050000000000000003, 'foo': 'bar', 'sigma': 20.210000000000001}

    To clear a dictionary

    >>> mydict.clear()
    >>> mydict

  • Lists

    Lists are ordered. List can include a mix of ,ultiple data types

    >>> li=["a",1,2,"foo",4.5]
    >>> li
    ['a', 1, 2, 'foo', 4.5]

    List elements start at index 0. A negative index of -1 returns the last items of the list. A range can be as li[m:n] where the elments starts at m upto but not including element n. li[:n] would start at the zeroth element. li[m:] would go from m to the last element. li[:] would display the entire list

    >>> li[0]
    >>> li[3]
    >>> li[-1]
    >>> li[1:3]
    [1, 2]

    To extend a list

    >>> li.extend(["bar", 12.1])
    >>> li
    ['a', 1, 2, 'foo', 4.5, 'bar', 12.1]

    To append to a list

    >>> li.append(["foobar", 100])
    >>> li
    ['a', 1, 2, 'foo', 4.5, 'bar', 12.1, ['foobar', 100]]

    The difference between "append" and "extend" is that extend inserts every element from the source list as an element into the destination list, whilst append simply inserts the list object itself

    Insert behaves just like append, just that insert requries to know the index at which the insertion occurs

    >>> li.insert(2,["insertedelement", 10000.22])
    >>> li
    ['a', 1, ['insertedelement', 10000.219999999999], 2, 'foo', 4.5, 'bar', 12.1, ['foobar', 100]]

    Finally, list operators such as "+", "+=" and "*" do the following

    >>> li=["a",1]
    >>> li
    ['a', 1]
    >>> li = li + ["b", 3]
    >>> li
    ['a', 1, 'b', 3]
    >>> li += [4, 5]
    >>> li
    ['a', 1, 'b', 3, 4, 5]
    >>> li = [1,2]*3
    >>> li
    [1, 2, 1, 2, 1, 2]

    "+", "+=" are slower than extend because the construct new lists, extend operates on the existing list

  • Tuples

    Tuples like lists are ordered. Tuples are declared using the round bracket rather than the square ones. Tuples are IMMUTABLE!. Tuples are faster than lists (if the list was meant for read only use only).

    >>> t=("a",1,2,"foo",4.5)
    >>> t
    (a', 1, 2, 'foo', 4.5)

  • Variables

    Single and multiple variable (range) declaration

    >>> h
    Traceback (most recent call last):
    File "", line 1, in
    NameError: name 'h' is not defined
    >>> h=1
    >>> h

    >>> v = ('a', 'b', 'e')
    >>> (x, y, z) = v
    >>> x
    >>> y
    >>> z

    >>> range(7)
    [0, 1, 2, 3, 4, 5, 6]
    >>> MONDAY
    >>> SATURDAY

    Range can take a start parameter and step size too, type range.__doc__ for mode details

  • Formatting

    >>> uid = "sa"
    >>> pwd = "secret"
    >>> print pwd + " is not a good password for " + uid
    secret is not a good password for sa
    >>> print "%s is not a good password for %s" % (pwd, uid)

    The first method is only useful if all the variables are string. For mixed datatypes only the second method will succeed

    >>> print "Today's stock price: %f" % 50.4625
    >>> print "Today's stock price: %.2f" % 50.4625
    >>> print "Change since yesterday: %+.2f" % 1.5

  • Mapping Lists

    One of the most powerful features of Python is the list comprehension, which provides a compact way of mapping a list into another list by applying a function to each of the elements of the list

    >>> li = [1, 9, 8, 4]
    >>> [elem*2 for elem in li]
    [2, 18, 16, 8]
    >>> li
    [1, 9, 8, 4]
    >>> li = [elem*2 for elem in li]
    >>> li
    [2, 18, 16, 8]

    The keys, values, and items Functions

    >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
    >>> params.keys()
    ['pwd', 'database', 'uid', 'server']
    >>> params.values()
    ['secret', 'master', 'sa', 'mpilgrim']
    >>> params.items()
    [('pwd', 'secret'), ('database', 'master'), ('uid', 'sa'), ('server', 'mpilgrim')]

    List comprehension, step-by-step

    >>> params.items()
    [('pwd', 'secret'), ('database', 'master'), ('uid', 'sa'), ('server', 'mpilgrim')]
    >>> [k for k, v in params.items()]
    ['pwd', 'database', 'uid', 'server']
    >>> [v for k, v in params.items()]
    ['secret', 'master', 'sa', 'mpilgrim']
    >>> ["%s=%s" % (k, v) for k, v in params.items()]
    ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim']

  • Functions

    Create a file called (using ActivePython IDE, maybe).

    def buildConnectionString(params):
           """Build a connection string from a dictionary of parameters.
           Returns string."""
           return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
    if __name__ == "__main__":
           myParams = {"server":"mpilgrim", \
                       "database":"master", \
                       "uid":"sa", \
                       "pwd":"secret" \
           print buildConnectionString(myParams)

    The output of will look like this:


    Python functions do not specify the datatype of their return value; they don't even specify whether or not they return a value. In fact, every Python function returns a value; if the function ever executes a return statement, it will return that value, otherwise it will return None, the Python null value.

    Triple quotes signify a multi-line string. Everything between the start and end quotes is part of a single string, Triple quotes signify a multi-line string. Everything between the start and end quotes is part of a single string, including carriage returns and other quote characters. You can use them anywhere, but you'll see them most often used when defining a doc string including carriage returns and other quote characters. You can use them anywhere, but you'll see them most often used when defining a doc string.

  • Indenting Code

    Python functions have no explicit begin or end, and no curly braces to mark where the function code starts and stops. The only delimiter is a colon (:) and the indentation of the code itself.

    Code blocks are defined by their indentation. By "code block", I mean functions, if statements, for loops, while loops, and so forth. Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords. This means that whitespace is significant, and must be consistent. In this example, the function code (including the doc string) is indented four spaces. It doesn't need to be four spaces, it just needs to be consistent. The first line that is not indented is outside the function.

  • The Main Program
Unlike C, C++, Java and the likes, Python uses a trick to run test a module, the if __name__  trick.

A module's __name__ depends on how you're using the module. If you import the module, then __name__ is the module's filename, without a directory path or file extension. But you can also run the module directly as a standalone program, in which case __name__ will be a special default value, __main__.

  • The Import Search Path

    >>> import sys
    >>> sys.path
    ['', 'C:\\WINDOWS\\system32\\', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26\\Lib\\site-packages\\pythonwin', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'W:\\python\\tutorial']
    >>> sys.path.append('C:\\temp')
    >>> sys.path
    ['', 'C:\\WINDOWS\\system32\\', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26\\Lib\\site-packages\\pythonwin', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'W:\\python\\tutorial', 'C:\\temp']

    Make sure you have the directory where you saved in the path. Now execute the following

    >>> import odbchelper
    >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
    >>> print odbchelper.buildConnectionString(params)
    >>> print odbchelper.buildConnectionString.__doc__
    Build a connection string from a dictionary

    Returns string.

  • Joining And Splitting Strings

    >>> dict={"foo":"bar","one":1,"pswd":"secret","uid":"sa"}
    >>> s=";".join(dict)
    >>> s
    >>> s1=";".join("%s=%s" % (k,v) for k, v in dict.items())
    >>> s1

    In the first case, just the keys of the dictionary are joined. Using comprehension, we can get a list of name value pairs in a ";" separated list

    Splitting a String reverses the above join >>> s.split(";")
    ['pswd', 'foo', 'uid', 'one']
    >>> s1.split(";")
    ['pswd=secret', 'foo=bar', 'uid=sa', 'one=1']

    However, note that the list is made up of String elements only