diff options
Diffstat (limited to 'Doc/tut/tut.tex')
-rw-r--r-- | Doc/tut/tut.tex | 113 |
1 files changed, 56 insertions, 57 deletions
diff --git a/Doc/tut/tut.tex b/Doc/tut/tut.tex index 71d2973..11434c4 100644 --- a/Doc/tut/tut.tex +++ b/Doc/tut/tut.tex @@ -38,7 +38,7 @@ pointers to many free third party Python modules, programs and tools, and additional documentation. The Python interpreter is easily extended with new functions and data -types implemented in \C{} or \Cpp{} (or other languages callable from \C{}). +types implemented in C or \Cpp{} (or other languages callable from C). Python is also suitable as an extension language for customizable applications. @@ -50,8 +50,8 @@ self-contained, so the tutorial can be read off-line as well. For a description of standard objects and modules, see the \emph{Python Library Reference} document. The \emph{Python Reference Manual} gives a more formal definition of the language. To write -extensions in \C{} or \Cpp{}, read the \emph{Extending and Embedding} and -\emph{Python/\C{} API} manuals. There are also several books covering +extensions in C or \Cpp{}, read the \emph{Extending and Embedding} and +\emph{Python/C API} manuals. There are also several books covering Python in depth. This tutorial does not attempt to be comprehensive and cover every @@ -72,15 +72,15 @@ modules described in the \emph{Python Library Reference}. If you ever wrote a large shell script, you probably know this feeling: you'd love to add yet another feature, but it's already so slow, and so big, and so complicated; or the feature involves a system -call or other function that is only accessible from \C{} \ldots Usually +call or other function that is only accessible from C \ldots Usually the problem at hand isn't serious enough to warrant rewriting the -script in \C{}; perhaps the problem requires variable-length strings or +script in C; perhaps the problem requires variable-length strings or other data types (like sorted lists of file names) that are easy in -the shell but lots of work to implement in \C{}, or perhaps you're not -sufficiently familiar with \C{}. +the shell but lots of work to implement in C, or perhaps you're not +sufficiently familiar with C. -Another situation: perhaps you have to work with several \C{} libraries, -and the usual \C{} write/compile/test/re-compile cycle is too slow. You +Another situation: perhaps you have to work with several C libraries, +and the usual C write/compile/test/re-compile cycle is too slow. You need to develop software more quickly. Possibly perhaps you've written a program that could use an extension language, and you don't want to design a language, write and debug an interpreter for it, then @@ -89,10 +89,10 @@ tie it into your application. In such cases, Python may be just the language for you. Python is simple to use, but it is a real programming language, offering much more structure and support for large programs than the shell has. On -the other hand, it also offers much more error checking than \C{}, and, +the other hand, it also offers much more error checking than C, and, being a \emph{very-high-level language}, it has high-level data types built in, such as flexible arrays and dictionaries that would cost you -days to implement efficiently in \C{}. Because of its more general data +days to implement efficiently in C. Because of its more general data types Python is applicable to a much larger problem domain than \emph{Awk} or even \emph{Perl}, yet many things are at least as easy in Python as in those languages. @@ -112,7 +112,7 @@ programs, or to test functions during bottom-up program development. It is also a handy desk calculator. Python allows writing very compact and readable programs. Programs -written in Python are typically much shorter than equivalent \C{} +written in Python are typically much shorter than equivalent C programs, for several reasons: \begin{itemize} \item @@ -125,12 +125,12 @@ brackets; no variable or argument declarations are necessary. \end{itemize} -Python is \emph{extensible}: if you know how to program in \C{} it is easy +Python is \emph{extensible}: if you know how to program in C it is easy to add a new built-in function or module to the interpreter, either to perform critical operations at maximum speed, or to link Python programs to libraries that may only be available in binary form (such as a vendor-specific graphics library). Once you are really hooked, -you can link the Python interpreter into an application written in \C{} +you can link the Python interpreter into an application written in C and use it as an extension or command language for that application. By the way, the language is named after the BBC show ``Monty Python's @@ -244,7 +244,7 @@ and a copyright notice before printing the first prompt, e.g.: \begin{verbatim} python -Python 1.5b1 (#1, Dec 3 1997, 00:02:06) [GCC 2.7.2.2] on sunos5 +Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> \end{verbatim} @@ -311,13 +311,14 @@ this file. If you want to read an additional start-up file from the current directory, you can program this in the global start-up file, -e.g.\ \samp{execfile('.pythonrc')}\indexii{.pythonrc.py}{file}. If +e.g.\ \samp{execfile('.pythonrc.py')}\indexii{.pythonrc.py}{file}. If you want to use the startup file in a script, you must do this explicitly in the script: \begin{verbatim} import os -if os.path.isfile(os.environ['PYTHONSTARTUP']): +if os.environ.get('PYTHONSTARTUP') \ + and os.path.isfile(os.environ['PYTHONSTARTUP']): execfile(os.environ['PYTHONSTARTUP']) \end{verbatim} @@ -347,7 +348,7 @@ for the primary prompt, \samp{>>> }. (It shouldn't take long.) The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators \code{+}, \code{-}, \code{*} and \code{/} -work just like in most other languages (e.g., Pascal or \C{}); parentheses +work just like in most other languages (e.g., Pascal or C); parentheses can be used for grouping. For example: \begin{verbatim} @@ -367,7 +368,7 @@ can be used for grouping. For example: -3 \end{verbatim} -Like in \C{}, the equal sign (\character{=}) is used to assign a value to a +Like in C, the equal sign (\character{=}) is used to assign a value to a variable. The value of an assignment is not written: \begin{verbatim} @@ -564,7 +565,7 @@ expressions: SyntaxError: invalid syntax \end{verbatim} -Strings can be subscripted (indexed); like in \C{}, the first character +Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Like in Icon, substrings can be specified with the \emph{slice notation}: two indices @@ -804,12 +805,12 @@ assignments take place. \item The \keyword{while} loop executes as long as the condition (here: -\code{b < 10}) remains true. In Python, like in \C{}, any non-zero +\code{b < 10}) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are -written the same as in \C{}: \code{<}, \code{>}, \code{==}, \code{<=}, +written the same as in C: \code{<}, \code{>}, \code{==}, \code{<=}, \code{>=} and \code{!=}. \item @@ -893,10 +894,10 @@ if', and is useful to avoid excessive indentation. An \section{\keyword{for} Statements \label{for}} The \keyword{for}\stindex{for} statement in Python differs a bit from -what you may be used to in \C{} or Pascal. Rather than always +what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and -halting condition (as \C{}), Python's \keyword{for}\stindex{for} +halting condition (as C), Python's \keyword{for}\stindex{for} statement iterates over the items of any sequence (e.g., a list or a string), in the order that they appear in the sequence. For example (no pun intended): @@ -974,10 +975,10 @@ and \function{len()} as follows: \keyword{else} Clauses on Loops \label{break}} -The \keyword{break} statement, like in \C{}, breaks out of the smallest +The \keyword{break} statement, like in C, breaks out of the smallest enclosing \keyword{for} or \keyword{while} loop. -The \keyword{continue} statement, also borrowed from \C{}, continues +The \keyword{continue} statement, also borrowed from C, continues with the next iteration of the loop. Loop statements may have an \code{else} clause; it is executed when @@ -1085,7 +1086,7 @@ mechanism: \end{verbatim} You might object that \code{fib} is not a function but a procedure. In -Python, like in \C{}, procedures are just functions that don't return a +Python, like in C, procedures are just functions that don't return a value. In fact, technically speaking, procedures do return a value, albeit a rather boring one. This value is called \code{None} (it's a built-in name). Writing the value \code{None} is normally suppressed by @@ -1430,7 +1431,7 @@ sequence for which \code{\var{function}(\var{item})} is true. For example, to compute some primes: \begin{verbatim} ->>> def f(x): return x%2 != 0 and x%3 != 0 +>>> def f(x): return x % 2 != 0 and x % 3 != 0 ... >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23] @@ -1698,7 +1699,7 @@ expression to a variable. For example, 'Trondheim' \end{verbatim} -Note that in Python, unlike \C{}, assignment cannot occur inside expressions. +Note that in Python, unlike C, assignment cannot occur inside expressions. \section{Comparing Sequences and Other Types \label{comparing}} @@ -1974,8 +1975,9 @@ The set of such modules is a configuration option; e.g., the \module{amoeba} module is only provided on systems that somehow support Amoeba primitives. One particular module deserves some attention: \module{sys}\refstmodindex{sys}, which is built into every -Python interpreter. The variables \code{sys.ps1} and \code{sys.ps2} -define the strings used as primary and secondary prompts: +Python interpreter. The variables \code{sys.ps1} and +\code{sys.ps2} define the strings used as primary and secondary +prompts: \begin{verbatim} >>> import sys @@ -1992,13 +1994,11 @@ C> These two variables are only defined if the interpreter is in interactive mode. -The variable -\code{sys.path} -is a list of strings that determine the interpreter's search path for -modules. -It is initialized to a default path taken from the environment variable -\envvar{PYTHONPATH}, or from a built-in default if \envvar{PYTHONPATH} -is not set. You can modify it using standard list operations, e.g.: +The variable \code{sys.path} is a list of strings that determine the +interpreter's search path for modules. It is initialized to a default +path taken from the environment variable \envvar{PYTHONPATH}, or from +a built-in default if \envvar{PYTHONPATH} is not set. You can modify +it using standard list operations, e.g.: \begin{verbatim} >>> import sys @@ -2279,7 +2279,7 @@ lay-out you can imagine. The standard module for padding strings to a given column width; these will be discussed shortly. The second way is to use the \code{\%} operator with a string as the left argument. \code{\%} -interprets the left argument as a \C{} \cfunction{sprintf()}-style +interprets the left argument as a C \cfunction{sprintf()}-style format string to be applied to the right argument, and returns the string resulting from this formatting operation. @@ -2391,18 +2391,18 @@ Dcab ==> 8637678 Sjoerd ==> 4127 \end{verbatim} -Most formats work exactly as in \C{} and require that you pass the proper +Most formats work exactly as in C and require that you pass the proper type; however, if you don't you get an exception, not a core dump. The \code{\%s} format is more relaxed: if the corresponding argument is not a string object, it is converted to string using the \function{str()} built-in function. Using \code{*} to pass the width or precision in as a separate (integer) argument is supported. The -\C{} formats \code{\%n} and \code{\%p} are not supported. +C formats \code{\%n} and \code{\%p} are not supported. If you have a really long format string that you don't want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by using -an extension of \C{} formats using the form \code{\%(name)format}, e.g. +an extension of C formats using the form \code{\%(name)format}, e.g. \begin{verbatim} >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} @@ -2446,7 +2446,7 @@ written. This behind-the-scenes modification to file data is fine for \ASCII{} text files, but it'll corrupt binary data like that in JPEGs or \file{.EXE} files. Be very careful to use binary mode when reading and writing such files. (Note that the precise semantics of text mode on -the Macintosh depends on the underlying \C{} library being used.) +the Macintosh depends on the underlying C library being used.) \subsection{Methods of File Objects \label{fileMethods}} @@ -3144,9 +3144,9 @@ x.f() \end{verbatim} In our example, this will return the string \code{'hello world'}. -However, it is not necessary to call a method right away: \code{x.f} -is a method object, and can be stored away and called at a later -moment, for example: +However, it is not necessary to call a method right away: +\code{x.f} is a method object, and can be stored away and called at a +later time. For example: \begin{verbatim} xf = x.f @@ -3201,9 +3201,9 @@ users (``clients'') of an object. In other words, classes are not usable to implement pure abstract data types. In fact, nothing in Python makes it possible to enforce data hiding --- it is all based upon convention. (On the other hand, the Python implementation, -written in \C{}, can completely hide implementation details and control +written in C, can completely hide implementation details and control access to an object if necessary; this can be used by extensions to -Python written in \C{}.) +Python written in C.) Clients should use data attributes with care --- clients may mess up @@ -3480,7 +3480,7 @@ class VirtualAttributes: \section{Odds and Ends \label{odds}} Sometimes it is useful to have a data type similar to the Pascal -``record'' or \C{} ``struct'', bundling together a couple of named data +``record'' or C ``struct'', bundling together a couple of named data items. An empty class definition will do nicely, e.g.: \begin{verbatim} @@ -3560,9 +3560,9 @@ for c in [B, C, D]: print "B" \end{verbatim} -Note that if the except clauses were reversed (with \samp{except B} -first), it would have printed B, B, B --- the first matching except -clause is triggered. +Note that if the except clauses were reversed (with +\samp{except B} first), it would have printed B, B, B --- the first +matching except clause is triggered. When an error message is printed for an unhandled exception which is a class, the class name is printed, then a colon and a space, and @@ -3579,7 +3579,7 @@ You should read, or at least page through, the Library Reference, which gives complete (though terse) reference material about types, functions, and modules that can save you a lot of time when writing Python programs. The standard Python distribution includes a -\emph{lot} of code in both \C{} and Python; there are modules to read +\emph{lot} of code in both C and Python; there are modules to read \UNIX{} mailboxes, retrieve documents via HTTP, generate random numbers, parse command-line options, write CGI programs, compress data, and a lot more; skimming through the Library Reference will give @@ -3708,9 +3708,9 @@ indented continuation lines...) Automatic completion of variable and module names is optionally available. To enable it in the interpreter's interactive mode, add -the following to your \file{\$HOME/.pythonrc} file:% $ <- bow to font-lock -\indexii{.pythonrc.py}{file}% -\refstmodindex{rlcompleter}% +the following to your \file{\$HOME/.pythonrc.py} file:% $ <- bow to font-lock +\indexii{.pythonrc.py}{file} +\refstmodindex{rlcompleter} \refbimodindex{readline} \begin{verbatim} @@ -3741,4 +3741,3 @@ would also be useful. % XXX Lele Gaifax's readline module, which adds name completion... \end{document} - |