Design, Build, Test, Iterate

Dive Into Python — Chapter 2. Your First Python Program

I’ve been working my tail off for the past two months to finish some schoolwork by a March deadline. It was my fault, but how I hate it! I still have a July deadline that is about to eat me, but you don’t care about that. :)

Because of the helpful distractions, I haven’t been able to do much else, including learning how to program (let alone doing the SPOJ exercises I promised myself to do). Now that I have a little more time, I am going to blog about what I learn from the various online textbooks on Python, C++, and Lisp that I am using. I am reading Dive Into Python by Mark Pilgrim.

Hopefully, this will force me to organize my thoughts more effectively and give me something to review later. So this is the first such entry.

Chapter 1 discusses installing Python on the various OSes… which, for me, was nothing harder than sudo aptitude install python on Ubuntu GNU/Linux.

2.1. Diving In

This first section gives a complete (short) Python program for me to chew on:

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)

2.2. Declaring Functions

Functions are declared using def:

def functionName(arg1, arg2)

The example provided uses CamelCase. I think C uses the same convention, though Lisp uses hyphens.

All functions return a value (its datatype is unspecified), even if it’s None, Python’s null value. Variables as well are not explicitly typed. This is in contrast to C++ and other statically typed languages like Java.

2.3. Documenting Functions

The doc string is defined using triple quotes. The example given:

def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""

The doc string, if present, must be the first thing defined in a function, and it is an attribute of the function.

2.4. Everything Is an Object

A function is an object. We can import a chunk of code as a module with the import command and access its functions, classes, or attributes with module.function. From there we can call a function’s doc string with module.function.__doc__.

Import search paths are defined in sys.path, so we can import the sys module and append our own paths with sys.path.append('/my/new/path').

This [fact that everything is an object] is so important that I’m going to repeat it in case you missed it the first few times: everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.

For now, I’ll just take his word for it.

2.5. Indenting Code

Code blocks are defined by their indentation. It does not matter how much they are indented as long as it is consistent. I think four spaces is the norm.

I don’t know why some people hate it. I love the absence of braces! Here is an example given in the book:

def fib(n):
    print 'n =', n
    if n > 1:
        return n * fib(n - 1)
    else:
        print 'end of the line'
        return 1

Braces are for computers, not for human eyes. This also forces people to organize their code (and in the same way), so reading others’ code isn’t a pain.

2.6. Testing Modules

This section is a tip on using the __name__ attribute to help test modules. If we import a module, __name__ is the module’s filename without the directory path or its file extension. However, if it is run as a standalone program, __name__ holds a special value of __main__.

Thus, we can use an if statement like

if __name__ == "__main__"

to design a test suite that will only run when the module is run as a standalone program and not as an imported module as part of a larger program. This can help with debugging.



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>