« A Book On Career Development | Main | Talented Friends »

September 11, 2005

Hello world. Here is pi. ...or was that Py?

Programming languages are the fundamental tools in a programmer's toolbox. Without them programming computers is next to impossible, requiring the use of machine code. The work I am doing now is mostly in PHP, Perl, and occasionally, Java. I have written a lot of Java code in the past, and Java is my preferred programming language. However, I bump into and ex-colleague, Mick, every few months and, when I do, he badgers me about giving Python a try. This weekend I did.

After the almost mandatory hello world, I decided to write a program to calculate the digits of π. I did something similar to this earlier in the year, when I flirted with Lisp, and I found it useful. It teaches you a lot about how a programming language handles numbers and how easy it is to implement numerical algorithms in that language.

What did I learn? Well, I learned that I like Python. The code (pretty printed here) came to under 70 lines and manipulating numbers was not cumbersome. The numeric operators worked fine with the huge numbers involved, apart from the division operator, /, which returned its results as floats and lost a lot of precision as a result. Fortunately, the integer division operator, //, did what I wanted, so this wasn't a problem. Once I discovered that, writing the program was pretty painless.

The generator feature of Python is really cool. A generator is a function that allows a programmer to lazy instantiate items in a sequence. When called it returns an object that has the iterator interface and calling the next() method on that object gets the next item in the sequence. I used a generator to calculate every second number in the Fibonacci sequence. The same effect could be achieved by creating a class. However, generators are concise, and feel more elegant.

I also discovered that the Python Cookbook is really good. Mick recommended it, so I bought it. I learned lots about generators from Chapter 19 and I expect I will be referring a fair bit to the chapters on XML processing, accessing databases, and string processing, as these activities make up the bulk of my coding tasks at work. I am looking forward to reading Chapter 20, on metaclasses and decorators.

All in all, from this weekend's dabbling, I am impressed with Python. Java might have some competition for my interest. It is a good job the two languages work well together.

Technorati Tags:

Posted by JohnC at September 11, 2005 01:34 AM

Comments