Remove trailing whitespace.

This commit is contained in:
Georg Brandl 2009-01-03 21:18:54 +00:00
parent 3d3558a465
commit 48310cd3f2
127 changed files with 825 additions and 825 deletions

View file

@ -14,7 +14,7 @@ multiple base classes, a derived class can override any methods of its base
class or classes, and a method can call the method of a base class with the same
name. Objects can contain an arbitrary amount of private data.
In C++ terminology, normally class members (including the data members) are
In C++ terminology, normally class members (including the data members) are
*public* (except see below :ref:`tut-private`),
and all member functions are *virtual*. There are no special constructors or
destructors. As in Modula-3, there are no shorthands for referencing the
@ -171,7 +171,7 @@ binding::
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
@ -302,7 +302,7 @@ are passed on to :meth:`__init__`. For example, ::
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
@ -532,7 +532,7 @@ Python has two builtin functions that work with inheritance:
is ``True`` since :class:`bool` is a subclass of :class:`int`. However,
``issubclass(float, int)`` is ``False`` since :class:`float` is not a
subclass of :class:`int`.
.. _tut-multiple:

View file

@ -61,7 +61,7 @@ they appear in the sequence. For example (no pun intended):
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
... print(x, len(x))
...
...
cat 3
window 6
defenestrate 12
@ -74,7 +74,7 @@ convenient::
>>> for x in a[:]: # make a slice copy of the entire list
... if len(x) > 6: a.insert(0, x)
...
...
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']
@ -96,7 +96,7 @@ If you do need to iterate over a sequence of numbers, the built-in function
2
3
4
The given end point is never part of the generated list; ``range(10)`` generates
@ -104,13 +104,13 @@ The given end point is never part of the generated list; ``range(10)`` generates
is possible to let the range start at another number, or to specify a different
increment (even negative; sometimes this is called the 'step')::
range(5, 10)
range(5, 10)
5 through 9
range(0, 10, 3)
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
range(-10, -100, -30)
-10, -40, -70
To iterate over the indices of a sequence, you can combine :func:`range` and
@ -119,7 +119,7 @@ To iterate over the indices of a sequence, you can combine :func:`range` and
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
...
0 Mary
1 had
2 a
@ -135,12 +135,12 @@ A strange thing happens if you just print a range::
range(0, 10)
In many ways the object returned by :func:`range` behaves as if it is a list,
but in fact it isn't. It is an object which returns the successive items of
the desired sequence when you iterate over it, but it doesn't really make
the list, thus saving space.
but in fact it isn't. It is an object which returns the successive items of
the desired sequence when you iterate over it, but it doesn't really make
the list, thus saving space.
We say such an object is *iterable*, that is, suitable as a target for
functions and constructs that expect something from which they can
We say such an object is *iterable*, that is, suitable as a target for
functions and constructs that expect something from which they can
obtain successive items until the supply is exhausted. We have seen that
the :keyword:`for` statement is such an *iterator*. The function :func:`list`
is another; it creates lists from iterables::
@ -177,7 +177,7 @@ following loop, which searches for prime numbers::
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
@ -198,7 +198,7 @@ required syntactically but the program requires no action. For example::
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
...
This is commonly used for creating minimal classes::
@ -212,7 +212,7 @@ at a more abstract level. The :keyword:`pass` is silently ignored::
>>> def initlog(*args):
... pass # Remember to implement this!
...
...
.. _tut-functions:
@ -229,7 +229,7 @@ boundary::
... print(b, end=' ')
... a, b = b, a+b
... print()
...
...
>>> # Now call the function we just defined:
... fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
@ -300,7 +300,7 @@ Fibonacci series, instead of printing it::
... result.append(b) # see below
... a, b = b, a+b
... return result
...
...
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
@ -436,7 +436,7 @@ calls. Here's an example that fails due to this restriction::
>>> def function(a):
... pass
...
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
@ -487,7 +487,7 @@ Arbitrary Argument Lists
------------------------
.. index::
statement: *
statement: *
Finally, the least frequently used option is to specify that a function can be
called with an arbitrary number of arguments. These arguments will be wrapped
@ -497,13 +497,13 @@ zero or more normal arguments may occur. ::
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))
Normally, these ``variadic`` arguments will be last in the list of formal
parameters, because they scoop up all remaining input arguments that are
parameters, because they scoop up all remaining input arguments that are
passed to the function. Any formal parameters which occur after the ``*args``
parameter are 'keyword-only' arguments, meaning that they can only be used as
parameter are 'keyword-only' arguments, meaning that they can only be used as
keywords rather than positional arguments. ::
>>> def concat(*args, sep="/"):
... return sep.join(args)
...
@ -581,7 +581,7 @@ Documentation Strings
single: strings, documentation
Here are some conventions about the content and formatting of documentation
strings.
strings.
The first line should always be a short, concise summary of the object's
purpose. For brevity, it should not explicitly state the object's name or type,
@ -610,11 +610,11 @@ Here is an example of a multi-line docstring::
>>> def my_function():
... """Do nothing, but document it.
...
...
... No, really, it doesn't do anything.
... """
... pass
...
...
>>> print(my_function.__doc__)
Do nothing, but document it.

View file

@ -159,7 +159,7 @@ List Comprehensions
List comprehensions provide a concise way to create lists from sequences.
Common applications are to make lists where each element is the result of
some operations applied to each member of the sequence, or to create a
some operations applied to each member of the sequence, or to create a
subsequence of those elements that satisfy a certain condition.
@ -167,7 +167,7 @@ Each list comprehension consists of an expression followed by a :keyword:`for`
clause, then zero or more :keyword:`for` or :keyword:`if` clauses. The result
will be a list resulting from evaluating the expression in the context of the
:keyword:`for` and :keyword:`if` clauses which follow it. If the expression
would evaluate to a tuple, it must be parenthesized.
would evaluate to a tuple, it must be parenthesized.
Here we take a list of numbers and return a list of three times each number::
@ -227,7 +227,7 @@ If you've got the stomach for it, list comprehensions can be nested. They are a
powerful tool but -- like all powerful tools -- they need to be used carefully,
if at all.
Consider the following example of a 3x3 matrix held as a list containing three
Consider the following example of a 3x3 matrix held as a list containing three
lists, one list per row::
>>> mat = [
@ -236,7 +236,7 @@ lists, one list per row::
... [7, 8, 9],
... ]
Now, if you wanted to swap rows and columns, you could use a list
Now, if you wanted to swap rows and columns, you could use a list
comprehension::
>>> print([[row[i] for row in mat] for i in [0, 1, 2]])
@ -254,7 +254,7 @@ A more verbose version of this snippet shows the flow explicitly::
print(row[i], end="")
print()
In real world, you should prefer builtin functions to complex flow statements.
In real world, you should prefer builtin functions to complex flow statements.
The :func:`zip` function would do a great job for this use case::
>>> list(zip(*mat))

View file

@ -91,7 +91,7 @@ is signalled by raising the :exc:`KeyboardInterrupt` exception. ::
... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
...
...
The :keyword:`try` statement works as follows.
@ -195,12 +195,12 @@ indirectly) in the try clause. For example::
>>> def this_fails():
... x = 1/0
...
...
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print('Handling run-time error:', err)
...
...
Handling run-time error: int division or modulo by zero
@ -251,12 +251,12 @@ directly or indirectly. For example::
... self.value = value
... def __str__(self):
... return repr(self.value)
...
...
>>> try:
... raise MyError(2*2)
... except MyError as e:
... print('My exception occurred, value:', e.value)
...
...
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
@ -326,7 +326,7 @@ example::
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
...
Goodbye, world!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
@ -389,9 +389,9 @@ and print its contents to the screen. ::
print(line)
The problem with this code is that it leaves the file open for an indeterminate
amount of time after this part of the code has finished executing.
This is not an issue in simple scripts, but can be a problem for larger
applications. The :keyword:`with` statement allows objects like files to be
amount of time after this part of the code has finished executing.
This is not an issue in simple scripts, but can be a problem for larger
applications. The :keyword:`with` statement allows objects like files to be
used in a way that ensures they are always cleaned up promptly and correctly. ::
with open("myfile.txt") as f:

View file

@ -1,7 +1,7 @@
.. _tutorial-index:
######################
The Python Tutorial
The Python Tutorial
######################
:Release: |version|

View file

@ -90,7 +90,7 @@ Here are two ways to write a table of squares and cubes::
>>> for x in range(1, 11):
... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
...
1 1 1
2 4 8
3 9 27
@ -165,7 +165,7 @@ number of characters wide. This is useful for making tables pretty.::
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print('{0:10} ==> {1:10d}'.format(name, phone))
...
...
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127
@ -343,7 +343,7 @@ beginning of the file as the reference point. ::
16
>>> f.seek(5) # Go to the 6th byte in the file
5
>>> f.read(1)
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
13
@ -353,7 +353,7 @@ beginning of the file as the reference point. ::
In text files (those opened without a ``b`` in the mode string), only seeks
relative to the beginning of the file are allowed (the exception being seeking
to the very file end with ``seek(0, 2)``).
When you're done with a file, call ``f.close()`` to close it and free up any
system resources taken up by the open file. After calling ``f.close()``,
attempts to use the file object will automatically fail. ::

View file

@ -115,7 +115,7 @@ example, take a look at this :keyword:`if` statement::
>>> the_world_is_flat = 1
>>> if the_world_is_flat:
... print("Be careful not to fall off!")
...
...
Be careful not to fall off!
@ -191,7 +191,7 @@ It is also possible to specify a different encoding for source files. In order
to do this, put one more special comment line right after the ``#!`` line to
define the source file encoding::
# -*- coding: encoding -*-
# -*- coding: encoding -*-
With that declaration, everything in the source file will be treated as having
the encoding *encoding* instead of UTF-8. The list of possible encodings can be

View file

@ -58,7 +58,7 @@ operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
>>> 8/5 # Fractions aren't lost when dividing integers
1.6000000000000001
Note: You might not see exactly the same result; floating point results can
Note: You might not see exactly the same result; floating point results can
differ from one machine to another. We will say more later about controlling
the appearance of floating point output; what we see here is the most
informative display but not as easy to read as we would get with::
@ -71,9 +71,9 @@ unless we are specifically discussing output formatting, and explain later
why these two ways of displaying floating point data come to be different.
See :ref:`tut-fp-issues` for a full discussion.
To do integer division and get an integer result,
To do integer division and get an integer result,
discarding any fractional result, there is another operator, ``//``::
>>> # Integer division returns the floor:
... 7//3
2
@ -103,7 +103,7 @@ error will occur::
>>> # try to access an undefined variable
... n
Traceback (most recent call last):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
@ -245,14 +245,14 @@ Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or
they will be included in the string. ::
print("""
Usage: thingy [OPTIONS]
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
produces the following output::
Usage: thingy [OPTIONS]
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
@ -371,10 +371,10 @@ One way to remember how slices work is to think of the indices as pointing
Then the right edge of the last character of a string of *n* characters has
index *n*, for example::
+---+---+---+---+---+
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
The first row of numbers gives the position of the indices 0...5 in the string;
@ -396,7 +396,7 @@ The built-in function :func:`len` returns the length of a string::
.. seealso::
:ref:`typesseq`
Strings are examples of *sequence types*, and support the common
Strings are examples of *sequence types*, and support the common
operations supported by such types.
:ref:`string-methods`
@ -565,7 +565,7 @@ series as follows::
>>> while b < 10:
... print(b)
... a, b = b, a+b
...
...
1
1
2
@ -601,8 +601,8 @@ This example introduces several new features.
* The :func:`print` function writes the value of the expression(s) it is
given. It differs from just writing the expression you want to write (as we did
earlier in the calculator examples) in the way it handles multiple
expressions, floating point quantities,
earlier in the calculator examples) in the way it handles multiple
expressions, floating point quantities,
and strings. Strings are printed without quotes, and a space is inserted
between items, so you can format things nicely, like this::
@ -617,5 +617,5 @@ This example introduces several new features.
>>> while b < 1000:
... print(b, end=' ')
... a, b = b, a+b
...
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

View file

@ -103,8 +103,8 @@ There is even a variant to import all names that a module defines::
1 1 2 3 5 8 13 21 34 55 89 144 233 377
This imports all names except those beginning with an underscore (``_``).
In most cases Python programmers do not use this facility since it introduces
an unknown set of names into the interpreter, possibly hiding some things
In most cases Python programmers do not use this facility since it introduces
an unknown set of names into the interpreter, possibly hiding some things
you have already defined.
.. note::
@ -287,7 +287,7 @@ defines. It returns a sorted list of strings::
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'callstats', 'copyright',
'displayhook', 'exc_info', 'excepthook',
'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
@ -317,25 +317,25 @@ want a list of those, they are defined in the standard module
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'Buffer
Error', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Excep
tion', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError
', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImp
lemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecatio
nWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StopIteration',
'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', '
UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueE
rror', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__'
, '__import__', '__name__', 'abs', 'all', 'any', 'basestring', 'bin', 'bool', 'b
uffer', 'bytes', 'chr', 'chr8', 'classmethod', 'cmp', 'compile', 'complex', 'cop
yright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'ex
ec', 'exit', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'h
ash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', '
len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'o
bject', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr
', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'st
r', 'str8', 'sum', 'super', 'trunc', 'tuple', 'type', 'vars', 'zip']
Error', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Excep
tion', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError
', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImp
lemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecatio
nWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StopIteration',
'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', '
UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueE
rror', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__'
, '__import__', '__name__', 'abs', 'all', 'any', 'basestring', 'bin', 'bool', 'b
uffer', 'bytes', 'chr', 'chr8', 'classmethod', 'cmp', 'compile', 'complex', 'cop
yright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'ex
ec', 'exit', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'h
ash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', '
len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'o
bject', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr
', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'st
r', 'str8', 'sum', 'super', 'trunc', 'tuple', 'type', 'vars', 'zip']
.. _tut-packages:

View file

@ -136,7 +136,7 @@ The :mod:`random` module provides tools for making random selections::
>>> random.random() # random float
0.17970987693706186
>>> random.randrange(6) # random integer chosen from range(6)
4
4
The SciPy project <http://scipy.org> has many other modules for numerical
computations.

View file

@ -174,7 +174,7 @@ tasks in background while the main program continues to run::
class AsyncZip(threading.Thread):
def __init__(self, infile, outfile):
threading.Thread.__init__(self)
threading.Thread.__init__(self)
self.infile = infile
self.outfile = outfile
def run(self):
@ -358,11 +358,11 @@ For example, calculating a 5% tax on a 70 cent phone charge gives different
results in decimal floating point and binary floating point. The difference
becomes significant if the results are rounded to the nearest cent::
>>> from decimal import *
>>> from decimal import *
>>> Decimal('0.70') * Decimal('1.05')
Decimal("0.7350")
>>> .70 * 1.05
0.73499999999999999
0.73499999999999999
The :class:`Decimal` result keeps a trailing zero, automatically inferring four
place significance from multiplicands with two place significance. Decimal
@ -380,7 +380,7 @@ calculations and equality tests that are unsuitable for binary floating point::
>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> sum([0.1]*10) == 1.0
False
False
The :mod:`decimal` module provides arithmetic with as much precision as needed::

View file

@ -49,8 +49,8 @@ More Python resources:
Cookbook (O'Reilly & Associates, ISBN 0-596-00797-3.)
* http://scipy.org: The Scientific Python project includes modules for fast
array computations and manipulations plus a host of packages for such
things as linear algebra, Fourier transforms, non-linear solvers,
array computations and manipulations plus a host of packages for such
things as linear algebra, Fourier transforms, non-linear solvers,
random number distributions, statistical analysis and the like.
For Python-related questions and problem reports, you can post to the newsgroup
@ -68,6 +68,6 @@ solution for your problem.
.. Postings figure based on average of last six months activity as
reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182
days = 116.9 msgs / day and steadily increasing. (XXX up to date figures?)
days = 116.9 msgs / day and steadily increasing. (XXX up to date figures?)