An Introduction to Python
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.
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 >> [CONTROL]-D
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 2 3 import posix 4 import string 5 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)
x++;
y--;
z++;
if (m == n || (n != o && o == q)) { j++; }
k++;
q = 0;
while (y--)
*ptr++;
if (m == n) {
x++;
}
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:
#!/usr/local/bin/python from ftplib import FTP ftp = FTP(`ftp.python.org') # 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) ftp.quit()
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
Trending Topics
| You Need A Budget | Feb 10, 2012 |
| The Linux powered LAN Gaming House | Feb 08, 2012 |
| Creating a vDSO: the Colonel's Other Chicken | Feb 06, 2012 |
| Your CMS Is Not Your Web Site | Feb 01, 2012 |
| Casper, the Friendly (and Persistent) Ghost | Jan 31, 2012 |
| Razor-qt 0.4 - Qt based Desktop Environment | Jan 30, 2012 |
- Fun with ethtool
- Parallel Programming with NVIDIA CUDA
- 100% disappointed with the decision to go all digital.
- Readers' Choice Awards 2011
- Linux-Based X Terminals with XDMCP
- Validate an E-Mail Address with PHP, the Right Way
- You Need A Budget
- Why Python?
- The Linux powered LAN Gaming House
- Python for Android






5 min 56 sec ago
4 hours 36 min ago
9 hours 43 min ago
10 hours 43 min ago
20 hours 11 min ago
20 hours 21 min ago
1 day 2 hours ago
1 day 5 hours ago
1 day 6 hours ago
1 day 7 hours ago