.. _tut-informal:
**************************************************
An Informal Introduction to Python Python 概要介绍
**************************************************
In the following examples, input and output are distinguished by the presence or
absence of prompts (``>>>`` and ``...``): to repeat the example, you must type
everything after the prompt, when the prompt appears; lines that do not begin
with a prompt are output from the interpreter. Note that a secondary prompt on a
line by itself in an example means you must type a blank line; this is used to
end a multi-line command.
下面的例子中,输入和输出分别由大于号和句号提示符( ``>>>`` 和
```...``` )标注。如果想重现这些例子,就要在解释器的提示符后,输入(提示
符后面的)那些不包含提示符的代码行。需要注意的是在练习中遇到的从属提示符表示
你需要在最后多输入一个空行,解释器才能知道这是一个多行命令的结束。
Many of the examples in this manual, even those entered at the interactive
prompt, include comments. Comments in Python start with the hash character,
``#``, and extend to the end of the physical line. A comment may appear at the
start of a line or following whitespace or code, but not within a string
literal. A hash character within a string literal is just a hash character.
Since comments are to clarify code and are not interpreted by Python, they may
be omitted when typing in examples.
本手册中的很多示例——包括那些带有交互提示符的——都含有注释。Python 中的
注释以 # 字符起始,直至实际的行尾(译注——这里原作者用了
``physical line`` 以表示实际的换行而非编辑器的自动换行)。注释可以从行
首开始,也可以在空白或代码之后,但是不出现在字符串中。文本字符串中的 #
字符仅仅表示 # 。代码中的注释不会被 Python 解释,录入示例的时候可以忽
略它们。
Some examples::
# this is the first comment
SPAM = 1 # and this is the second comment
# ... and now a third!
STRING = "# This is not a comment."
.. _tut-calculator:
Using Python as a Calculator 将 Python 当做计算器
===============================================
Let's try some simple Python commands. Start the interpreter and wait for the
primary prompt, ``>>>``. (It shouldn't take long.)
我们来尝试一些简单的 Python 命令。启动解释器然后等待主提示符 ``>>>``
出现(不需要很久)。
.. _tut-numbers:
Numbers 数值
------------
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 ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
(for example, Pascal or C); parentheses can be used for grouping. For example::
解释器的表示就像一个简单的计算器:可以向其录入一些表达式,它会给出返回
值。表达式语法很直白:运算符 ``+`` , ``-`` , ``*`` 和 ``/`` 与其它语
言一样(例如: Pascal 或 C);括号用于分组。例如 ::
>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2 # and a comment on the same line as code
4
>>> (50-5*6)/4
5
>>> # Integer division returns the floor:
... 7/3
2
>>> 7/-3
-3
The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no
result is displayed before the next interactive prompt::
等号( ``'='`` )用于给变量赋值 ::
>>> width = 20
>>> height = 5*9
>>> width * height
900
A value can be assigned to several variables simultaneously::
一个值可以同时赋给几个变量 ::
>>> x = y = z = 0 # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0
Variables must be "defined" (assigned a value) before they can be used, or an
error will occur::
变量在使用前必须“定义”(赋值),否则会出错 ::
>>> # try to access an undefined variable
... n
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
There is full support for floating point; operators with mixed type operands
convert the integer operand to floating point::
浮点数有完整的支持;与整型混合计算时会自动转为浮点数 ::
>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5
Complex numbers are also supported; imaginary numbers are written with a suffix
of ``j`` or ``J``. Complex numbers with a nonzero real component are written as
``(real+imagj)``, or can be created with the ``complex(real, imag)`` function.
::
复数也得到支持;带有后缀 ``j`` 或 ``J`` 就被视为虚数。带有非零实部的复
数写为 ``(real+imagj)`` ,或者可以用 ``complex(real, imag)`` 函数创建 ::
>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
Complex numbers are always represented as two floating point numbers, the real
and imaginary part. To extract these parts from a complex number *z*, use
``z.real`` and ``z.imag``. ::
复数的实部和虚部总是记为两个浮点数。要从复数 *z* 中提取实部和虚部,使
用 ``z.real`` 和 ``z.imag`` 。 ::
>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5
The conversion functions to floating point and integer (:func:`float`,
:func:`int` and :func:`long`) don't work for complex numbers --- there is no one
correct way to convert a complex number to a real number. Use ``abs(z)`` to get
its magnitude (as a float) or ``z.real`` to get its real part. ::
浮点数和整数之间的转换函数( :func:`float` 和 :func:`int` 以及
:func:`long` ) 不能用于复数。没有什么正确方法可以把一个复数转成一个实
数。函数 ``abs(z)`` 用于获取其模(浮点数)或 ``z.real`` 获取其实部 ::
>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a) # sqrt(a.real**2 + a.imag**2)
5.0
In interactive mode, the last printed expression is assigned to the variable
``_``. This means that when you are using Python as a desk calculator, it is
somewhat easier to continue calculations, for example::
交互模式中,最近一个表达式的值赋给变量 ``_`` 。这样我们就可以把它当作
一个桌面计算器,很方便的用于连续计算,例如 ::
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
This variable should be treated as read-only by the user. Don't explicitly
assign a value to it --- you would create an independent local variable with the
same name masking the built-in variable with its magic behavior.
此变量对于用户是只读的。不要尝试给它赋值 —— 你只会创建一个独立的同名局
部变量,它屏蔽了系统内置变量的魔术效果。
.. _tut-strings:
Strings 字符串
--------------
Besides numbers, Python can also manipulate strings, which can be expressed in
several ways. They can be enclosed in single quotes or double quotes::
相比数值,Python 也提供了可以通过几种不同方式传递的字符串。它们可以用
单引号或双引号标识 ::
>>> 'spam eggs'
'spam eggs'
>>> 'doesn/'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "/"Yes,/" he said."
'"Yes," he said.'
>>> '"Isn/'t," she said.'
'"Isn/'t," she said.'
String literals can span multiple lines in several ways. Continuation lines can
be used, with a backslash as the last character on the line indicating that the
next line is a logical continuation of the line::
字符串文本有几种方法分行。可以使用反斜杠为行结尾的连续字符串,它表示下
一行在逻辑上是本行的继续内容。
hello = "This is a rather long string containing/n/
several lines of text just as you would do in C./n/
Note that whitespace at the beginning of the line is/
significant."
print hello
Note that newlines still need to be embedded in the string using ``/n`` -- the
newline following the trailing backslash is discarded. This example would print
the following:
需要注意的是,还是需要在字符串中写入 ``/n`` ——结尾的反斜杠会被忽略。前
例会打印为如下形式:
.. code-block:: text
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or
``'''``. End of lines do not need to be escaped when using triple-quotes, but
they will be included in the string. ::
另外,字符串可以标识在一对儿三引号中: ``"""`` 或 ``'''`` 。三引号中,
不需要行属转义,它们已经包含在字符串中 ::
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
produces the following output:
得到以下输出 ::
.. code-block:: text
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
If we make the string literal a "raw" string, ``/n`` sequences are not converted
to newlines, but the backslash at the end of the line, and the newline character
in the source, are both included in the string as data. Thus, the example::
如果我们生成一个“原始”字符串, ``/n`` 序列不会被转义,而且行尾的反斜
杠,源码中的换行符,都成为字符串中的一部分数据,因此下例 ::
hello = r"This is a rather long string containing/n/
several lines of text much as you would do in C."
print hello
would print:
会打印:
.. code-block:: text
This is a rather long string containing/n/
several lines of text much as you would do in C.
The interpreter prints the result of string operations in the same way as they
are typed for input: inside quotes, and with quotes and other funny characters
escaped by backslashes, to show the precise value. The string is enclosed in
double quotes if the string contains a single quote and no double quotes, else
it's enclosed in single quotes. (The :keyword:`print` statement, described
later, can be used to write strings without quotes or escapes.)
解释器打印的字符串操作结果与它们输入时的方式一致:以括号标识,包含反斜
杠转义的有趣的字符,以精确的显示值。如果字符串包含单引号,不包含双引
号,它就以双引号标识。否则它以单引号标识。(后面介绍的
:keyword:`print` 语句,可以输出没有标识和转义的字符串。)
Strings can be concatenated (glued together) with the ``+`` operator, and
repeated with ``*``::
字符串可以由 ``+`` 操作符连接(粘到一起),可以由 ``*`` 重复 ::
>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'
Two string literals next to each other are automatically concatenated; the first
line above could also have been written ``word = 'Help' 'A'``; this only works
with two literals, not with arbitrary string expressions::
相邻的两个字符串文本自动连接在一起,前面那行代码也可以写为
``word ='Help' 'A'`` ,它只用于两个字符串文本,不能用于字符串表达式。
>>> 'str' 'ing' # <- This is ok
'string'
>>> 'str'.strip() + 'ing' # <- This is ok
'string'
>>> 'str'.strip() 'ing' # <- This is invalid
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
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
*slice notation*: two indices separated by a colon. ::
字符串也可以被截取(检索)。类似于 C ,字符串的第一个字符索引为 0 。没
有独立的字符类型,字符就是长度为 1 的字符串。类似 Icon ,可以用
*切片标注* 法截取字符串:由两个索引分割的复本。 ::
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
Slice indices have useful defaults; an omitted first index defaults to zero, an
omitted second index defaults to the size of the string being sliced. ::
索引切片可以有默认值,切片时,忽略第一个索引的话,默认为0,忽略第二个
索引,默认为字符串的长度。(其实还有第三个参数,表示切片步长,它默认为
1,完整的切片操作是 word[2:4:1] ——译者) ::
>>> word[:2] # The first two characters
'He'
>>> word[2:] # Everything except the first two characters
'lpA'
Unlike a C string, Python strings cannot be changed. Assigning to an indexed
position in the string results in an error::
不同于 C 字符串,Python 字符串不可变。向字符串文本的某一个索引赋值会引
发错误 ::
>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support slice assignment
However, creating a new string with the combined content is easy and efficient::
不过,组合文本内容生成一个新文本简单而高效 ::
>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'
Here's a useful invariant of slice operations: ``s[:i] + s[i:]`` equals ``s``.
::
切片操作有个有用的不变性: ``s[:i] + s[i:]`` 等于 ``s`` 。 ::
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
Degenerate slice indices are handled gracefully: an index that is too large is
replaced by the string size, an upper bound smaller than the lower bound returns
an empty string. ::
退化的切割检索很优雅:上限过大,会替换为文本长度,上界小于下界则返回空
字符串。 ::
>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''
Indices may be negative numbers, to start counting from the right. For example::
索引可以是负数,此时从右端开始计量。例如 ::
>>> word[-1] # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # Everything except the last two characters
'Hel'
But note that -0 is really the same as 0, so it does not count from the right!
::
不过需要注意的是 -0 实际上就是 0,所以它不会从右边开始计数!
>>> word[-0] # (since -0 equals 0)
'H'
Out-of-range negative slice indices are truncated, but don't try this for
single-element (non-slice) indices::
负索引切片越界会被截断,不要尝试将它用于单元素(非切片)检索 ::
>>> word[-100:]
'HelpA'
>>> word[-10] # error
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
One way to remember how slices work is to think of the indices as pointing
*between* characters, with the left edge of the first character numbered 0.
Then the right edge of the last character of a string of *n* characters has
index *n*, for example::
有个办法可以很容易的记住切片的工作方式:切片时的索引是在两个字符
*之间* 。左边第一个字符的索引为0,,而长度为 *n* 的字符串其最后一个字
符的右界索引为 *n* 。例如 ::
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
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;
the second row gives the corresponding negative indices. The slice from *i* to
*j* consists of all characters between the edges labeled *i* and *j*,
respectively.
文本中的第一行数字给出字符串中的索引点 0...5 。第二行给出相应的负索引。
切片是从 *i* 到 *j* 两个数值标示的边界之间的所有字符。
For non-negative indices, the length of a slice is the difference of the
indices, if both are within bounds. For example, the length of ``word[1:3]`` is
2.
对于非负索引,如果上下都在边界内,切片长度与索引不同。例如,
``word[1:3]`` 是 2 。
The built-in function :func:`len` returns the length of a string::
内置函数 :func:`len` 返回字符串长度 ::
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
.. seealso::
:ref:`typesseq`
Strings, and the Unicode strings described in the next section, are
examples of *sequence types*, and support the common operations supported
by such types.
:ref:`string-methods`
Both strings and Unicode strings support a large number of methods for
basic transformations and searching.
:ref:`new-string-formatting`
Information about string formatting with :meth:`str.format` is described
here.
:ref:`string-formatting`
The old formatting operations invoked when strings and Unicode strings are
the left operand of the ``%`` operator are described in more detail here.
.. _tut-unicodestrings:
Unicode Strings Unicode 文本
----------------------------
.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
Starting with Python 2.0 a new data type for storing text data is available to
the programmer: the Unicode object. It can be used to store and manipulate
Unicode data (see http://www.unicode.org/) and integrates well with the existing
string objects, providing auto-conversions where necessary.
从 Python 2.0 起,程序员们有了一个新的,用来存储文本数据的类型: Unicode
对象。它可以用于存储和维护 Unicode 数据(参见
http://www.unicode.org/ ) ,并且与现有的字符串对象有良好的集成,必要
时提供自动转换。
Unicode has the advantage of providing one ordinal for every character in every
script used in modern and ancient texts. Previously, there were only 256
possible ordinals for script characters. Texts were typically bound to a code
page which mapped the ordinals to script characters. This lead to very much
confusion especially with respect to internationalization (usually written as
``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software. Unicode solves
these problems by defining one code page for all scripts.
Unicode 的先进之处在于为每一种现代或古代使用的文字系统中出现的每一个字符都
提供了统一的序列号。之前,文字系统中的字符只能有 256 种可能的顺序。通过代
码页分界映射。文本绑定到映射文字系统的代码页。这在软件国际化的时候尤其
麻烦 (通常写作 ``i18n`` —— ``'i'`` + 18 个字符 + ``'n'`` )。 Unicode
解决了为所有的文字系统设置一个独立代码页的难题。
Creating Unicode strings in Python is just as simple as creating normal
strings::
在 Python 中创建 Unicode 字符串和创建普通的字符串一样简单 ::
>>> u'Hello World !'
u'Hello World !'
The small ``'u'`` in front of the quote indicates that a Unicode string is
supposed to be created. If you want to include special characters in the string,
you can do so by using the Python *Unicode-Escape* encoding. The following
example shows how::
引号前的 ``'u'`` 表示这会创建一个 Unicode 字符串。如果想要在字符串中包
含特殊字符,可以使用 Python 的 *Unicode-Escape* (Unicode 转义——译者)。
请看下面的例子 ::
>>> u'Hello/u0020World !'
u'Hello World !'
For experts, there is also a raw mode just like the one for normal strings. You
have to prefix the opening quote with 'ur' to have unevenPython use the
*Raw-Unicode-Escape* encoding. It will only apply the above ``/uXXXX``
conversion if there is an uneven number of backslashes in front of the small
'u'. ::
特别的,和普通字符串一样, Unicode 字符串也有原始模式。可以在引号前加
“ur”,Python 会采用 *Raw-Unicode-Escape* 编码(原始 Unicode 转义——译
者)。如果有前缀为 '/u' 的数值,它也只会显示为 ``/uXXXX`` 。 ::
>>> ur'Hello/u0020World !'
u'Hello World !'
>>> ur'Hello//u0020World !'
u'Hellou0020World !'
The raw mode is most useful when you have to enter lots of backslashes, as can
be necessary in regular expressions.
如果你需要大量输入反斜杠,原始模式非常有用,这在正则表达式中几乎是必须
的。
Apart from these standard encodings, Python provides a whole set of other ways
of creating Unicode strings on the basis of a known encoding.
所为这些编码标准的一部分,Python 提供了基于已知编码来创建 Unicode 字符
串的整套方法。
.. index:: builtin: unicode
The built-in function :func:`unicode` provides access to all registered Unicode
codecs (COders and DECoders). Some of the more well known encodings which these
codecs can convert are *Latin-1*, *ASCII*, *UTF-8*, and *UTF-16*. The latter two
are variable-length encodings that store each Unicode character in one or more
bytes. The default encoding is normally set to ASCII, which passes through
characters in the range 0 to 127 and rejects any other characters with an error.
When a Unicode string is printed, written to a file, or converted with
:func:`str`, conversion takes place using this default encoding. ::
内置函数 :func:`unicode` 可以使用所有注册的 Unicode 编码( COders 和
DECoders )。众所周知, *Latin-1* , *ASCII* , *UTF-8* 和 *UTF-16* 之
类的编码可以互相转换(Latin-1 表示一个很小的拉丁语言符号集,与 ASCII 基
本一致,其实不能用来表示庞大的东方语言字符集——译者)。后两个是变长编
码,将每一个 Uniocde 字符存储为一到多个字节。默认通常编码为 ASCII,此
编码接受 0 到 127 这个范围的编码,否则报错。将一个 Unicode 字符串打印
或写入到文件中,或者使用 :func:`str` 转换时,转换操作以此为默认编码。 ::
>>> u"abc"
u'abc'
>>> str(u"abc")
'abc'
>>> u"äöü"
u'/xe4/xf6/xfc'
>>> str(u"äöü")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
To convert a Unicode string into an 8-bit string using a specific encoding,
Unicode objects provide an :func:`encode` method that takes one argument, the
name of the encoding. Lowercase names for encodings are preferred. ::
为了将一个 Unicode 字符串写为一个使用特定编码的 8 位字符串, Unicode 对象提供一
:func:`encode` 方法,它接受编码名作为参数。编码名应该小写。 ::
>>> u"äöü".encode('utf-8')
'/xc3/xa4/xc3/xb6/xc3/xbc'
If you have data in a specific encoding and want to produce a corresponding
Unicode string from it, you can use the :func:`unicode` function with the
encoding name as the second argument. ::
如果有一个其它编码的数据,希望可以从中生成一 Unicode 字符串,你可以使用 :func:`unicode`
函数,它接受编码名作为第二参数。 ::
>>> unicode('/xc3/xa4/xc3/xb6/xc3/xbc', 'utf-8')
u'/xe4/xf6/xfc'
.. _tut-lists:
Lists 列表
----------
Python knows a number of *compound* data types, used to group together other
values. The most versatile is the *list*, which can be written as a list of
comma-separated values (items) between square brackets. List items need not all
have the same type. ::
Python 有几个 *复合* 数据类型,用于分线其它的值。最通用的是 *list* (列
表) ,它可以写作中括号之间的一列逗号分隔的值。列表的元素不必是同一类型。 ::
>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
Like string indices, list indices start at 0, and lists can be sliced,
concatenated and so on::
就像字符串索引,列表从 0 开始检索。列表可以被切片和连接 ::
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
All slice operations return a new list containing the requested elements. This
means that the following slice returns a shallow copy of the list *a*::
所有的切片操作都会返回新的列表,包含求得的元素。这意味着以下的切片操作
返回列表 *a* 的一个浅复制副本 ::
>>> a[:]
['spam', 'eggs', 100, 1234]
Unlike strings, which are *immutable*, it is possible to change individual
elements of a list::
不像 *不可变的* 字符串,列表允许修改元素 ::
>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]
Assignment to slices is also possible, and this can even change the size of the
list or clear it entirely::
也可以对切片赋值,此操作可以改变列表的尺寸,或清空它 ::
>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> # Insert (a copy of) itself at the beginning
>>> a[:0] = a
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>> # Clear the list: replace all items with an empty list
>>> a[:] = []
>>> a
[]
The built-in function :func:`len` also applies to lists::
内置函数 :func:`len` 也可以用于列表 ::
>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4
It is possible to nest lists (create lists containing other lists), for
example::
允许嵌套列表(创建一个包含其它列表的列表),例如 ::
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra') # See section 5.1
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']
Note that in the last example, ``p[1]`` and ``q`` really refer to the same
object! We'll come back to *object semantics* later.
注意最后一个例子中, ``p[1]`` 和 ``q`` 实际上指向同一个对象! 我们会在
后面的 *object semantics* 中继续讨论。
.. _tut-firststeps:
First Steps Towards Programming 编程的第一步
===========================================
Of course, we can use Python for more complicated tasks than adding two and two
together. For instance, we can write an initial sub-sequence of the *Fibonacci*
series as follows::
当然,我们可以使用 Python 完成比二加二更复杂的任务。例如,我们可以写一
个生成 *菲波那契* 子序列的程序,如下所示 ::
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
... print b
... a, b = b, a+b
...
1
1
2
3
5
8
This example introduces several new features.
这个例子介绍了几个新功能。
* The first line contains a *multiple assignment*: the variables ``a`` and ``b``
simultaneously get the new values 0 and 1. On the last line this is used again,
demonstrating that the expressions on the right-hand side are all evaluated
first before any of the assignments take place. The right-hand side expressions
are evaluated from the left to the right.
第一行包括了一个 *多重赋值* :变量 ``a`` 和 ``b`` 同时获得了新的值 0
和 1 。最后一行又使用了一次。在这个演示中,变量赋值前,右边首先完成
计算。右边的表达式从左到右计算。
* The :keyword:`while` loop executes as long as the condition (here: ``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: ``<`` (less than), ``>`` (greater than), ``==``
(equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
and ``!=`` (not equal to).
条件(这里是 ``b < 10`` )为 true 时, :keyword:`while` 循环执行。在
Python 中,类似于 C ,任何非零整数都是 true;0 是 false 。条件也可以
是字符串或列表,实际上可以是任何序列;所有长度不为零的是 true ,空序
列是 false。示例中的测试是一个简单的比较。标准比较操作符与 C 相同:
``<`` (小于), ``>`` (大于), ``==`` (等于), ``<=`` (小于等
于), ``>=`` (大于等于)和 ``!=`` (不等于)。
* The *body* of the loop is *indented*: indentation is Python's way of grouping
statements. Python does not (yet!) provide an intelligent input line editing
facility, so you have to type a tab or space(s) for each indented line. In
practice you will prepare more complicated input for Python with a text editor;
most text editors have an auto-indent facility. When a compound statement is
entered interactively, it must be followed by a blank line to indicate
completion (since the parser cannot guess when you have typed the last line).
Note that each line within a basic block must be indented by the same amount.
循环 *体* 是 *缩进* 的:缩进是 Python 是 Python 组织語句的方法。
Python (还) 不提供集成的行编辑功能,所以你要为每一个缩进行输入 TAB
或空格。实践中建议你找个文本编辑来录入复杂的 Python 程序,大多数文本
编辑器提供自动缩进。交互式录入复合语句时,必须在最后输入一个空行来标
识结束(因为解释器没办法猜测你输入的哪一行是最后一行),需要注意的是
同一个语句块中的语句块必须缩进同样数量的空白。
* The :keyword:`print` statement 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
and strings. Strings are printed without quotes, and a space is inserted
between items, so you can format things nicely, like this::
关键字 :keyword:`print` 语句输出给定表达式的值。它控制多个表达式和字
符串输出为你想要字符串(就像我们在前面计算器的例子中那样)。字符串打
印时不用引号包围,每两个子项之间插入空间,所以你可以把格式弄得很漂
亮,像这样 ::
>>> i = 256*256
>>> print 'The value of i is', i
The value of i is 65536
A trailing comma avoids the newline after the output::
用一个逗号结尾就可以禁止输出换行 ::
>>> a, b = 0, 1
>>> while b < 1000:
... print b,
... a, b = b, a+b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Note that the interpreter inserts a newline before it prints the next prompt if
the last line was not completed.
注意,在这里,如果最后一行没有输出完全,解释器在它打印下一个提示符前
会插入一个换行。