Encyclopedia > Python programming language

  Article Content

Python programming language

Python is an interpreted, interactive programming language created by Guido van Rossum. It is named after the television series Monty Python's Flying Circus. Python is often compared to Tcl, Perl, Scheme or Java and recently to Ruby.

Table of contents

Philosophy Python is a multi-paradigm language, like C++ and unlike Smalltalk or Haskell. This means that, rather than forcing coders to adopt one particular style of coding, it permits several. Object orientation, structured programming and functional programming are all supported. It is dynamically type-checked and uses garbage collection for memory management.

It has also been called an agile programming language[?] [1] (http://www.pycs.net/altis/2003/04/04).

Popularized explicitly in contrast to Perl, Python has many similarities to that language. However, Python's designers reject Perl's exuberant syntax in favor of a more spare, less cluttered one. As with Perl, Python's developers have expressly forwarded a particular "culture" or ideology of what they want their language to be -- favoring language forms they see as "beautiful", "explicit", and "simple". [2] (http://python.org/dev/culture)

Though -- again as with Perl -- Python is sometimes classed as a "scripting language", it has been used to develop many large software projects such as the Zope application server and the Mnet[?] file sharing system.

Data types and structures Python has a broad range of basic data types. Alongside conventional integer and floating point arithmetic, it transparently supports arbitrarily large integers and complex numbers.

It supports the usual panoply of string operations, with one exception: strings in Python are immutable objects, so any string operation that might elsewhere alter a string (such as a substitution of characters) will instead return a new string.

Python values, not variables, carry type -- meaning that Python is a dynamically typed language, like Lisp and unlike Java or C. All values are passed by reference.

Among dynamically typed languages, Python is moderately type-checked. It is neither as loose as Perl nor as strict as Caml. Implicit conversion is defined for numeric types, so one may validly multiply a complex number by a long integer (for instance) without explicit casting. However, there is no implicit conversion between (e.g.) numbers and strings; unlike in Perl, a number is an invalid argument to a string operation.

Collection types

Python also has several collection types, including lists, tuples, and dictionaries. Lists, tuples, and strings are sequences and share most of their methods in common: one can iterate over the characters of a string as easily as the elements of a list. Lists are extensible arrays, whereas tuples are of fixed length and immutable.

The purpose for all this immutability comes in with dictionaries, a type known elsewhere as hashes, associative arrays, or maps. To preserve consistency under pass-by-reference, the keys of a dictionary must be of immutable type. Dictionary values, on the other hand, may be of any type.

Object system

The Python type system is well integrated with the class system. Although the built-in data types are not precisely classes, a class can inherit from a type. Thus it is possible to extend strings or dictionaries ... or even integers, should you care to do such a thing. Python also supports multiple inheritance.

The language supports extensive introspection of types and classes. Types can be read and compared -- indeed, as in Smalltalk, types are a type. The attributes of an object can be extracted as a dictionary.

Operators can be overloaded in Python by defining special member functions -- for instance, defining __add__ on a class permits one to use the + operator on members of that class. (Compare C++'s operator+ and similar method names.)

Syntax Python was designed to be highly readable. It has a simple visual layout, uses English keywords frequently where other languages use punctuation, and has notably fewer syntactic constructions than many structured languages such as C, Perl, or Pascal.

For instance, Python has only two structured loop forms -- for, which loops over elements of a list or iterator (like Perl foreach); and while, which loops as long as a Boolean expression is true. It thus lacks C-style complex for, a do...while, and Perl's until, though of course equivalents can be expressed. Likewise, it has only if...elif...else for branching -- no switch or labeled goto.

The whitespace thing

One unusual aspect of Python's syntax is the method used to delimit program blocks. Sometimes termed "the whitespace thing", it is one aspect of Python syntax that many programmers who've never written a line of Python have heard of, since it is unique among currently widespread languages.

In languages that use the block structure ultimately derived from Algol -- languages including Pascal, C, and Perl -- blocks of code are set off with braces or keywords. (C and Perl use { }; Pascal uses begin and end.) In all these languages, however, programmers conventionally indent the code within a block, to set it off visually from the surrounding code.

Python, instead, borrows a feature from the lesser-known language Occam -- instead of punctuation or keywords, it uses this indentation itself to indicate the run of a block. A brief example will make this clear. Here are C and Python functions which do the same thing -- computing the factorial of an integer:

Factorial function in C:

 int factorial(int x) {      
     if (x == 0) {                      
     } else {
         return(x * factorial(x-1));

Factorial function in Python:

 def factorial(x):
     if x == 0:
         return 1
         return x * factorial(x-1)

Some programmers used to Algol-style languages, in which whitespace is semantically empty, at first find this confusing. A few have drawn unflattering comparison to the column-oriented style used on punched-card Fortran systems: once, it was a major development to have "free-form" languages in which only symbols mattered and not their position on the line.

To Python programmers, however, "the whitespace thing" is simply an extrapolation of a convention that programmers in Algol-style languages already follow anyway.

Functional programming

As mentioned above, another strength of Python is the availability of functional syntax elements. As may be expected, these make working with lists and other collections much more straightforward. One such construction is the list comprehension, introduced from the functional language Haskell, as seen here in calculating the first five powers of two:

 numbers = [1, 2, 3, 4, 5]
 powers_of_two = [ 2 ** n for n in numbers ]

Because Python permits functions as arguments, it is also possible to express more subtle functional constructs, such as the continuation (http://www.ps.uni-sb.de/~duchier/python/continuations).

Python's lambda keyword may misdirect some functional-programming fans. Python lambda blocks may contain only expressions, not statements. Thus, they are not the most general way to return a function. Instead, the usual thing to do is to just define and return a function using a locally scoped name, as in the following example of a simple curried function:

 def add_and_print_maker(x):
     def temp(y):
         print "%d + %d = %d" % (x, y, x+y)
     return temp

Exception handling

Python supports (and extensively uses) exception handling as a means of testing for error conditions. Indeed, it is even possible to trap the exception caused by a syntax error[?]!

Exceptions permit more concise and reliable error checking than many other ways of reporting erroneous or exceptional events. Exceptions are thread-safe; they tend not to clutter up code in the way that testing for returned error codes does in C; and they can easily propagate up the calling stack when an error must be reported to a higher level of the program.

Python style calls for the use of exceptions whenever an error condition might arise. Indeed, rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it -- catching the exception if access is rejected.

Standard library Python has a large standard library[?], which makes it well suited to many tasks. The modules of the standard library can be augmented with custom modules written in either C or Python. The standard library is particularly well tailored to writing Internet-facing applications, with a large number of standard formats and protocols (such as MIME and HTTP) supported. Modules for creating graphical user interfaces, connecting to relational databases, and manipulating regular expressions are also included.

The standard library is one of Python's greatest strengths. The bulk of it is cross-platform compatible, meaning that even heavily leveraged Python programs can often run on Unix, Windows, Macintosh, and other platforms without change.

Other features Like Lisp, and unlike Perl, the Python interpreter also supports an interactive mode in which expressions can be entered from the terminal and results seen immediately. This is a boon for those learning the language and experienced developers alike: snippets of code can be tested in interactive mode before integrating them into a program proper.

Python also includes a unit testing framework for creating exhaustive test suites. While static-typing aficionados see this as a replacement for a static type-checking system, Python programmers largely do not share this view.


  • Code example and explanation to illustrate the differences between an excplicitely and implicity typed language. Namely Python and Java
  • Here is some comparison between C++ and Python with a pretty lengthy example.
  • Java implemetation of Python programming language is called Jython.

External Links

All Wikipedia text is available under the terms of the GNU Free Documentation License

  Search Encyclopedia

Search over one million articles, find something about almost anything!
  Featured Article
Canadian Music Hall of Fame

... 1980 Paul Anka 1981 Joni Mitchell 1982 Neil Young 1983 Glenn Gould 1986 Gordon Lightfoot 1987 The Guess Who[?] 1989 The Band 1990 Maureen Forrester[?] ...

This page was created in 37.5 ms