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.
On Windows platforms, be sure to give your script file
a name that ends in “.py”. If Python is installed, double-clicking on
any script with this ending will use Python to run the script.
Under Linux and MacOS X, the first line of your script must look like this:
#!pythonpath
The tells the operating system where to find
Python. This path will usually be “pythonpath/usr/local/bin/python”, but you can use the
“which”
shell command to find the path on your computer:
$ which python /usr/local/bin/python
Once you have created your script, you must also use this command to make it executable:
chmod +x your-script-name
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 "{0:>10s} {1:>2s} {2:s}".format("2**n", "n", "2**(-n)")
for n in range(13):
print "{0:10d} {1:2d} {2:17.15f}".format(2**n, n, 2.0**(-n))
Here we see the invocation of this script under the bash shell, and the output:
$ ./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