Python 101 (part 1): Snake Eyes - Start It Up (
Page 3 of 6 )
With that out of the way, let's get down to actually doing
something with Python. I'm assuming here that you've already got Python up and
running on your system; if you haven't, now is a good time to visit
http://www.python.org/ and download a version for your platform (installation instructions are included
with each distribution, and you might also want to download a copy of the Python
documentation and function reference.)
The examples in this series will assume Python on Linux, although you're free
to use it on the platform of your choice.
If you're on a UNIX system, a quick way to check whether Python is already present
on the system is with the UNIX "which" command. Try typing this in your UNIX shell:
$ which python
If Perl is available, the program should return the full path to the Python binary,
usually
/usr/bin/python
or
/usr/local/bin/python
There are two primary methods to run Python code - via the command line, or via
a script.
The command line interpreter allows you to type in Python code line by line,
and executes it immediately; this is a great way to see the result of a particular
statement or set of statements. You can start up the interpreter by typing in
the full path to the Python binary at any command prompt.
Once the interpreter starts up, you'll see a brief copyright notice and some
version information, followed by a ">>>" - this indicates that the interpreter
is ready and willing to receive your commands. Here's a brief example of what
this might look like:
$ python
Python 1.5.2 (#1, Aug 25 2000, 09:33:37) [GCC 2.96 20000731
(experimental)]
on
linux-i386
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>
print "Snake Eyes"
Snake Eyes
>>>
You can exit the interpreter with a Ctrl-D.
The disadvantage of the command line interpreter is that your code is lost once
you exit it. Therefore, Python also allows you to save your code to a text file,
and run this code as a script from the command line...as the following example
demonstrates.
# eyes.py - print a line of output
print "Snake Eyes"
$ python eyes.py
Snake Eyes
Python scripts and modules (explained later) typically end in a .py file extension.
In the example above, I've specified the name of the script to run as a parameter
on the command line. If you're on a UNIX system, you have the additional option
of directly running the script by name, by adding a line specifying the location
of the command interpreter at the top of the script file.
#!/usr/bin/python
# eyes.py - print a line of output
print "Snake Eyes"
This technique should be familiar to anyone who's programmed in Perl or bash.
Note that the script file must have executable privileges - you can accomplish
this with the "chmod" command.
$ chmod +x eyes.py
I'll be using both these techniques to demonstrate code snippets over the course
of this tutorial.