Tuesday, May 6, 2008

Getting started with Python

There are a lot of possibilities for writing and executing Python code. On the Mac it's easy because Python is pre-installed (PyObjC too, if you install the Developer Tools along with Leopard). Despite what python.org says, I haven't felt the need yet to upgrade from what came with the OS installation. For my text editor, I use a free, open-source, syntax-coloring text editor called Smultron. I like it so much I really need to make a donation. Posted below is a snapshot of a simple program in the editor. I named the file 'factorial.py'. The extension '.py' lets Smultron know how to color the code.

Once the file is saved to disk, I just open Terminal, cd to the directory where the file is, and type 'python factorial.py'. Actually, I can type 'python fac' and press tab for command-completion. One nice thing about this setup is I just click to switch between the open file window and the Terminal window. Terminal has command history (up arrow) as well, so it's easy to rerun a script.  I usually use command-K in Terminal to clean up the window if the output is extensive.

As for finding bugs, I use print statements to check the values of things as I go along. Norm Matloff would not approve, but it works for me, even for complex programs. When I'm sure of a segment, I just comment out the print statements. I pasted the output into the code file. It looks like this: