Next / Previous / Contents / TCC Help System / NM Tech homepage

7. How to write a self-executing Python script

So far we have used Python's conversational mode to demonstrate all the features. Now it's time to learn how to write a complete program.

Your program will live in a file called a script. To create your script, use your favorite text editor (emacs, vi, Notepad, whatever), and just type your Python statements into it.

How you make it executable depends on your operating system.

Here is a complete script, set up for a typical Linux installation. This script, powersof2, prints a table showing the values of 2n and 2-n for n in the range 1, 2, ..., 12.

#!/usr/local/bin/python
print "Table of powers of two"
print
print "%10s %2s %-15s" % ("2**n", "n", "2**(-n)")
for n in range(13):
    print "%10d %2d %.15f" % (2**n, n, 2.0**(-n))

Here we see the invocation of this script under the bash shell, and the output:

bash-3.1$ ./powersof2
Table of powers of two

      2**n  n 2**(-n)
         1  0 1.000000000000000
         2  1 0.500000000000000
         4  2 0.250000000000000
         8  3 0.125000000000000
        16  4 0.062500000000000
        32  5 0.031250000000000
        64  6 0.015625000000000
       128  7 0.007812500000000
       256  8 0.003906250000000
       512  9 0.001953125000000
      1024 10 0.000976562500000
      2048 11 0.000488281250000
      4096 12 0.000244140625000