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.
在后面的例子中,區(qū)分輸入和輸出的方法是看是否有提示符("»> " 和"... "):想要重現(xiàn)這些例子的話,你就要在提示符顯示后輸入所有的一切;沒有以提示符開始的行,是解釋器輸出的信息。需要注意的是示例中的從屬提示符用于多行命令的結(jié)束,它表示你需要輸入一個(gè)空行。
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.
本手冊(cè)中的很多示例都包括注釋,甚至有一些在交互提示符中折行。Python中的注釋以符號(hào) "#" 起始,一直到當(dāng)前行的結(jié)尾。注釋可能出現(xiàn)在一行的開始,也可能跟在空格或程序代碼之后,但不會(huì)出現(xiàn)在字符串中,字符串中的 "#" 號(hào)只代表 "#" 號(hào)。
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."
Let's try some simple Python commands. Start the interpreter and wait
for the primary prompt, ">>
> ". (It shouldn't take long.)
讓我們?cè)囼?yàn)一些簡單的 Python
命令。啟動(dòng)解釋器然后等待主提示符">>
> "出現(xiàn)(這用不了太久)。
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:
解釋器的行為就像是一個(gè)計(jì)算器。你可以向它輸入一個(gè)表達(dá)式,它會(huì)返回結(jié)果。表達(dá)式的語法簡明易懂:+
,-
,*
,/
和大多數(shù)語言中的用法一樣(比如C或Pascal),括號(hào)用于分組。例如:
>>> 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
Like in C, the equal sign ("=") is used to assign a value to a variable. The value of an assignment is not written:
像c一樣,等號(hào)("=")用于給變量賦值。被分配的值是只讀的。
>>> width = 20 >>> height = 5*9 >>> width * height 900
A value can be assigned to several variables simultaneously:
同一個(gè)值可以同時(shí)賦給幾個(gè)變量:
>>> x = y = z = 0 # Zero x, y and z >>> x 0 >>> y 0 >>> z 0
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
Python完全支持浮點(diǎn)數(shù),不同類型的操作數(shù)混在一起時(shí),操作符會(huì)把整型轉(zhuǎn)化為浮點(diǎn)數(shù)。
>>> 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.
Python 也同樣支持復(fù)數(shù),虛部由一個(gè)后綴"j"或者"J"來表示。帶有非零實(shí)部的復(fù)數(shù)記為"real+imagj)",或者也可以通過"complex(real, img)"函數(shù)創(chuàng)建。
>>> 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
.
復(fù)數(shù)總是由實(shí)部和虛部兩部分浮點(diǎn)數(shù)來表示?梢詮 z.real
和 z.imag
得到復(fù)數(shù)z的實(shí)部和虛部。
>>> a=1.5+0.5j >>> a.real 1.5 >>> a.imag 0.5
The conversion functions to floating point and integer
(float(), int() and 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.
用于向浮點(diǎn)數(shù)和整型轉(zhuǎn)化的函數(shù)(float(), int() 和 long())不能對(duì)復(fù)數(shù)起作用--沒有什么方法可以將復(fù)數(shù)轉(zhuǎn)化為實(shí)數(shù)?梢允褂胊bs(z)取得它的模,也可以通過z.real得到它的實(shí)部。
>>> 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:
交互模式下,最近一次表達(dá)式輸出保存在 _
變量中。這意味著把 Python
當(dāng)做桌面計(jì)算器使用時(shí),可以方便的進(jìn)行連續(xù)計(jì)算,例如:
>>> 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.
這個(gè)變量對(duì)于用戶來說是只讀的。不要試圖去給它賦值--限于 Python 的語法規(guī)則,你只會(huì)創(chuàng)建一個(gè)同名的局部變量覆蓋它。
Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double quotes:
除了數(shù)值, Python 還可以通過幾種不同的方法操作字符串。字符串用單引號(hào)或雙引號(hào)標(biāo)識(shí):
>>> '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:
字符串可以通過幾種方式分行?梢栽谛屑臃葱备茏鰹槔^續(xù)符,這表示下一行是當(dāng)前行的邏輯沿續(xù)。
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 would 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
來表示;反斜杠后面的新行標(biāo)識(shí)(newline,縮寫“n”)會(huì)轉(zhuǎn)換為換行符,示例會(huì)按如下格式打印:
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.
If we make the string literal a ``raw'' string, however, the
\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:
然而,如果我們創(chuàng)建一個(gè)“行”("raw")字符串,\
n
序列就不會(huì)轉(zhuǎn)為換行,源碼中的反斜杠和換行符n都會(huì)做為字符串中的數(shù)據(jù)處理。如下所示:
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:
會(huì)打印為:
This is a rather long string containing\n\ several lines of text much as you would do in C.
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.
'
'
另外,字符串可以用一對(duì)三重引號(hào)”””或'''來標(biāo)識(shí)。三重引號(hào)中的字符串在行尾不需要換行標(biāo)記,所有的格式都會(huì)包括在字符串中。
print """ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """
produces the following output:
生成以下輸出:
Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to
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 print statement, described later, can be used to write strings without quotes or escapes.)
解釋器打印出來的字符串與它們輸入的形式完全相同:內(nèi)部的引號(hào),用反斜杠標(biāo)識(shí)的引號(hào)和各種怪字符,都精確的顯示出來。如果字符串中包含單引號(hào),不包含雙引號(hào),可以用雙引號(hào)引用它,反之可以用單引號(hào)。(后面介紹的 print 語句,可以在不使用引號(hào)和反斜杠的情況下輸出字符串)。
Strings can be concatenated (glued together) with the
+
operator, and repeated with *
:
字符串可以用 + 號(hào)聯(lián)接(或者說粘合),也可以用 * 號(hào)循環(huán)。
>>> 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:
兩個(gè)字符串值之間會(huì)自動(dòng)聯(lián)接,上例第一行可以寫成“word = 'Help' 'A'”。這種方式只對(duì)字符串值有效,任何字符串表達(dá)式都不適用這種方法。
>>> '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.
字符串可以用下標(biāo)(索引)查詢;就像 C 一樣,字符串的第一個(gè)字符下標(biāo)是 0。這里沒有獨(dú)立的字符類型,字符僅僅是大小為一的字符串。就像在 Icon 中那樣,字符串的子串可以通過切片標(biāo)志來表示:兩個(gè)由冒號(hào)隔開的索引。
>>> 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.
切片索引可以使用默認(rèn)值;前一個(gè)索引默認(rèn)值為 0,后一個(gè)索引默認(rèn)值為被切片的字符串的長度。
>>> 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 字符串不能改寫。按字符串索引賦值會(huì)產(chǎn)生錯(cuò)誤。
>>> word[0] = 'x' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object doesn't support item assignment >>> word[:1] = 'Splat' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object doesn't 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
.
切片操作有一個(gè)很有用的不變性:
>>> 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.
退化的切片索引處理方式很優(yōu)美:過大的索引代替為字符串大小,下界比上界大的返回空字符串。
>>> word[1:100] 'elpA' >>> word[10:] '' >>> word[2:1] ''
Indices may be negative numbers, to start counting from the right. For example:
索引可以是負(fù)數(shù),計(jì)數(shù)從右邊開始,例如:
>>> 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,它沒有從右邊計(jì)數(shù)!
>>> 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:
越界的負(fù)切片索引會(huì)被截?cái),不過不要嘗試在單元素索引(非切片的)中這樣做:
>>> word[-100:] 'HelpA' >>> word[-10] # error Traceback (most recent call last): File "<stdin>", line 1, in ? IndexError: string index out of range
The best 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:
理解切片的最好方式是把索引視為兩個(gè)字符之間的點(diǎn),第一個(gè)字符的左邊是0,字符串中第n個(gè)字符的右邊是索引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各個(gè)索引的位置,第二行是對(duì)應(yīng)的負(fù)索引。從i到j(luò)的切片由這兩個(gè)標(biāo)志之間的字符組成。
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.
對(duì)于非負(fù)索引,切片長度就是兩索引的差。例如,word[1:3]的長度是2。
The built-in function len() returns the length of a string:
內(nèi)置函數(shù) len() 返回字符串長度:
>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34
See Also:
%
operator are
described in more detail here.
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.
從Python2.0開始,程序員們可以使用一種新的數(shù)據(jù)類型來存儲(chǔ)文本數(shù)據(jù):Unicode 對(duì)象。它可以用于存儲(chǔ)多種Unicode數(shù)據(jù)(請(qǐng)參閱 http://www.unicode.org/ ),并且,通過必要時(shí)的自動(dòng)轉(zhuǎn)換,它可以與現(xiàn)有的字符串對(duì)象良好的結(jié)合。
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 and 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 針對(duì)現(xiàn)代和舊式的文本中所有的字符提供了一個(gè)序列。以前,字符只能使用256個(gè)序號(hào),文本通常通過綁定代碼頁來與字符映射。這很容易導(dǎo)致混亂,特別是軟件的國際化( internationalization --通常寫做“i18n”--“i”+ "i" +“n”)。 Unicode 通過為所有字符定義一個(gè)統(tǒng)一的代碼頁解決了這個(gè)問題。
Creating Unicode strings in Python is just as simple as creating normal strings:
Python 中定義一個(gè) Unicode 字符串和定義一個(gè)普通字符串一樣簡單:
>>> u'Hello World !' u'Hello World !'
The small "u" in front of the quote indicates that an 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:
引號(hào)前小寫的“u”表示這里創(chuàng)建的是一個(gè) Unicode 字符串。如果你想加入一個(gè)特殊字符,可以使用 Python 的 Unicode-Escape 編碼。如下例所示:
>>> u'Hello\u0020World !' u'Hello World !'
The escape sequence \u0020
indicates to insert the Unicode
character with the ordinal value 0x0020 (the space character) at the
given position.
被替換的 \u0020
標(biāo)識(shí)表示在給定位置插入編碼值為 0x0020 的
Unicode 字符(空格符)。
Other characters are interpreted by using their respective ordinal values directly as Unicode ordinals. If you have literal strings in the standard Latin-1 encoding that is used in many Western countries, you will find it convenient that the lower 256 characters of Unicode are the same as the 256 characters of Latin-1.
其它字符也會(huì)被直接解釋成對(duì)應(yīng)的 Unicode 碼。如果你有一個(gè)在西方國家常用的 Latin-1 編碼字符串,你可以發(fā)現(xiàn) Unicode 字符集的前256個(gè)字符與 Latin-1 的對(duì)應(yīng)字符編碼完全相同。
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
Python 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'.
另外,有一種與普通字符串相同的行模式。要使用 Python 的 Raw-Unicode-Escape 編碼,你需要在字符串的引號(hào)前加上 ur
前綴。如果在小寫“u”前有不止一個(gè)反斜杠,它只會(huì)把那些單獨(dú)的
uXXXX 轉(zhuǎn)化為Unicode字符。
>>> 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.
行模式在你需要輸入很多個(gè)反斜杠時(shí)很有用,使用正則表達(dá)式時(shí)會(huì)帶來方便。
Apart from these standard encodings, Python provides a whole set of other ways of creating Unicode strings on the basis of a known encoding.
作為這些編碼標(biāo)準(zhǔn)的一部分, Python 提供了一個(gè)完備的方法集用于從已知的編碼集創(chuàng)建 Unicode 字符串。
The built-in function 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 str(), conversion takes place using this default encoding.
內(nèi)置函數(shù) unicode() 提供了訪問(編碼和解碼)所有已注冊(cè)的 Unicode 編碼的方法。它能轉(zhuǎn)換眾所周知的 Latin-1, ASCII, UTF-8, 和 UTF-16。后面的兩個(gè)可變長編碼字符集用一個(gè)或多個(gè) byte 存儲(chǔ) Unicode 字符。默認(rèn)的字符集是 ASCII,它只處理0到127的編碼,拒絕其它的字符并返回一個(gè)錯(cuò)誤。當(dāng)一個(gè) Unicode 字符串被打印、寫入文件或通過 str() 轉(zhuǎn)化時(shí),它們被替換為默認(rèn)的編碼。
>>> 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 encode() method that takes one argument, the name of the encoding. Lowercase names for encodings are preferred.
要把一個(gè) Unicode 字符串用指定的字符集轉(zhuǎn)化成8位字符串,可以使用 Unicode 對(duì)象提供的 encode() 方法,它有一個(gè)參數(shù)用以指定編碼名稱。編碼名稱小寫。
>>> 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 unicode() function with the encoding name as the second argument.
如果你有一個(gè)特定編碼的字符串,想要把它轉(zhuǎn)為 Unicode 字符集,,可以使用 encode() 函數(shù),它以編碼名做為第二個(gè)參數(shù)。
>>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8') u'\xe4\xf6\xfc'
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 已經(jīng)有了幾個(gè)復(fù)合數(shù)據(jù)類型,用于組織其它的值。最通用的是鏈表,它寫為中括之間用逗號(hào)分隔的一列值(子項(xiàng)),鏈表的子項(xiàng)不一定是同一類型的值。
>>> 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:
像字符串一樣,鏈表也以零開始,可以被切片,聯(lián)接,等等:
>>> 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] + ['Boe!'] ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Unlike strings, which are immutable, it is possible to change individual elements of a list:
與不變的字符串不同,鏈表可以改變每個(gè)獨(dú)立元素的值:
>>> 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:
可以進(jìn)行切片操作,甚至還可以改變鏈表的大。
>>> # 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] >>> a[:0] = a # Insert (a copy of) itself at the beginning >>> a [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
The built-in function len() also applies to lists:
內(nèi)置函數(shù)len()也同樣可以用于鏈表:
>>> len(a) 8
It is possible to nest lists (create lists containing other lists), for example:
它也可以嵌套鏈表(在鏈表中創(chuàng)建其它鏈表),例如:
>>> 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.
注意最后一個(gè)例子, p[1]
和 q
實(shí)際上指向同一個(gè)對(duì)象!我們?cè)诤竺鏁?huì)講到對(duì)象語法。
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:
當(dāng)然,我們可以用 Python 做比2加2更復(fù)雜的事。例如,我們可以用以下的方法輸出菲波那契(Fibonacci)序列的子序列:
>>> # 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.
示例中介紹了一些新功能:
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.
第一行包括了 復(fù)合參數(shù):變量 a
和 b
同時(shí)被賦值為 0 和 1 。最后一行又一次使用了這種技術(shù),證明了在賦值之前表達(dá)式右邊先進(jìn)行了運(yùn)算。右邊的表達(dá)式從左到右運(yùn)算。
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).
while 循環(huán)運(yùn)行在條件為真時(shí)執(zhí)行(這里是 b < 10
)。在 Python 中,類似于 C 任何非零值為真,零為假。這個(gè)條件也可以用于字符串或鏈表,事實(shí)上于對(duì)任何序列類型,長度非零時(shí)為真,空序列為假。示例所用的是一個(gè)簡單的比較。標(biāo)準(zhǔn)的比較運(yùn)算符寫法和 C 相同: <
(小于),>
(大于),==
(等于),<=
(小于等于),>=
(大于等于)和 !=
(不等于)。
循環(huán)體是縮進(jìn)的:縮進(jìn)是 Python 對(duì)語句分組的方法。 Python 還沒有提供一個(gè)智能編輯功能,你要在每一個(gè)縮進(jìn)行輸入一個(gè) tab 或(一個(gè)或多個(gè))空格。實(shí)際上你可能會(huì)準(zhǔn)備更為復(fù)雜的文本編輯器來編寫你的 Python 程序,大多數(shù)文本編輯器都提供了自動(dòng)縮進(jìn)功能。交互式的輸入一個(gè)復(fù)雜語句時(shí),需要用一個(gè)空行表示完成(因?yàn)榻忉屍鳑]辦法猜出你什么時(shí)候輸入最后一行)。需要注意的是每一行都要有相同的縮進(jìn)來標(biāo)識(shí)這是同一個(gè)語句塊。
print 語句打印給定表達(dá)式的值。它與你僅僅輸入你需要的表達(dá)式(就像前面的計(jì)算器示例)不同,它可以同時(shí)輸出多個(gè)表達(dá)式。字符串輸出時(shí)沒有引號(hào),各項(xiàng)之間用一個(gè)空格分開,你可以很容易區(qū)分它們,如下所示:
>>> 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:
print 語句末尾的逗號(hào)避免了輸出中的換行:
>>> 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.
需要注意的是,如果最后一行仍沒有寫完,解釋器會(huì)在它打印下一個(gè)命令時(shí)插入一個(gè)新行。
譯者:劉鑫(march.liu AT gmail DOT com) 由:limodou轉(zhuǎn)(limodou AT gmail DOT com) CHM 文件制作:Colin.Wang 2007年9月