Chapter 1. Getting To Know Python

Table of Contents

1.1. Diving in

Here is a complete, working Python program.

It probably makes absolutely no sense to you. Don’t worry about that; we’re going to dissect it line by line. But read through it first and see what, if anything, you can make of it.

Example 1.1. odbchelper.py

If you have not already done so, you can download this and other examples used in this book.


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)

Now run this program and see what happens.

Tip
In the Python IDE on Windows, you can run a module with File->Run... (Ctrl-R). Output is displayed in the interactive window.
Tip
In the Python IDE on Mac OS, you can run a module with Python->Run window... (Cmd-R), but there is an important option you must set first. Open the module in the IDE, pop up the module’s options menu by clicking the black triangle in the upper-right corner of the window, and make sure “Run as __main__” is checked. This setting is saved with the module, so you only have to do this once per module.
Tip
On UNIX-compatible systems (including Mac OS X), you can run a module from the command line: python odbchelper.py

Example 1.2. Output of odbchelper.py

server=mpilgrim;uid=sa;database=master;pwd=secret