An Introduction to Python

Python is an extensible, high-level, interpreted, object-oriented programming language. Ready for use in the real world, it's also free.

If you've been programming on a Linux system, you may be coding in C or C++. If you're a systems administrator, you may be programming in perl, Tcl, awk, or one of the various (sh/csh/tsh/bash) shell scripting languages. Maybe you wrote a script to do a particular job, but now find that it doesn't scale up very well. You might be writing C applications, but now wish you didn't have to be bogged down in the low-level details. Or you may simply be intrigued by the possibility of doing high-level, object-oriented programming in a friendly, interpreted environment.

If any of the above applies to your situation, you may be interested in Python. Python is a powerful language for the rapid development of applications. The interpreter is easily extensible, and you may embed your favorite C code as a compiled extension module.

Python is not one of the research languages which seem to get promoted solely for pedagogical reasons. It is possible to do useful coding almost immediately. Python seems to encourage object-oriented programming by clearing the paths, rather than erecting parapets.

Getting Started

To execute the standard hello program, enter the following at the command line:

$ python
Python 1.2 (Jun  3, 1995) [GCC 2.6.3]
Copyright 1991-1995 Sitchting Mathematisch Centrum, Amsterdam
>> print "hello, bruce"
hello, bruce

Most Python programs, though developed incrementally, are executed as a normal script. The next program illustrates some extensions to the original. The new version will identify who you are based on your user account in /etc/passwd.

 1  #!/usr/local/bin/python
3  import posix
4  import string
6  uid = `posix.getuid()`
7  passwd = open(`/etc/passwd')
8  for line in passwd.readlines():
9      rec = string.splitfields(line, `:')
10      if rec[2] == uid:
11          print `hello', rec[0],
12          print `mind if we call you bruce?'
13          break
14  else:
15      print "I can't find you in /etc/passwd"

A line-by-line explanation of the program is as follows:

  • 1 --- Command interpreter to invoke

  • 3-4 --- Import two standard Python modules, posix and regsub.

  • 6 --- Get the user id using the posix module. The enclosing backticks (`) tell Python to assign this value as a string.

  • 7 --- Open the /etc/passwd file in read mode.

  • 8 --- Start a for loop, reading in all the lines of /etc/passwd. Compound statements, such as conditionals, have headers starting with a keyword (if, while, for, try) and end with a colon.

  • 9 --- Each line in /etc/passwd is read and split into array rec[] based on a colon : boundary, using string.splitfields()

  • 10 --- If rec[2] from /etc/passwd matches our call to posix.getuid(), we have identified the user. The first 3 fields of /etc/passwd are: rec[0] = name, rec[1] = password, and rec[2] = uid.

  • 11-12 --- Print the user's account name to stdout. The trailing comma avoids the newline after the output.

  • 13 --- Break the for loop.

  • 14-15 --- Print message if we can't locate the user in /etc/passwd.

The observant reader will note that the control statements lack any form of BEGIN/END keywords or matching braces. This is because the indentation defines the way statements are grouped. Not only does this eliminate the need for braces, but it enforces a readable coding style. No doubt this design feature will turn off a few potential Python hackers, but in practice, it is useful. I can think of numerous times I've spent tracking bugs in C resulting from misinterpreting code that looked like any of these fragments, usually deeply nested:

if (n == 0)

if (m == n || (n != o && o == q)) { j++; }
q = 0;
while (y--)
     if (m == n) {

A coding style enforced in the language definition would have saved me much frustration. Python code written by another programmer is usually very readable.


You might object that we did a lot of work in the program above just to demonstrate Python language features. A better method would be to use the pwd module from the standard Python library:

print `hello', pwd.getpwuid(posix.getuid())[0]

This points out another nicety about Python that is critical for any new language's success: the robustness of its library. As mentioned earlier, you may extend Python by adding a compiled extension module to your personal library, but in most cases you don't have to.

Take the ftplib module for instance. If you wanted to write a Python script to automatically download the latest FAQ, you can simply use ftplib in the following example:

from ftplib import FTP
ftp = FTP(`')     # connect to host
ftp.login()                     # login anonymous
ftp.cwd(`pub/python/doc')       # change directory
ftp.retrlines(`LIST')           # list python/doc
F = open(`python.FAQ', `w')     # file: python.FAQ
ftp.retrbinary(`RETR FAQ', F.write, 1024)

Python has numerous features which make programming fun and restore your perspective of the design objectives. The language encourages you to explore its features by writing experimental functions during program development. Several notable Python features:

  • Automatic memory management. No malloc/free or new/delete is necessary—when objects become unreachable they are garbage-collected.

  • Support for manipulating lists, tuples, and arrays

  • Associative arrays, referred to as “Dictionaries” in Python

  • Modules to encourage reusability. Python comes with a large set of standard modules that may be used as the basis for learning to program in Python.

  • Exception handling

  • Classes