Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
122 views

Programming With Python PDF

Uploaded by

Bogdan Pfa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views

Programming With Python PDF

Uploaded by

Bogdan Pfa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Programming

with
Python
Greg Lindstrom

W
orking in IT is the same no matter languages. In particular, he wanted a language that
the field.Whether it is communica- would be easy to extend for use with other lan-
tions, data brokerage, or any other guages. Today, the Python Software Foundation
field, IT professionals collect, (http://www.python.org/psf) holds Python’s intel-
manipulate, store, and analyze data. At NovaSys lectual property rights.The PSF also runs PyCon,
Health in Little Rock, Arkansas, we process an annual gathering of Python enthusiasts held in
healthcare claims for our customers.This includes Washington, D.C., each spring and oversees a pro-
administering claims for various insurance plans, gram of grants to advance the language.
adjudicating the claims, and paying out benefits.
The data layouts are complex, the competition ANOTHER LANGUAGE?
fierce, and the pace breakneck. Moreover, we Why do we need another programming lan-
must do the job correctly because real people are guage? Because computer science is constantly
on the end of every record advancing with newer, faster hardware, better
Python is a we touch. techniques, and—oh, yeah—the Internet.Twenty
powerful, easy-to- Approximately two years years ago, a new language called C was trying to
ago, contracted third-party replace Assembler, Cobol, and Fortran as the lan-
learn programming vendors performed most of guage of choice in the mainframe world (I know,
language based on NovaSys Health’s data pro- because I was lobbying for it). Today, Python is
cessing offsite.Although we one of several modern languages that uses these
traditional could service our clients venerable languages as a foundation while also
languages but with this arrangement, targeting current operating systems, networks,
being a small shop put us and hardware. (See the “Hello, World!” sidebar
better suited to near the bottom of most for a comparison of several current programming
contractors’ priority lists. languages.)
current operating Implementing even a simple Python provides everything I want in a pro-
systems, networks, change to a file layout could gramming language (simple text and file process-
take weeks and cost thou- ing, network operations like ftp, and a built-in GUI
and hardware. sands of dollars. Because library) and is easy to learn and understand. My
this kept us from respond- 10-year-old daughter programs her mathematics
ing to client requirements in homework in Python (she just wrote a routine to
a time frame acceptable to our senior staff, the
company decided to create an IT department to
process records in house. We chose Python
(http://www.python.org) as the primary program-
Inside
ming language for our IT needs because it is pow-
erful, well supported, and easy to learn. Hello, World!
Guido van Rossum created Python in the early The Zen of Python
1990s.To ensure a clear, easy-to-use language, van
Rossum only used ideas that had proven their
Python Resources
worth over time in other computer programming

10 IT Pro September ❘ October 2005 Published by the IEEE Computer Society 1520-9202/05/$20.00 © 2005 IEEE
Hello, World!
Figure A is a side-by-side listing of the traditional “Hello,World!” program in various languages. In an attempt to be impar-
tial,I took the following examples from Wolfram Rösler’s “Hello World Collection” (http://www.roesler-ac.de/wolfram/hello.htm),
which lists examples of “Hello,World!” in 221 programming languages.

Figure A. Traditional “Hello, World!” program in various languages:


Python (a), Perl (b), Ansi C (c), C++ (d), C# (e), Java (f), and Ruby (g).

# Hello World in Python // Hello World in Microsoft C# (“C-


print ‘Hello, World’ Sharp”).
using System;
(a) class HelloWorld
{
# Hello world in perl public static int Main(String[] args)
print “Hello World!\n”; {
(b) Console.WriteLine(“Hello, World!”);
return 0;
/* Hello World in C, Ansi-style */ }
#include <stdio.h> }
#include <stdlib.h> (e)
int main(void)
{ // Hello World in Java
puts(“Hello World!”); class HelloWorld {
return EXIT_SUCCESS; static public void main( String args[]
} ) {
(c) System.out.println( “Hello World!” );
}
// Hello World in C++ }
#include <iostream.h> (f)
main()
{ # Hello World in Ruby
cout << “Hello World!” << endl; STDOUT << “Hello World!”
return 0; (g)
}
(d)

convert degrees Celsius to degrees Fahrenheit), and last Light & Magic writes, “Python plays a key role in our
year my 12-year-old daughter wrote a routine to help solve production pipeline.Without it, a project the size of Star
word search puzzles. I have taught Python to junior and Wars: Episode II would have been very difficult to pull
senior high school students and am always impressed with off. From crown renderings to batch processing to com-
how quickly they pick up the concepts. positing, Python binds all things together.”
Many contributors to the Python mailing list are part- • Michael Muller, a software consultant, writes, “Python
time programmers using Python in their chosen profes- requires less supporting code. In most other languages,
sions. Python is so easy to learn that you will be writing a significant amount code is needed just to get to the
simple programs in a few hours and using Python at work point of implementing an algorithm. In Python this is
in a day. However, because Python is so easy to learn, many kept to a minimum: It is not necessary to declare vari-
people in the industry do not think of it as a serious lan- ables or types, create iterators and other support objects,
guage (like Perl, C++, or Java). break code into particular files, or write other support-
ing code required in languages like C++ or Java. As a
WHO’S USING PYTHON? result, Python is almost executable pseudo-code” (“At
If you are interested in who is using Python and why, visit Philips, the Semiconductor Line in Fishkill Runs on
the pythonology Web page (http://www. pythonology.org). Python,” Michael Muller, Python Success Stories, Jan.
There you can read Python success stories and quotes from 2003, www.pythonology.com/success&story=philips).
Python users. For example, • “Python has been an important part of Google since the
beginning and remains so as the system grows and
• Tommy Burnette, senior technical director at Industrial evolves,” writes Peter Norvich, director of search quality.

September ❘ October 2005 IT Pro 11


PROGRAMMING LANGUAGES

In addition, Python offers “inter-


The Zen of Python faces to many system calls and
libraries, as well as to various window-
Tim Peters ing systems,” such as X11, Motif, and
Beautiful is better than ugly. Mac. You can use Python to write
Explicit is better than implicit. built-in modules in C or C++, or as “an
Simple is better than complex. extension language for applications
Complex is better than complicated. that need a programmable interface.”
Flat is better than nested. Finally, Python is portable and runs
Sparse is better than dense. on Unix,Windows, OS/2, Mac,Amiga,
Readability counts. and just about any platform with C
Special cases aren’t special enough to break the rules. libraries. Although the Python imple-
Although practicality beats purity. mentation is copyrighted, it is “freely
Errors should never pass silently. usable and distributable, even for com-
Unless explicitly silenced. mercial use.”
In the face of ambiguity, refuse the temptation to guess. The Python development team
There should be one—and preferably only one—obvious way to do it. intentionally adheres to a slow-growth
Although that way may not be obvious at first unless you’re Dutch. policy and thinks through additions to
Now is better than never. the language so thoroughly that even
Although never is often better than *right* now. mathematicians get impatient. For
If the implementation is hard to explain, it’s a bad idea. example, the team debated adding a
If the implementation is easy to explain, it may be a good idea. Boolean data type—a seemingly sim-
Namespaces are one honking great idea—let’s do more of those! ple change—for months because they
wanted to consider all of the use cases.
(Reprinted from http://www.python.org/doc/Humor.html#zen. Used with permission.)
In “The Zen of Python” sidebar,Tim
Peters lists several informal philoso-
phies of the language, which can be
summed up as “simple is better.”
“Today, dozens of Google engineers use Python, and Python coders love simple code—that is, code that
we’re looking for more people with skills in this lan- Geoffrey James’ Tao of Programming describes as adher-
guage.” ing to the “principle of least astonishment.” This does not
mean that it will not let you do complex and amazing
No collection of quotes would be complete without things, just that it stays out of the way and lets you go about
NASA, where they are “using Python to implement a your business. Python is happy to play second fiddle to your
CAD/CAE/PDM [computer-aided design/computer-aided ideas.
engineering/product data management] repository and The Python community prides itself on being friendly,
model management, integration, and transformation sys- helpful, and humorous (the name “Python” comes from
tem that will be the core infrastructure for its next-gener- van Rossum’s fondness for Monty Python’s Flying Circus).
ation collaborative engineering environment,” according You can find many mailing lists and news groups by click-
to Steve Waterbury, software group leader, NASA STEP ing the “Community” link on the Python homepage.Your
Testbed (http://step. nasa.gov/testbed). questions will be answered by people interested in helping
At the very least, Python deserves a serious look. you. Flaming—that is, humiliating people who ask “unwor-
thy” questions—is rare; however, if you ask members to
PYTHON PHILOSOPHY simply do your work for you, they will call you on it. The
So what makes Python different from other program- Python community spirit is not accidental; van Rossum is
ming languages? Why not stick with C or C++, run with committed to education, especially to making Python
the ever-popular Java, or harness the power of Perl? In a accessible to users without computer science degrees.
word: simplicity. As Rob Andrews writes,“Computer ‘geeks’ have a rep-
Python is described as “an interpreted, interactive, utation for lacking people skills, but the Python community
object-oriented programming language” often compared challenges this myth every day by demonstrating genuine
to Tcl, Perl, Scheme, or Java. According to the Python interest in people learning the language and encouraging
homepage, the programming language combines “remark- people in general. Many people learn quickly to apologize
able power with very clear syntax,” and uses “modules, profusely for being stupid and naive when posting ques-
classes, exceptions, high-level dynamic data types, and tions to e-mail lists and Usenet programming discussions.
dynamic typing.” But the Pythonistas teach people not to put themselves

12 IT Pro September ❘ October 2005


down. If you look over the archives of comp.lang.python several choices. CBS, the AARP, and NATO use Zope
(http://www. zope.org), a popular object-oriented Web
and the Python Tutor e-mail list, you can easily verify that
people are told ‘you are not stupid, and neither is your framework. Other Web frameworks include CherryPy
question’ when newbies insult themselves up front.” (http://www.cherrypy.org) and Quixota (http://www.mems-
exchange.org/software/quixote). Many in the Python com-
OTHER PYTHON EFFORTS munity feel that having so many choices violates “the
Python takes advantage of language should have one, and
the underlying C libraries [Python’s] simple syntax and preferably one, way to do it” phi-
found on most computer losophy, and a spirited debate
systems. Recognizing the built-in data structures let continues on the message boards
substantial group of pro- us concentrate on the as to which, if any, of these varia-
grammers familiar (and tions should become the accepted
happy) with the Java layout’s complexities and framework.
libraries, a group of Python what we want to do with
developers combined USING PYTHON
Python’s simple syntax with the records. One of the most common IT
Java libraries to create tasks is generating reports using
Jython. You can find more information in a database. At
information at http://www.jython.org. NovaSys Health, we send our clients daily encrypted
An implementation of Python for Microsoft’s .NET reports about membership and deductible status. Python
framework is also in the works. At the March 2005 PyCon makes it easy to connect to and use virtually any database.
conference, Microsoft’s Jim Hugunin gave a keynote NovaSys Health houses its customer data in a Postgre
address covering the development of Iron Python database, while our claim adjudication system uses Oracle.
(http://www. ironpython. com), which lets Python develop- Our architecture uses classes and objects extensively, with
ers share .NET’s benefits. one class handling database issues. Our applications con-
For those interested in Web development, Python offers nect to both databases and to a Microsoft Access database

IEEE save
Computer Society
members
25 %
m e m b e r ?

on all conferences
o n l i n e
t o d a y !

sponsored by the
IEEE
J o i n
a

Computer Society
N o t

w w w. c o m p u t e r. o r g / j o i n

September ❘ October 2005 IT Pro 13


PROGRAMMING LANGUAGES

As I mentioned earlier, changing something as


Python simple as a data layout used to take weeks and
Resources cost over a thousand dollars. With the extractor
engine and a simple Web interface, we can often
make changes and provide a test file for review
Tutorials while our clients are still on the phone. Our
➤ Dive into Python, by Mark Pilgrim: clients are happy with this type of response, and
http://diveintopython.org our leadership now expects it.
➤ How To Think Like a Computer Scientist: Learning in Although we could have written the applica-
Python, by Allen B. Downey, Jeffrey Elkner, and Chris tion in virtually any other language, Python let us
Meyers: http://www.ibiblio.org/obp/thinkCSpy bring it in with about 300 lines of code. More
➤ Python Tutorial, by Guido van Rossum: importantly, the code is so easy to read that our
http://docs. python.org/tut/tut.html VP could understand over 80 percent of it (by his
➤ Python tutorials (more than 200 tutorials and papers sorted estimate). Making the code accessible to more
by topic): http://www.awaretek.com/tutorials.html people reduces logical errors and simplifies main-
tenance. Over the past few months, we have
Mailing lists and user groups received many requests to add features to extrac-
➤ Local user groups: tor, and I am constantly amazed at how easy it is
http://wiki.python.org/moin/LocalUserGroups to maintain and modify Python.
➤ Python mailing lists, newsgroups, and Web forums: A pleasant side effect of the extractor project
http://www.python.org/community/lists.html resulted from a conversation with a NovaSys
employee who verifies the credentials of the
Other fun stuff medical providers in the networks we service. She
➤ Planet Python (Python-related blogs): told me that creating the packets for our
http://www.planetpython. org providers required between three and five days
➤ Python Eggs (tutorials, references, and other links): of her time each month. After discussing the
http://www. python-eggs.org process with her for few minutes, it became clear
➤ Python events: http://wiki.python.org/moin/PythonEvents that we could write a query to pull the required
➤ Pythonology: http://www.pythonology.org information and drop it into an existing mail-
➤ PythonWare: http://www.pythonware.com merge routine to automatically create the pack-
ets. We even formatted the cover letter to fit the
address in an envelope window, eliminating the
need for address labels.We created everything in
on a Windows server as well as an Image database on an PDF to give it a professional look. This reduced the time
older HP-3000 system. for this task to less than 30 minutes each month.
Initially, we had separate scripts for each client.Although Our current effort involves more than 8,000 lines of code
this system worked, maintaining multiple versions of code that we use to automatically process and track claims. Our
was a logistical nightmare. The company’s vice-president CEO is pleased and tells us he has five or six more ideas for
of IT challenged the IT department to write “one extrac- projects for us take on. We could not be happier.
tion routine to rule them all.” We considered the scripts
used to produce our daily membership reports and noticed COMPLEX PROGRAMMING TASKS
that they all did the same thing:They pulled data based on The Electronic Data Interchange (EDI) X12 defines the
client and date parameters, formatted the data into client- standard for transmitting medical data. For medical claims
specific formats (fixed-length and delimited), and then (known as 837p records) from professionals, the standard
transmitted the encrypted file to the client. is more than 600 pages long. Another 600 pages address
Our response to the challenge was a routine called extrac- claims from institutions, and more address dental claims.
tor (we are nothing if not clever), which performs the nec- EDI-X12 files consist of many variable-length, delimited
essary tasks using data housed in a database, letting us data segments organized into various combinations of
change the routines via Web pages.The database even holds loops, groups, and data sets creating a flexible but complex
the record layouts and Structured Query Language (SQL) layout to process.
used for client-specific queries, letting us make changes to Complex programming is precisely where Python shines.
jobs confidentially. Every time a job completes, extractor The language’s simple syntax and built-in data structures
sends an e-mail to the logistics staff. If an error occurs (cor- let us concentrate on the layout’s complexities and what
rupted file, network error, and so on), extractor e-mails the we want to do with the records—that is, Python tries to get
development team specifying the error encountered. out of your way. Not only does the standard library come

14 IT Pro September ❘ October 2005


with many functions to make programming easier, but ber of development environments including Java, Eiffel,
Python groups the functions into libraries and modules so Forth, and Visual Basic, and Python is by far the most pow-
that everything fits together with a consistent interface. erful environment I have used. First, it is amazingly power-
As many Python mailing list members have commented, ful. Second, the design-code-test cycle is short with rapid
Python “fits your head.” feedback. Third, it is the only language I have used where I
Some people’s hard work has made processing EDI-X12 can be away from [my work] for a while (busy in the nursery)
files even easier. John Holland, for example, wrote an appli- and know what I am doing when I come back to it.” You can
cation to convert EDI-X12 files to XML (and back to X12 see his work in progress at http://mindwrapper.org.
format), which he has given to the open source commu- I could give you numerous other examples of great work
nity. Holland, who works in the healthcare field, saw a need being done in Python, but I would like you to write some
and “scratched the itch” using Python. He actively main- of your own code. Let’s get started.
tains the code by listening to its users. You can check out
his work at http://pyx12.sourceforge.net. GETTING PYTHON, LEARNING PYTHON
Another programmer doing remarkable things with The home for all things Python is http://www. python.org.
Python is Donnal Walter at the University of Arkansas’ There you can find easy-to-follow instructions for installing
College of Medicine and Arkansas Children’s Hospital in and using Python. As of this writing, the current package
Little Rock.Walter has both a PhD and an MD, but he uses is version 2.4.1. Pick the distribution for your operating
Python because it is simple. He is writing tools to use in system and you will be ready to start. Although Python
the hospital’s pediatrics departments and a framework to installs and runs on several operating systems, I will con-
help others write their own tools. Walter believes that cli- centrate on the Windows version to simplify the discus-
nicians should be directly involved in constructing soft- sion. Download the file and then double-click from file
ware because large-scale commercial software cannot manager to start the installation wizard. If you start now,
meet all of their specialized needs. you will be ready to go in less than 10 minutes—honest.
About Python,Walter says,“I have worked with a num- The Python homepage offers several fine tutorials tai-

SCHOLARSHIP
MONEY FOR
STUDENT LEADERS
Lance Stafford Larson Student Scholarship best paper contest

Upsilon Pi Epsilon/IEEE Computer Society Award for Academic Excellence
Each carries a $500 cash award.
Application deadline: 31 October

Investing in Students
www.computer.org/students/

September ❘ October 2005 IT Pro 15


PROGRAMMING LANGUAGES

lored to experience level—from no programming experi-


ence to years of experience. Mark Pilgrim’s Dive into
How to Reach Python is one of the best and, like the other tutorials on
the site, is freely available. If you want to spend money,
IT Professional you can find other tutorials at your favorite bookseller.
An excellent resource for Python users is the Python
Cookbook (O’Reilly Press, 2nd ed.). It contains hundreds
Writers of code snippets covering all aspects of programming. In
the fine tradition of the O’Reilly cookbooks, you will learn
We welcome submissions. For detailed information
something new every time you pick the book up.
visit our Web site: http://www.computer.org/itpro/.
BATTERIES INCLUDED
Products and Books Python comes with “batteries included,” meaning that it
Send product and book announcements to ships with more than 300 libraries to assist in various pro-
itproducts@computer.org. gramming tasks.There are routines to handle XML, socket
connections, e-mail, operating systems, and many other
tasks because the Python community does not believe in
Letters to the Editor reinventing the wheel. Before a module becomes part of
Please provide an e-mail address or daytime phone the standard library, the development team scrutinizes it to
number with your letter. Send letters to Letters, IT ensure that it fits with the core distribution.
Pro, 10662 Los Vaqueros Cir., PO Box 3014, Los If a task is not covered in the standard libraries, someone
Alamitos, CA 90720-1314; fax +1 714 821 4010; else has probably written a routine and is willing to share
itpro@computer.org. it (recall Holland’s routines for parsing EDI-X12 records).
Python is open source and benefits from thousands of
enthusiasts (Pythonistas) sharing code and ideas. (Check
On the Web
out the Search section on the Python homepage.)
Visit http://computer.org for information about
joining and becoming involved with the Society NEXT STEPS
and IT Pro. The best way to learn a programming language is to pro-
gram.An excellent place to find all levels of programming
Magazine Change of Address tasks is the “Useless Python” Web site (http://www.
uselesspython. com)—a site created and maintained to pro-
Send change-of-address requests for magazine
mote and share all things Python.Among other things, you
subscriptions to address.change@ieee.org. Make
will find lists of problems from past computer programming
sure to specify IT Pro. contests. Choose a task and get to work. If you run into trou-
ble, ask for help on the python tutor mailing list. Post your
Missing or Damaged Copies solutions to the site to share with others. It is a great way to
If you are missing an issue or received a damaged learn Python (and a lot of fun).
copy, contact help@computer.org. This article is just an introduction to Python. Python also
handles images, scientific computing, HTML, and much
more. The “Python Resources” lists places to go for more
Reprint Permission information, but why not give Python a try? Download the
To obtain permission to reprint an article, contact current version and print a tutorial from the Python home-
William Hagen, IEEE Copyrights and Trademarks page. With just a little effort, you could be doing great
Manager, at w.hagen@ieee.org. To buy reprints, see things with Python. ■
http://www.computer.org/author/reprint.htm.
Greg Lindstrom is a senior programmer at NovaSys
Health in Little Rock, Arkansas. Contact him at
greg.lindstrom@novasyshealth.com.

For further information on this or any other computing


topic, visit our Digital Library at www.computer.org/
publications/dlib.

16 IT Pro September ❘ October 2005

You might also like