1.1 What Is Python?
1.1 What Is Python?
fi
.
fi
at the python prompt.
For longer programs, you can compose your python code in the editor of
your choice, and execute the program by either typing “python”,
followed by the name of the le containing your program, or by clicking
on the le’s icon, if you’ve associated the suf x of your python le with
the python in- terpreter. The le extension most commonly used for
python les is “.py”. Under UNIX systems, a standard technique for
running programs written in languages like python is to include a
specially formed comment as the rst line of the le, informing the shell
where to nd the interpreter for your program. Suppose that python is
installed as /usr/local/bin/python on your system. (The UNIX command
“which python” should tell you where python is installed if it’s not in /
usr/local/bin.) Then the rst line of your python program, starting in
column 1, should look like this:
#!/usr/local/bin/pytho
1.4. BASIC PRINCIPLES OF PYTHON 11
After creating a le, say myprogram.py, which contains the special
comment as its rst line, you would make the le executable (through
the UNIX com- mand “chmod +x myprogram.py”), and then you could
execute your pro- gram by simply typing “myprogram.py” at the UNIX
prompt.
When you’re running python interactively, you can instruct python to
ex- ecute les containing python programs with the exec le function.
Suppose that you are using python interactively, and wish to run the
program you’ve stored in the le myprog.py. You could enter the
following statement:
exec le("myprog.py"
The le name, since it is not an internal python symbol (like a variable
name or keyword), must be surrounded by quotes.
fi
fi
fi
fi
fi
fi
fi
fi
)
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
1.4 Basic Principles of Python
Python has many features that usually are found only in languages which
are much more complex to learn and use. These features were designed
into python from its very rst beginnings, rather than being accumulated
into an end result, as is the case with many other scripting languages. If
you’re new to programming, even the basic descriptions which follow
may seem intimidating. But don’t worry – all of these ideas will be made
clearer in the chapters which follow. The idea of presenting these
concepts now is to make you aware of how python works, and the
general philosophy behind python programming. If some of the concepts
that are introduced here seem abstract or overly complex, just try to get a
general feel for the idea, and the details will be eshed out later
fi
fi
fi
[’__builtins__’, ’__doc__’, ’__name__’
>>> dir(__builtins__
[’ArithmeticError’, ’AssertionError’, ’AttributeError’, ’EOFError’
’Ellipsis’, ’Exception’, ’FloatingPointError’, ’IOError’, ’ImportError’
’IndexError’, ’KeyError’, ’KeyboardInterrupt’, ’LookupError’
’MemoryError’, ’NameError’, ’None’, ’Over owError’, ’RuntimeError’
’StandardError’, ’SyntaxError’, ’SystemError’, ’SystemExit’, ’TypeError’
’ValueError’, ’ZeroDivisionError’, ’_’, ’__debug__’, ’__doc__’
14 CHAPTER 1. INTRODUCTION
’__import__’, ’__name__’, ’abs’, ’apply’, ’callable’, ’chr’, ’cmp’
’coerce’, ’compile’, ’complex’, ’delattr’, ’dir’, ’divmod’, ’eval’
’exec le’, ’ lter’, ’ oat’, ’getattr’, ’globals’, ’hasattr’
’hash’, ’hex’, ’id’, ’input’, ’int’, ’intern’, ’isinstance’
’issubclass’, ’len’, ’list’, ’locals’, ’long’, ’map’, ’max’, ’min’
’oct’, ’open’, ’ord’, ’pow’, ’range’, ’raw_input’, ’reduce’, ’reload’
’repr’, ’round’, ’setattr’, ’slice’, ’str’, ’tuple’, ’type’, ’vars’
’xrange’
The __builtins__ namespace contains all the functions, variables and ex-
ceptions which are part of python’s core.
To give controlled access to other namespaces, python uses the import
statement. There are three ways to use this statement. In its simplest
form, you import the name of a module; this allows you to specify the
various objects de ned in that module by using a two level name, with
the mod- ule’s name and the object’s name separated by a period. For
example, the string module (Section 8.4) provides many functions useful
for dealing with character strings. Suppose we want to use the split
function of the string module to break up a sentence into a list containing
separate words. We could use the following sequence of statements:
>>> import strin
>>> string.split(’Welcome to the Ministry of Silly Walks’
[’Welcome’, ’to’, ’the’, ’Ministry’, ’of’, ’Silly’, ’Walks’
If we had tried to refer to this function as simply “split”, python would
not be able to nd it. That’s because we have only imported the string
fi
]
fi
fi
g
fi
fl
)
fl
,
module into the local namespace, not all of the objects de ned in the
module. (See below for details of how to do that.)
The second form of the import statement is more speci c; it speci es the
individual objects from a module whose names we want imported into
the local namespace. For example, if we only needed the two functions
split and join for use in a program, we could import just those two names
directly into the local namespace, allowing us to dispense with the
string. pre x:
>>> from string import split,joi
>>> split(’Welcome to the Ministry of Silly Walks’
[’Welcome’, ’to’, ’the’, ’Ministry’, ’of’, ’Silly’, ’Walks’
This technique reduces the amount of typing we need to do, and is an
ef cient way to bring just a few outside objects into the local
environment.
1.4. BASIC PRINCIPLES OF PYTHON 15
Finally, some modules are designed so that you’re expected to have top-
level access to all of the functions in the module without having to use
the module name as a pre x. In cases like this you can use a statement
like:
>>> from string import
Now all of the objects de ned in the string module are available directly
in the top-level environment, with no need for a pre x. You should use
this technique with caution, because certain commonly used names from
the module may override the names of your variables. In addition, it
introduces lots of names into the local namespace, which could
adversely affect python’s ef ciency.
fi
fi
fi
n
fi
fi
]
fi
fi
provides a consistent method of handling errors, a topic often refered to
as exception handling. When you’re performing an operation that might
result in an error, you can surround it with a try loop, and provide an
except clause to tell python what to do when a particular error arises.
While this is a fairly advanced concept, usually found in more complex
languages, you can start using it in even your earliest python programs.
As a simple example, consider dividing two numbers. If the divisor is
zero, most programs (python included) will stop running, leaving the
user back at a system shell prompt, or with nothing at all. Here’s a little
python program that illustrates this concept; assume we’ve saved it to a
le called div.py:
#!/usr/local/bin/python x=7
y=0
print x/y
print "Now we’re done!
When we run this program, we don’t get to the line which prints the
message, because the division by zero is a “fatal” error:
% div.p
Traceback (innermost last)
16
CHAPTER 1. INTRODUCTION
File "div.py", line 5, in
print x/
ZeroDivisionError: integer division or modul
While the message may look a little complicated, the main point to
notice is that the last line of the message tells us the name of the
exception that occured. This allows us to construct an except clause to
handle the problem:
x=7 y=0
fi
y
"
o
try
print x/
except ZeroDivisionError
print "Oops - I can’t divide by zero, sorry!
print "Now we’re done!
Now when we run the program, it behaves a little more nicely:
% div.p
Oops - I can’t divide by zero, sorry
Now we’re done
Since each exception in python has a name, it’s very easy to modify your
program to handle errors whenever they’re discovered. And of course, if
you can think ahead, you can construct try/except clauses to catch errors
before they happen.
:
"
"