Scripting Clinic: Curl Up With Python
This full-blown interpreted programming language lets you write large, complex programs without having to mess with compiling and linking.
![]() |
Python has one particular quality that tends to throw new users, especially if they are experienced programmers: Indentation is part of the program logic. Code blocks (functions, conditional statements, and so forth) are defined by their indentation. There are no curly braces or brackets. Indenting starts a block, and unindenting ends it. (Do not mix tabs and spaces, use one or the other exclusively.) This might seem weird, if you're used to using all kinds of punctuation, but it makes for a consistent, readable appearance in all Python scripts and programs, no matter who writes them. And it makes it easy to find code blocks.
The number of spaces does not matter. Most folks use multiples of four; that seems to strike the right balance between readability, and not devoting too much of each line to whitespace.
The Python Interpreter
Like Bash, Python lets you test commands out on the command line before committing them to a script. This opens Python's basic, no-frills command shell:
$ python
Python 2.3.3 (#2, Jan 13 2004, 00:47:05)
[GCC 3.3.3 20040110 (prerelease) (Debian)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
The three angle braces means it is waiting obediently for your command. So let's give it something to do, hit Ctrl+D. Wups! All gone.
Sometimes the program will seem stuck:
>>> somecommand
Python is waiting for some input. If you have nothing to input, hit Ctrl+C to move on:
KeyboardInterrupt
>>>
Python Scripts
The first line in any Python script is
#! /usr/bin/env python
Of course the script must be made executable:
$ chmod +x scriptname.py
Now you can run it like any script or command:
$ ./scriptname.py
Declaring Functions
Functions are the basic building blocks of scripts and programs. Python makes it easy to declare functions. You don't need to declare one until you need it. You don't need header files. And dear to my heart, you don't need to specify a return datatype. That's right, no need to hassle with ints and floats and chars and other horrid things, Python figures out the types for you. You don't need to specify a return value, either. If the function returns a value, Python will print it. If it doesn't, no sweat, it won't. (Technically speaking, it returns a null value.) Use the def keyword to declare a function:
>>> def lamerFunction():
Easy as pie. Any arguments go in the parantheses, separated by commas. End your function declaration with a colon.
- 1
- 2
- Next Page »