.. _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 pision 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 “”, line 1, in
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 “”, 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’
>>> ”
”
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’ # >> ‘str’.strip() + ‘ing’ # >> ‘str’.strip() ‘ing’ # >> 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 “”, line 1, in ?
typeerror: object does not support item assignment
>>> word[:1] = ‘splat’
traceback (most recent call last):
file “”, 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 “”, 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
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’hello////u0020world !’
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 “”, 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 inpidual
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: ““ (greater than), “==“
(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.
注意,在这里,如果最后一行没有输出完全,解释器在它打印下一个提示符前
会插入一个换行。
以上就是python 2.7基础教程之:概要介绍的内容,更多相关内容请关注php中文网(www.php1.cn)!