Python Programming Language

back to top Python Language and command usage

PLEAC (Programming Language Examples Alike Cookbook) for Python
This site shows how to do tasks in Python that are pressented in the great Perl Cookbook (by Tom Christiansen & Nathan Torkington, published by O'Reilly
Python examples are provided for 64.29% of corresponding Perl code.

import sys
print sys.argv # prints argument array (sys.argv[0] is script name)

Python is derived from ABC, an attempt at an interactive BASIC-like language.
As though designed to be "cleaner" than Perl, minimal punctuation in code. Simple variable names (no "$" or "@" prefixes), code blocks defined by indentation instead of braces, range(n) produces numbers 0 up to but not including n, list and dictionary (hash) data structures.

for x in range(-5,10):     # produces [-5, -4, -3, ..., 7, 8, 9]
  if x < 0:
    print "x is negative"
  elif x%2:                # true if x mod 2 is 1 (not 0)
    print "x is positive and odd"
    print "x is positive and even"

for i in range(8):    #  0 1 2 3 4 5 6 7
   if i in (2,6,4,1):
	   print i
prints 1 2 4 6 (in a column)

Interactive Python:
python -i
^d to exit
help() goes to extensive help system!
q quits help system
dir() shows all variables in workspace!

Python one-liners: (from

I'm updating the zsh completion function for python and need to
generate a list of modules for completing the new '-m' option.

> For python 2.4, try:
> python -c "import sys; print sorted(sys.modules)"

back to top Commands

from tutorial at Note the double (parallel) assignment

A trailing comma avoids the newline after the output:

>>> a, b = 0, 1
>>> while b < 1000:
...     print b,
...     a, b = b, a+b
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

back to top Complex Numbers

Complex numbers are also supported; imaginary numbers are written with a suffix of "j" or "J". Complex numbers with a nonzero real component are written as "(real+imagj)", or can be created with the "complex(real, imag)" function.

>>> 1j * 1J
>>> 1j * complex(0,1)
>>> 3+1j*3
>>> (3+1j)*3
>>> (1+2j)/(1+1j)

Complex numbers are always represented as two floating point numbers, the real and imaginary part. To extract these parts from a complex number z, use z.real and z.imag.

>>> a=1.5+0.5j
>>> a.real
>>> a.imag

The conversion functions to floating point and integer (float(), int() and long()) don't work for complex numbers -- there is no one correct way to convert a complex number to a real number. Use abs(z) to get its magnitude (as a float) or z.real to get its real part.

>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
>>> a.imag
>>> abs(a)  # sqrt(a.real**2 + a.imag**2)

Arbitrary Precision Integers:

>>> 2L + 3
>>> 5L ** 100

back to top "Anonymous" Variable

In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
>>> price + _
>>> round(_, 2)

back to top Functions

>>> def modexp ( t, u, n ):
   """computes s = (t ^ u) mod n
      args are base, exponent, modulus
      (see Bruce Schneier's book, _Applied Cryptography_ p. 244)"""
   s = 1
   while u:
    	if u & 1:
    	   s = (s * t)%n
    	u >>= 1
    	t = (t * t)%n;
   return s

>>> modexp(2,11,997)
>>> modexp(2,13,997)
>>> modexp(216,11,997)
>>> modexp(54,13,997)

back to top Modules

A python program typically imports standard modules containing needed pre-writen functions. From the Python Turorial:

6.1.1 The Module Search Path

When a module named spam is imported, the interpreter searches for a file named in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation- dependent default path; on Unix, this is usually .:/usr/local/lib/python.

Actually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation-dependent default. This allows Python programs that know what they're doing to modify or replace the module search path. Note that because the directory containing the script being run is on the search path, it is important that the script not have the same name as a standard module, or Python will attempt to load the script as a module when that module is imported. This will generally be an error.

Also from the Python Turorial:

6.3 The dir() Function

The built-in function dir() is used to find out which names a module defines. 
It returns a sorted list of strings:

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
 '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 
 'builtin_module_names', 'byteorder', 'callstats', 'copyright',
 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
 'version', 'version_info', 'warnoptions']

Without arguments, dir() lists the names you have defined currently:

>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__doc__', '__file__', '__name__', 'a', 'fib', 'fibo', 'sys']

Note that it lists all types of names: variables, modules, functions, etc.

dir() does not list the names of built-in functions and variables. 
If you want a list of those, they are defined in the standard module __builtin__:

>>> import __builtin__
>>> dir(__builtin__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning',
 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
 'NotImplementedError', 'OSError', 'OverflowError', 
 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
 'UserWarning', 'ValueError', 'Warning', 'WindowsError',
 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
 '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer',
 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set',
 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

Using modules os, sys, glob:

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', 
'_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 
'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info', 
'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'exitfunc', 
'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 
'getwindowsversion', 'hexversion', 'last_traceback', 'last_type', 'last_value', 'maxint', 'maxunicode', 
'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 
'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 
'subversion', 'version', 'version_info', 'warnoptions', 'winver']
>>> import os
>>> import glob
>>> os.getcwd()
>>> os.chdir('/Documents and Settings/Owner/')
>>> os.getcwd()
'C:\\Documents and Settings\\Owner'
>>> os.chdir('My Documents')
>>> os.chdir('python')
>>> os.getcwd()
'C:\\Documents and Settings\\Owner\\My Documents\\python'
>>> glob.glob('*.py')
['', '', '', '']

back to top Image Processing with PIL

From PIL intro

To load an image from a file, use the open function in the Image module.

>>> import Image
>>> im ="birdsMCE59.jpg")
If successful, this function returns an Image object. You can now use instance attributes to examine the file contents.
>>> print im.format, im.size, im.mode
PPM (512, 512) RGB

The format attribute identifies the source of an image.

Display the image we just loaded:

(The standard version of show is not very efficient, since it saves the image to a temporary file and calls the xv utility to display the image. If you don't have xv installed, it won't even work. When it does work though, it is very handy for debugging and tests.)

Applying point transforms (and incidentally showing an implicit looping over mech!)

# multiply each pixel by 1.2
out = im.point(lambda i: i * 1.2)

Draw a Grey Cross Over an Image - per

import Image, ImageDraw

im ="lena.pgm")

draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)
del draw

# write to stdout, "PNG")

back to top Sound

From google "python sound example": pymedia tutorial

back to top Mod Python (Apache)

back to top Python CGI

Entirely different than Python Server Pages! no <% %> tags...

print "Content-Type: text/plain\n\n"

a = 5/2
print "5/2 =", a

a = 5/2.0
print "5/2.0 =", a, "\n"

# String addition and multiplication.
python_words = "python is" + 3*" really" + " neat."
print python_words, "\n"

# Print parts of the string.
print "The first character is:", python_words[0]
print "The last character is:", python_words[-1]
print "In the middle is: \n", python_words[1:-1]

back to top Python Server Pages (PSP) and Mod Python

Files have extension .psp; examples from 2004 article on python server pages

if form.has_key('name'):
   greet = 'Hello, %s!' % form['name'].capitalize()
   greet = 'Hello there!'
# end
  <h1><%= greet %></h1>

another examples from the article:

import time
<h1>Current time is
<%= time.ctime() %> </h1>

from mod_python tutorial at

import time
Hello world, the time is: <%=time.strftime("%Y-%m-%d, %H:%M:%S")%>

back to top Python Links