Posts Tagged 'Python'

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)
        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.


Learning Common Lisp

Many online sources say that Lisp is a “programmable programming language.” Defining my own macros, being creative, and all that sounded a lot like the Art of Problem Solving spirit. So I decided to learn it. I’m reading Practical Common Lisp by Peter Seibel. The examples make things clear. I can’t say much else because I’m still a novice.

From “If programming languages were cars…”:

Lisp: looks like a car, but with enough tweaking you can turn it into a pretty effective airplane or submarine.

[from Paul Tanimoto:]

Lisp: At first it doesn’t seem to be a car at all, but now and then you spot a few people driving it around. After a point you decide to learn more about it and you realize it’s actually a car that can make more cars. You tell your friends, but they all laugh and say these cars look way too weird. You still keep one in your garage, hoping one day they will take over the streets.

And from Paul Graham, author of On Lisp, another ostensibly good book:

Lisp code looks weird. But those parentheses are there for a reason. They are the outward evidence of a fundamental difference between Lisp and other languages.

For good measure, other entries from “If programming languages were cars…”:

Python is a great beginner’s car; you can drive it without a license. Unless you want to drive really fast or on really treacherous terrain, you may never need another car.

C++ is a souped-up version of the C racing car with dozens of extra features that only breaks down every 250 miles, but when it does, nobody can figure out what went wrong.

I hope I’m getting somewhere with all this.

SPOJ — programming exercises

The Sphere Online Judge has thousands of programming exercises you can try (submit your code and see if it’s correct!) in lots of different languages. I’m only a (extremely) novice python programmer; here is my first submission to exercise 1 (code TEST):

#!/usr/bin/env python

n = 0
while n != 42:
    n = input()
    if n == 42:
    print n

I think it’s a little ugly, with redundant bits of code. Maybe this could actually be done with around three lines rather than six? (Okay maybe not.)