summaryrefslogtreecommitdiffstats
path: root/Doc/tutorial
diff options
context:
space:
mode:
Diffstat (limited to 'Doc/tutorial')
-rw-r--r--Doc/tutorial/appendix.rst124
-rw-r--r--Doc/tutorial/classes.rst79
-rw-r--r--Doc/tutorial/controlflow.rst23
-rw-r--r--Doc/tutorial/datastructures.rst22
-rw-r--r--Doc/tutorial/errors.rst4
-rw-r--r--Doc/tutorial/index.rst3
-rw-r--r--Doc/tutorial/inputoutput.rst4
-rw-r--r--Doc/tutorial/interactive.rst153
-rw-r--r--Doc/tutorial/interpreter.rst148
-rw-r--r--Doc/tutorial/introduction.rst6
-rw-r--r--Doc/tutorial/modules.rst45
-rw-r--r--Doc/tutorial/stdlib.rst13
-rw-r--r--Doc/tutorial/stdlib2.rst2
-rw-r--r--Doc/tutorial/whatnow.rst14
14 files changed, 313 insertions, 327 deletions
diff --git a/Doc/tutorial/appendix.rst b/Doc/tutorial/appendix.rst
new file mode 100644
index 0000000..8670efc
--- /dev/null
+++ b/Doc/tutorial/appendix.rst
@@ -0,0 +1,124 @@
+.. _tut-appendix:
+
+********
+Appendix
+********
+
+
+.. _tut-interac:
+
+Interactive Mode
+================
+
+.. _tut-error:
+
+Error Handling
+--------------
+
+When an error occurs, the interpreter prints an error message and a stack trace.
+In interactive mode, it then returns to the primary prompt; when input came from
+a file, it exits with a nonzero exit status after printing the stack trace.
+(Exceptions handled by an :keyword:`except` clause in a :keyword:`try` statement
+are not errors in this context.) Some errors are unconditionally fatal and
+cause an exit with a nonzero exit; this applies to internal inconsistencies and
+some cases of running out of memory. All error messages are written to the
+standard error stream; normal output from executed commands is written to
+standard output.
+
+Typing the interrupt character (usually Control-C or DEL) to the primary or
+secondary prompt cancels the input and returns to the primary prompt. [#]_
+Typing an interrupt while a command is executing raises the
+:exc:`KeyboardInterrupt` exception, which may be handled by a :keyword:`try`
+statement.
+
+
+.. _tut-scripts:
+
+Executable Python Scripts
+-------------------------
+
+On BSD'ish Unix systems, Python scripts can be made directly executable, like
+shell scripts, by putting the line ::
+
+ #!/usr/bin/env python3.4
+
+(assuming that the interpreter is on the user's :envvar:`PATH`) at the beginning
+of the script and giving the file an executable mode. The ``#!`` must be the
+first two characters of the file. On some platforms, this first line must end
+with a Unix-style line ending (``'\n'``), not a Windows (``'\r\n'``) line
+ending. Note that the hash, or pound, character, ``'#'``, is used to start a
+comment in Python.
+
+The script can be given an executable mode, or permission, using the
+:program:`chmod` command.
+
+.. code-block:: bash
+
+ $ chmod +x myscript.py
+
+On Windows systems, there is no notion of an "executable mode". The Python
+installer automatically associates ``.py`` files with ``python.exe`` so that
+a double-click on a Python file will run it as a script. The extension can
+also be ``.pyw``, in that case, the console window that normally appears is
+suppressed.
+
+
+.. _tut-startup:
+
+The Interactive Startup File
+----------------------------
+
+When you use Python interactively, it is frequently handy to have some standard
+commands executed every time the interpreter is started. You can do this by
+setting an environment variable named :envvar:`PYTHONSTARTUP` to the name of a
+file containing your start-up commands. This is similar to the :file:`.profile`
+feature of the Unix shells.
+
+This file is only read in interactive sessions, not when Python reads commands
+from a script, and not when :file:`/dev/tty` is given as the explicit source of
+commands (which otherwise behaves like an interactive session). It is executed
+in the same namespace where interactive commands are executed, so that objects
+that it defines or imports can be used without qualification in the interactive
+session. You can also change the prompts ``sys.ps1`` and ``sys.ps2`` in 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 using code like ``if
+os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())``.
+If you want to use the startup file in a script, you must do this explicitly
+in the script::
+
+ import os
+ filename = os.environ.get('PYTHONSTARTUP')
+ if filename and os.path.isfile(filename):
+ with open(filename) as fobj:
+ startup_file = fobj.read()
+ exec(startup_file)
+
+
+.. _tut-customize:
+
+The Customization Modules
+-------------------------
+
+Python provides two hooks to let you customize it: :mod:`sitecustomize` and
+:mod:`usercustomize`. To see how it works, you need first to find the location
+of your user site-packages directory. Start Python and run this code::
+
+ >>> import site
+ >>> site.getusersitepackages()
+ '/home/user/.local/lib/python3.4/site-packages'
+
+Now you can create a file named :file:`usercustomize.py` in that directory and
+put anything you want in it. It will affect every invocation of Python, unless
+it is started with the :option:`-s` option to disable the automatic import.
+
+:mod:`sitecustomize` works in the same way, but is typically created by an
+administrator of the computer in the global site-packages directory, and is
+imported before :mod:`usercustomize`. See the documentation of the :mod:`site`
+module for more details.
+
+
+.. rubric:: Footnotes
+
+.. [#] A problem with the GNU Readline package may prevent this.
diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst
index 08072a3..7e014ef 100644
--- a/Doc/tutorial/classes.rst
+++ b/Doc/tutorial/classes.rst
@@ -387,6 +387,77 @@ object and the argument list, and the function object is called with this new
argument list.
+.. _tut-class-and-instance-variables:
+
+Class and Instance Variables
+----------------------------
+
+Generally speaking, instance variables are for data unique to each instance
+and class variables are for attributes and methods shared by all instances
+of the class::
+
+ class Dog:
+
+ kind = 'canine' # class variable shared by all instances
+
+ def __init__(self, name):
+ self.name = name # instance variable unique to each instance
+
+ >>> d = Dog('Fido')
+ >>> e = Dog('Buddy')
+ >>> d.kind # shared by all dogs
+ 'canine'
+ >>> e.kind # shared by all dogs
+ 'canine'
+ >>> d.name # unique to d
+ 'Fido'
+ >>> e.name # unique to e
+ 'Buddy'
+
+As discussed in :ref:`tut-object`, shared data can have possibly surprising
+effects with involving :term:`mutable` objects such as lists and dictionaries.
+For example, the *tricks* list in the following code should not be used as a
+class variable because just a single list would be shared by all *Dog*
+instances::
+
+ class Dog:
+
+ tricks = [] # mistaken use of a class variable
+
+ def __init__(self, name):
+ self.name = name
+
+ def add_trick(self, trick):
+ self.tricks.append(trick)
+
+ >>> d = Dog('Fido')
+ >>> e = Dog('Buddy')
+ >>> d.add_trick('roll over')
+ >>> e.add_trick('play dead')
+ >>> d.tricks # unexpectedly shared by all dogs
+ ['roll over', 'play dead']
+
+Correct design of the class should use an instance variable instead::
+
+ class Dog:
+
+ def __init__(self, name):
+ self.name = name
+ self.tricks = [] # creates a new empty list for each dog
+
+ def add_trick(self, trick):
+ self.tricks.append(trick)
+
+ >>> d = Dog('Fido')
+ >>> e = Dog('Buddy')
+ >>> d.add_trick('roll over')
+ >>> e.add_trick('play dead')
+ >>> d.tricks
+ ['roll over']
+ >>> e.tricks
+ ['play dead']
+
+
.. _tut-remarks:
Random Remarks
@@ -572,7 +643,7 @@ class, that calls each parent only once, and that is monotonic (meaning that a
class can be subclassed without affecting the precedence order of its parents).
Taken together, these properties make it possible to design reliable and
extensible classes with multiple inheritance. For more detail, see
-http://www.python.org/download/releases/2.3/mro/.
+https://www.python.org/download/releases/2.3/mro/.
.. _tut-private:
@@ -731,7 +802,7 @@ using a :keyword:`for` statement::
for char in "123":
print(char)
for line in open("myfile.txt"):
- print(line)
+ print(line, end='')
This style of access is clear, concise, and convenient. The use of iterators
pervades and unifies Python. Behind the scenes, the :keyword:`for` statement
@@ -798,7 +869,7 @@ Generators
:term:`Generator`\s are a simple and powerful tool for creating iterators. They
are written like regular functions but use the :keyword:`yield` statement
whenever they want to return data. Each time :func:`next` is called on it, the
-generator resumes where it left-off (it remembers all the data values and which
+generator resumes where it left off (it remembers all the data values and which
statement was last executed). An example shows that generators can be trivially
easy to create::
@@ -816,7 +887,7 @@ easy to create::
o
g
-Anything that can be done with generators can also be done with class based
+Anything that can be done with generators can also be done with class-based
iterators as described in the previous section. What makes generators so
compact is that the :meth:`__iter__` and :meth:`~generator.__next__` methods
are created automatically.
diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst
index 97aea4f..813c828 100644
--- a/Doc/tutorial/controlflow.rst
+++ b/Doc/tutorial/controlflow.rst
@@ -370,7 +370,7 @@ defined to allow. For example::
return False
retries = retries - 1
if retries < 0:
- raise IOError('uncooperative user')
+ raise OSError('uncooperative user')
print(complaint)
This function can be called in several ways:
@@ -673,11 +673,9 @@ Function Annotations
pair: function; annotations
single: -> (return annotation assignment)
-:ref:`Function annotations <function>` are completely optional,
-arbitrary metadata information about user-defined functions. Neither Python
-itself nor the standard library use function annotations in any way; this
-section just shows the syntax. Third-party projects are free to use function
-annotations for documentation, type checking, and other uses.
+:ref:`Function annotations <function>` are completely optional metadata
+information about the types used by user-defined functions (see :pep:`484`
+for more information).
Annotations are stored in the :attr:`__annotations__` attribute of the function
as a dictionary and have no effect on any other part of the function. Parameter
@@ -686,16 +684,17 @@ expression evaluating to the value of the annotation. Return annotations are
defined by a literal ``->``, followed by an expression, between the parameter
list and the colon denoting the end of the :keyword:`def` statement. The
following example has a positional argument, a keyword argument, and the return
-value annotated with nonsense::
+value annotated::
- >>> def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
+ >>> def f(ham: str, eggs: str = 'eggs') -> str:
... print("Annotations:", f.__annotations__)
... print("Arguments:", ham, eggs)
+ ... return ham + ' and ' + eggs
...
- >>> f('wonderful')
- Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': 42}
- Arguments: wonderful spam
-
+ >>> f('spam')
+ Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
+ Arguments: spam eggs
+ 'spam and eggs'
.. _tut-codingstyle:
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst
index 24d2d2e..1ea299f 100644
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -111,10 +111,15 @@ An example that uses most of the list methods::
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
+ >>> a.pop()
+ 1234.5
+ >>> a
+ [-1, 1, 66.25, 333, 333]
You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that
-modify the list have no return value printed -- they return ``None``. [1]_ This
-is a design principle for all mutable data structures in Python.
+only modify the list have no return value printed -- they return the default
+``None``. [1]_ This is a design principle for all mutable data structures in
+Python.
.. _tut-lists-as-stacks:
@@ -194,12 +199,17 @@ For example, assume we want to create a list of squares, like::
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
-We can obtain the same result with::
+Note that this creates (or overwrites) a variable named ``x`` that still exists
+after the loop completes. We can calculate the list of squares without any
+side effects using::
+
+ squares = list(map(lambda x: x**2, range(10)))
+
+or, equivalently::
squares = [x**2 for x in range(10)]
-This is also equivalent to ``squares = list(map(lambda x: x**2, range(10)))``,
-but it's more concise and readable.
+which is more concise and readable.
A list comprehension consists of brackets containing an expression followed
by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
@@ -674,7 +684,7 @@ the same type, the lexicographical comparison is carried out recursively. If
all items of two sequences compare equal, the sequences are considered equal.
If one sequence is an initial sub-sequence of the other, the shorter sequence is
the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode
-codepoint number to order individual characters. Some examples of comparisons
+code point number to order individual characters. Some examples of comparisons
between sequences of the same type::
(1, 2, 3) < (1, 2, 4)
diff --git a/Doc/tutorial/errors.rst b/Doc/tutorial/errors.rst
index 4282151..d048ae9 100644
--- a/Doc/tutorial/errors.rst
+++ b/Doc/tutorial/errors.rst
@@ -131,8 +131,8 @@ the exception (allowing a caller to handle the exception as well)::
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
- except IOError as err:
- print("I/O error: {0}".format(err))
+ except OSError as err:
+ print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
diff --git a/Doc/tutorial/index.rst b/Doc/tutorial/index.rst
index 604cff8..c14b1d6 100644
--- a/Doc/tutorial/index.rst
+++ b/Doc/tutorial/index.rst
@@ -12,7 +12,7 @@ and rapid application development in many areas on most platforms.
The Python interpreter and the extensive standard library are freely available
in source or binary form for all major platforms from the Python Web site,
-http://www.python.org/, and may be freely distributed. The same site also
+https://www.python.org/, and may be freely distributed. The same site also
contains distributions of and pointers to many free third party Python modules,
programs and tools, and additional documentation.
@@ -56,3 +56,4 @@ The :ref:`glossary` is also worth going through.
whatnow.rst
interactive.rst
floatingpoint.rst
+ appendix.rst
diff --git a/Doc/tutorial/inputoutput.rst b/Doc/tutorial/inputoutput.rst
index b3bf0ef..6f9c99d 100644
--- a/Doc/tutorial/inputoutput.rst
+++ b/Doc/tutorial/inputoutput.rst
@@ -323,8 +323,8 @@ first::
18
``f.tell()`` returns an integer giving the file object's current position in the file
-represented as number of bytes from the beginning of the file when in `binary mode` and
-an opaque number when in `text mode`.
+represented as number of bytes from the beginning of the file when in binary mode and
+an opaque number when in text mode.
To change the file object's position, use ``f.seek(offset, from_what)``. The position is computed
from adding *offset* to a reference point; the reference point is selected by
diff --git a/Doc/tutorial/interactive.rst b/Doc/tutorial/interactive.rst
index 36acb06..abf30f0 100644
--- a/Doc/tutorial/interactive.rst
+++ b/Doc/tutorial/interactive.rst
@@ -7,140 +7,27 @@ Interactive Input Editing and History Substitution
Some versions of the Python interpreter support editing of the current input
line and history substitution, similar to facilities found in the Korn shell and
the GNU Bash shell. This is implemented using the `GNU Readline`_ library,
-which supports Emacs-style and vi-style editing. This library has its own
-documentation which I won't duplicate here; however, the basics are easily
-explained. The interactive editing and history described here are optionally
-available in the Unix and Cygwin versions of the interpreter.
-
-This chapter does *not* document the editing facilities of Mark Hammond's
-PythonWin package or the Tk-based environment, IDLE, distributed with Python.
-The command line history recall which operates within DOS boxes on NT and some
-other DOS and Windows flavors is yet another beast.
-
-
-.. _tut-lineediting:
-
-Line Editing
-============
-
-If supported, input line editing is active whenever the interpreter prints a
-primary or secondary prompt. The current line can be edited using the
-conventional Emacs control characters. The most important of these are:
-:kbd:`C-A` (Control-A) moves the cursor to the beginning of the line, :kbd:`C-E`
-to the end, :kbd:`C-B` moves it one position to the left, :kbd:`C-F` to the
-right. Backspace erases the character to the left of the cursor, :kbd:`C-D` the
-character to its right. :kbd:`C-K` kills (erases) the rest of the line to the
-right of the cursor, :kbd:`C-Y` yanks back the last killed string.
-:kbd:`C-underscore` undoes the last change you made; it can be repeated for
-cumulative effect.
-
-
-.. _tut-history:
-
-History Substitution
-====================
-
-History substitution works as follows. All non-empty input lines issued are
-saved in a history buffer, and when a new prompt is given you are positioned on
-a new line at the bottom of this buffer. :kbd:`C-P` moves one line up (back) in
-the history buffer, :kbd:`C-N` moves one down. Any line in the history buffer
-can be edited; an asterisk appears in front of the prompt to mark a line as
-modified. Pressing the :kbd:`Return` key passes the current line to the
-interpreter. :kbd:`C-R` starts an incremental reverse search; :kbd:`C-S` starts
-a forward search.
+which supports various styles of editing. This library has its own
+documentation which we won't duplicate here.
.. _tut-keybindings:
-Key Bindings
-============
-
-The key bindings and some other parameters of the Readline library can be
-customized by placing commands in an initialization file called
-:file:`~/.inputrc`. Key bindings have the form ::
-
- key-name: function-name
-
-or ::
-
- "string": function-name
-
-and options can be set with ::
-
- set option-name value
-
-For example::
-
- # I prefer vi-style editing:
- set editing-mode vi
-
- # Edit using a single line:
- set horizontal-scroll-mode On
+Tab Completion and History Editing
+==================================
- # Rebind some keys:
- Meta-h: backward-kill-word
- "\C-u": universal-argument
- "\C-x\C-r": re-read-init-file
-
-Note that the default binding for :kbd:`Tab` in Python is to insert a :kbd:`Tab`
-character instead of Readline's default filename completion function. If you
-insist, you can override this by putting ::
-
- Tab: complete
-
-in your :file:`~/.inputrc`. (Of course, this makes it harder to type indented
-continuation lines if you're accustomed to using :kbd:`Tab` for that purpose.)
-
-.. index::
- module: rlcompleter
- module: readline
-
-Automatic completion of variable and module names is optionally available. To
-enable it in the interpreter's interactive mode, add the following to your
-startup file: [#]_ ::
-
- import rlcompleter, readline
- readline.parse_and_bind('tab: complete')
-
-This binds the :kbd:`Tab` key to the completion function, so hitting the
-:kbd:`Tab` key twice suggests completions; it looks at Python statement names,
-the current local variables, and the available module names. For dotted
-expressions such as ``string.a``, it will evaluate the expression up to the
-final ``'.'`` and then suggest completions from the attributes of the resulting
-object. Note that this may execute application-defined code if an object with a
-:meth:`__getattr__` method is part of the expression.
-
-A more capable startup file might look like this example. Note that this
-deletes the names it creates once they are no longer needed; this is done since
-the startup file is executed in the same namespace as the interactive commands,
-and removing the names avoids creating side effects in the interactive
-environment. You may find it convenient to keep some of the imported modules,
-such as :mod:`os`, which turn out to be needed in most sessions with the
-interpreter. ::
-
- # Add auto-completion and a stored history file of commands to your Python
- # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
- # bound to the Esc key by default (you can change it - see readline docs).
- #
- # Store the file in ~/.pystartup, and set an environment variable to point
- # to it: "export PYTHONSTARTUP=~/.pystartup" in bash.
-
- import atexit
- import os
- import readline
- import rlcompleter
-
- historyPath = os.path.expanduser("~/.pyhistory")
-
- def save_history(historyPath=historyPath):
- import readline
- readline.write_history_file(historyPath)
-
- if os.path.exists(historyPath):
- readline.read_history_file(historyPath)
-
- atexit.register(save_history)
- del os, atexit, readline, rlcompleter, save_history, historyPath
+Completion of variable and module names is
+:ref:`automatically enabled <rlcompleter-config>` at interpreter startup so
+that the :kbd:`Tab` key invokes the completion function; it looks at
+Python statement names, the current local variables, and the available
+module names. For dotted expressions such as ``string.a``, it will evaluate
+the expression up to the final ``'.'`` and then suggest completions from
+the attributes of the resulting object. Note that this may execute
+application-defined code if an object with a :meth:`__getattr__` method
+is part of the expression. The default configuration also saves your
+history into a file named :file:`.python_history` in your user directory.
+The history will be available again during the next interactive interpreter
+session.
.. _tut-commentary:
@@ -162,14 +49,6 @@ into other applications. Another similar enhanced interactive environment is
bpython_.
-.. rubric:: Footnotes
-
-.. [#] Python will execute the contents of a file identified by the
- :envvar:`PYTHONSTARTUP` environment variable when you start an interactive
- interpreter. To customize Python even for non-interactive mode, see
- :ref:`tut-customize`.
-
-
.. _GNU Readline: http://tiswww.case.edu/php/chet/readline/rltop.html
.. _IPython: http://ipython.scipy.org/
.. _bpython: http://www.bpython-interpreter.org/
diff --git a/Doc/tutorial/interpreter.rst b/Doc/tutorial/interpreter.rst
index cdc2bf2..8051634 100644
--- a/Doc/tutorial/interpreter.rst
+++ b/Doc/tutorial/interpreter.rst
@@ -10,13 +10,13 @@ Using the Python Interpreter
Invoking the Interpreter
========================
-The Python interpreter is usually installed as :file:`/usr/local/bin/python3.3`
+The Python interpreter is usually installed as :file:`/usr/local/bin/python3.4`
on those machines where it is available; putting :file:`/usr/local/bin` in your
Unix shell's search path makes it possible to start it by typing the command:
.. code-block:: text
- python3.3
+ python3.4
to the shell. [#]_ Since the choice of the directory where the interpreter lives
is an installation option, other places are possible; check with your local
@@ -24,26 +24,25 @@ Python guru or system administrator. (E.g., :file:`/usr/local/python` is a
popular alternative location.)
On Windows machines, the Python installation is usually placed in
-:file:`C:\\Python33`, though you can change this when you're running the
+:file:`C:\\Python34`, though you can change this when you're running the
installer. To add this directory to your path, you can type the following
command into the command prompt in a DOS box::
- set path=%path%;C:\python33
+ set path=%path%;C:\python34
Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on
Windows) at the primary prompt causes the interpreter to exit with a zero exit
status. If that doesn't work, you can exit the interpreter by typing the
following command: ``quit()``.
-The interpreter's line-editing features usually aren't very sophisticated. On
-Unix, whoever installed the interpreter may have enabled support for the GNU
-readline library, which adds more elaborate interactive editing and history
-features. Perhaps the quickest check to see whether command line editing is
-supported is typing Control-P to the first Python prompt you get. If it beeps,
-you have command line editing; see Appendix :ref:`tut-interacting` for an
-introduction to the keys. If nothing appears to happen, or if ``^P`` is echoed,
-command line editing isn't available; you'll only be able to use backspace to
-remove characters from the current line.
+The interpreter's line-editing features include interactive editing, history
+substitution and code completion on systems that support readline. Perhaps the
+quickest check to see whether command line editing is supported is typing
+Control-P to the first Python prompt you get. If it beeps, you have command
+line editing; see Appendix :ref:`tut-interacting` for an introduction to the
+keys. If nothing appears to happen, or if ``^P`` is echoed, command line
+editing isn't available; you'll only be able to use backspace to remove
+characters from the current line.
The interpreter operates somewhat like the Unix shell: when called with standard
input connected to a tty device, it reads and executes commands interactively;
@@ -64,6 +63,8 @@ When a script file is used, it is sometimes useful to be able to run the script
and enter interactive mode afterwards. This can be done by passing :option:`-i`
before the script.
+All command line options are described in :ref:`using-on-general`.
+
.. _tut-argpassing:
@@ -95,9 +96,9 @@ with the *secondary prompt*, by default three dots (``...``). The interpreter
prints a welcome message stating its version number and a copyright notice
before printing the first prompt::
- $ python3.3
- Python 3.3 (default, Sep 24 2012, 09:25:04)
- [GCC 4.6.3] on linux2
+ $ python3.4
+ Python 3.4 (default, Mar 16 2014, 09:25:04)
+ [GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
@@ -106,70 +107,22 @@ before printing the first prompt::
Continuation lines are needed when entering a multi-line construct. As an
example, take a look at this :keyword:`if` statement::
- >>> the_world_is_flat = 1
+ >>> the_world_is_flat = True
>>> if the_world_is_flat:
... print("Be careful not to fall off!")
...
Be careful not to fall off!
+For more on interactive mode, see :ref:`tut-interac`.
+
+
.. _tut-interp:
The Interpreter and Its Environment
===================================
-.. _tut-error:
-
-Error Handling
---------------
-
-When an error occurs, the interpreter prints an error message and a stack trace.
-In interactive mode, it then returns to the primary prompt; when input came from
-a file, it exits with a nonzero exit status after printing the stack trace.
-(Exceptions handled by an :keyword:`except` clause in a :keyword:`try` statement
-are not errors in this context.) Some errors are unconditionally fatal and
-cause an exit with a nonzero exit; this applies to internal inconsistencies and
-some cases of running out of memory. All error messages are written to the
-standard error stream; normal output from executed commands is written to
-standard output.
-
-Typing the interrupt character (usually Control-C or DEL) to the primary or
-secondary prompt cancels the input and returns to the primary prompt. [#]_
-Typing an interrupt while a command is executing raises the
-:exc:`KeyboardInterrupt` exception, which may be handled by a :keyword:`try`
-statement.
-
-
-.. _tut-scripts:
-
-Executable Python Scripts
--------------------------
-
-On BSD'ish Unix systems, Python scripts can be made directly executable, like
-shell scripts, by putting the line ::
-
- #! /usr/bin/env python3.3
-
-(assuming that the interpreter is on the user's :envvar:`PATH`) at the beginning
-of the script and giving the file an executable mode. The ``#!`` must be the
-first two characters of the file. On some platforms, this first line must end
-with a Unix-style line ending (``'\n'``), not a Windows (``'\r\n'``) line
-ending. Note that the hash, or pound, character, ``'#'``, is used to start a
-comment in Python.
-
-The script can be given an executable mode, or permission, using the
-:program:`chmod` command::
-
- $ chmod +x myscript.py
-
-On Windows systems, there is no notion of an "executable mode". The Python
-installer automatically associates ``.py`` files with ``python.exe`` so that
-a double-click on a Python file will run it as a script. The extension can
-also be ``.pyw``, in that case, the console window that normally appears is
-suppressed.
-
-
.. _tut-source-encoding:
Source Code Encoding
@@ -203,67 +156,8 @@ files. The special encoding comment must be in the *first or second* line
within the file.
-.. _tut-startup:
-
-The Interactive Startup File
-----------------------------
-
-When you use Python interactively, it is frequently handy to have some standard
-commands executed every time the interpreter is started. You can do this by
-setting an environment variable named :envvar:`PYTHONSTARTUP` to the name of a
-file containing your start-up commands. This is similar to the :file:`.profile`
-feature of the Unix shells.
-
-.. XXX This should probably be dumped in an appendix, since most people
- don't use Python interactively in non-trivial ways.
-
-This file is only read in interactive sessions, not when Python reads commands
-from a script, and not when :file:`/dev/tty` is given as the explicit source of
-commands (which otherwise behaves like an interactive session). It is executed
-in the same namespace where interactive commands are executed, so that objects
-that it defines or imports can be used without qualification in the interactive
-session. You can also change the prompts ``sys.ps1`` and ``sys.ps2`` in 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 using code like ``if
-os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())``.
-If you want to use the startup file in a script, you must do this explicitly
-in the script::
-
- import os
- filename = os.environ.get('PYTHONSTARTUP')
- if filename and os.path.isfile(filename):
- exec(open(filename).read())
-
-
-.. _tut-customize:
-
-The Customization Modules
--------------------------
-
-Python provides two hooks to let you customize it: :mod:`sitecustomize` and
-:mod:`usercustomize`. To see how it works, you need first to find the location
-of your user site-packages directory. Start Python and run this code:
-
- >>> import site
- >>> site.getusersitepackages()
- '/home/user/.local/lib/python3.2/site-packages'
-
-Now you can create a file named :file:`usercustomize.py` in that directory and
-put anything you want in it. It will affect every invocation of Python, unless
-it is started with the :option:`-s` option to disable the automatic import.
-
-:mod:`sitecustomize` works in the same way, but is typically created by an
-administrator of the computer in the global site-packages directory, and is
-imported before :mod:`usercustomize`. See the documentation of the :mod:`site`
-module for more details.
-
-
.. rubric:: Footnotes
.. [#] On Unix, the Python 3.x interpreter is by default not installed with the
executable named ``python``, so that it does not conflict with a
simultaneously installed Python 2.x executable.
-
-.. [#] A problem with the GNU Readline package may prevent this.
diff --git a/Doc/tutorial/introduction.rst b/Doc/tutorial/introduction.rst
index 9efd1ac..531d06b 100644
--- a/Doc/tutorial/introduction.rst
+++ b/Doc/tutorial/introduction.rst
@@ -1,4 +1,4 @@
-.. _tut-informal:
+.. _tut-informal:
**********************************
An Informal Introduction to Python
@@ -305,7 +305,7 @@ indices, if both are within bounds. For example, the length of ``word[1:3]`` is
Attempting to use a index that is too large will result in an error::
- >>> word[42] # the word only has 7 characters
+ >>> word[42] # the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
@@ -391,7 +391,7 @@ means that the following slice returns a new (shallow) copy of the list::
>>> squares[:]
[1, 4, 9, 16, 25]
-Lists also supports operations like concatenation::
+Lists also support operations like concatenation::
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
diff --git a/Doc/tutorial/modules.rst b/Doc/tutorial/modules.rst
index 1902964..fd361ae 100644
--- a/Doc/tutorial/modules.rst
+++ b/Doc/tutorial/modules.rst
@@ -165,10 +165,16 @@ a built-in module with that name. If not found, it then searches for a file
named :file:`spam.py` in a list of directories given by the variable
:data:`sys.path`. :data:`sys.path` is initialized from these locations:
-* the directory containing the input script (or the current directory).
+* The directory containing the input script (or the current directory when no
+ file is specified).
* :envvar:`PYTHONPATH` (a list of directory names, with the same syntax as the
shell variable :envvar:`PATH`).
-* the installation-dependent default.
+* The installation-dependent default.
+
+.. note::
+ On file systems which support symlinks, the directory containing the input
+ script is calculated after the symlink is followed. In other words the
+ directory containing the symlink is **not** added to the module search path.
After initialization, Python programs can modify :data:`sys.path`. The
directory containing the script being run is placed at the beginning of the
@@ -278,24 +284,23 @@ defines. It returns a sorted list of strings::
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys) # doctest: +NORMALIZE_WHITESPACE
- ['__displayhook__', '__doc__', '__egginsert', '__excepthook__',
- '__loader__', '__name__', '__package__', '__plen', '__stderr__',
- '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames',
- '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions',
- 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix',
- 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',
- 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',
- 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',
- 'float_repr_style', 'getcheckinterval', 'getdefaultencoding',
- 'getdlopenflags', 'getfilesystemencoding', 'getobjects', 'getprofile',
- 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',
- 'gettotalrefcount', 'gettrace', 'hash_info', 'hexversion',
- 'implementation', 'int_info', 'intern', 'maxsize', 'maxunicode',
- 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
- 'platform', 'prefix', 'ps1', 'setcheckinterval', 'setdlopenflags',
- 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace',
- 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info',
- 'warnoptions']
+ ['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
+ '__package__', '__stderr__', '__stdin__', '__stdout__',
+ '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
+ '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
+ 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
+ 'call_tracing', 'callstats', 'copyright', 'displayhook',
+ 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
+ 'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
+ 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
+ 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
+ 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
+ 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
+ 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
+ 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
+ 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
+ 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
+ 'thread_info', 'version', 'version_info', 'warnoptions']
Without arguments, :func:`dir` lists the names you have defined currently::
diff --git a/Doc/tutorial/stdlib.rst b/Doc/tutorial/stdlib.rst
index 7e7a154..d71598e 100644
--- a/Doc/tutorial/stdlib.rst
+++ b/Doc/tutorial/stdlib.rst
@@ -15,7 +15,7 @@ operating system::
>>> import os
>>> os.getcwd() # Return the current working directory
- 'C:\\Python33'
+ 'C:\\Python34'
>>> os.chdir('/server/accesslogs') # Change current working directory
>>> os.system('mkdir today') # Run the command mkdir in the system shell
0
@@ -40,7 +40,9 @@ a higher level interface that is easier to use::
>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
+ 'archive.db'
>>> shutil.move('/build/executables', 'installdir')
+ 'installdir'
.. _tut-file-wildcards:
@@ -151,10 +153,11 @@ protocols. Two of the simplest are :mod:`urllib.request` for retrieving data
from URLs and :mod:`smtplib` for sending mail::
>>> from urllib.request import urlopen
- >>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
- ... line = line.decode('utf-8') # Decoding the binary data to text.
- ... if 'EST' in line or 'EDT' in line: # look for Eastern Time
- ... print(line)
+ >>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
+ ... for line in response:
+ ... line = line.decode('utf-8') # Decoding the binary data to text.
+ ... if 'EST' in line or 'EDT' in line: # look for Eastern Time
+ ... print(line)
<BR>Nov. 25, 09:43:32 PM EST
diff --git a/Doc/tutorial/stdlib2.rst b/Doc/tutorial/stdlib2.rst
index c1dd69a..c0197ea 100644
--- a/Doc/tutorial/stdlib2.rst
+++ b/Doc/tutorial/stdlib2.rst
@@ -277,7 +277,7 @@ applications include caching objects that are expensive to create::
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
d['primary'] # entry was automatically removed
- File "C:/python33/lib/weakref.py", line 46, in __getitem__
+ File "C:/python34/lib/weakref.py", line 46, in __getitem__
o = self.data[key]()
KeyError: 'primary'
diff --git a/Doc/tutorial/whatnow.rst b/Doc/tutorial/whatnow.rst
index 7fcbdc3f..6b03cb5 100644
--- a/Doc/tutorial/whatnow.rst
+++ b/Doc/tutorial/whatnow.rst
@@ -21,8 +21,8 @@ the set are:
and many other tasks. Skimming through the Library Reference will give you an
idea of what's available.
-* :ref:`install-index` explains how to install external modules written by other
- Python users.
+* :ref:`installing-index` explains how to install additional modules written
+ by other Python users.
* :ref:`reference-index`: A detailed explanation of Python's syntax and
semantics. It's heavy reading, but is useful as a complete guide to the
@@ -30,20 +30,20 @@ the set are:
More Python resources:
-* http://www.python.org: The major Python Web site. It contains code,
+* https://www.python.org: The major Python Web site. It contains code,
documentation, and pointers to Python-related pages around the Web. This Web
site is mirrored in various places around the world, such as Europe, Japan, and
Australia; a mirror may be faster than the main site, depending on your
geographical location.
-* http://docs.python.org: Fast access to Python's documentation.
+* https://docs.python.org: Fast access to Python's documentation.
-* http://pypi.python.org: The Python Package Index, previously also nicknamed
+* https://pypi.python.org/pypi: The Python Package Index, previously also nicknamed
the Cheese Shop, is an index of user-created Python modules that are available
for download. Once you begin releasing code, you can register it here so that
others can find it.
-* http://aspn.activestate.com/ASPN/Python/Cookbook/: The Python Cookbook is a
+* http://code.activestate.com/recipes/langs/python/: The Python Cookbook is a
sizable collection of code examples, larger modules, and useful scripts.
Particularly notable contributions are collected in a book also titled Python
Cookbook (O'Reilly & Associates, ISBN 0-596-00797-3.)
@@ -61,7 +61,7 @@ around 120 postings a day (with peaks up to several hundred), asking (and
answering) questions, suggesting new features, and announcing new modules.
Before posting, be sure to check the list of :ref:`Frequently Asked Questions
<faq-index>` (also called the FAQ).
-Mailing list archives are available at http://mail.python.org/pipermail/.
+Mailing list archives are available at https://mail.python.org/pipermail/.
The FAQ answers many of the questions that come up again and again,
and may already contain the solution for your problem.