.. _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 interter.. 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,
讀 ````````````s s更好詞 to A comment may appear at thestart of a line or following whitespace or code, but not within a stringliteral. A hash character within a string literal is just ahash. not interpreted by Python, they maybe omitted when typing in examples.本手冊中的許多示例——包括那些帶有交互提示符的——都含有註釋。 Python 中的註釋以 # 字符起始,直至實際的行尾(譯註——這裡原作者用了 ``physical line`` 以表示實際的換行而非編輯器的自動換行)。註解可以從行首開始,也可以在空白或程式碼之後,但不出現在字串中。文字字串中的 #字元僅表示 # 。程式碼中的註解不會被 Python 解釋,錄入範例的時候可以忽略它們。 Some examples:: # this is the first comment SPAM = 1 # ... 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 theprimary prompt, ``>>>``. (It shouldn't take long.)我們來嘗試一些簡單的Python 指令。啟動解釋器然後等待主提示符號 ``>>>``出現(不需要很久)。 .. _tut-numbers:Numbers 數值------------The interpreter acts as a simple calculator: you can type an expression at itŜvalue. Expression syntax is straightforward: the
operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
(for exle, Pas calor. ); parentheses can be used for grouping. For example::
解釋器的表示就像一個簡單的計算器:可以向其錄入一些表達式,它會給出返回
值。表達式語法很直白:運算子``+`` , ``-`` , ``*`` 和``/`` 與其它語言
言一樣(例如: Pascal 或C);括號用於分組。例如::
>>> 2+2
4
>>> # This is a comment
... 2+2
> c line as code 4 >>> (50-5*6)/4 5 >>>> > 7/-3
-3
The equal sign (``'='``) is used to assign a value to a variable. Afterwards, no
result is displayed before the next inter遠等號( ``'='`` )用於賦值變數::
>>> width = 20
>>> height = 5*9
>> value can be assigned to several variables simultaneously::
一個值可以同時賦給幾個變數::
>>> x = y = z = 0 # Zero x, y and z
>>> x = y = z = 0 # Zero x, y and z>>> x = y = z = 0 # Zero x, y and z
>>> x = y = z = 0 # Zero x, y and z>>> x = y = z = 0 # Zero x, y and z
>>> x
0
>>> y
0
>>> zDefŝ
) 名詞be used, or anerror will occur::變數在使用前必須「定義」(賦值),否則會發生錯誤:: >>> # try to access an undefined variable ... n. le : File "point
Com the realand 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 >>. :` float`,:func:`int` and :func:`long`) don't work for complex numbers --- there is no onecorrect way to convert a complex number to a real number. Use `` abs(z)`` to getits 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 "類型
3.0
>>> a.imag
4.0
>>> abs(a) , the last printed expression is assigned to the variable
``_``. This means that when you are using Python as a desk calculator, it is
some easier to continue calcations, for ex.一個表達式的值賦給變數``_`` 。這樣我們就可以把它當作
一個桌面計算器,很方便的用於連續計算,例如::
>>> tax = 12.5 / 100
>>> price = 100.50
>> * tax 12.5625 >>> price + _ 113.0625 ated as read-only by the user. Don't explicitlyassign a value to it --- you would create an independent local variable with thesame 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
several ways. They can be enclosed inseveral ways。 quotes::
相比數值,Python 也提供了可以透過幾種不同方式傳遞的字串。它們可以用
單引號或雙引號來識別::
>>> 'spam eggs'
'spam eggs'
> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
'"Yes," he said.'
/" he said." '"Yes," he said.' >>> '"Isn/'t," she said.' '"Isn/'t," sheString said.' can span multiple lines in several ways. Continuation lines canbe used, with a backslash as the last character on the line indicating that the❤方法分行。可以使用反斜線為行結尾的連續字串,它表示下一行在邏輯上是本行的繼續內容。 hello = "This is a rather long string containing/n/ several lines of text just as you would do in C./n/significant."
print hello
Note that newlines still need to be embedded in the string using ``/n`` -- the
新 follo
需要注意的是,還是需要在字串中寫入``/n`` ——結尾的反斜線會被忽略。前例會印為以下形式:.. code-block:: text This is a rather long string containing beginning of the line is significant.Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or``'''``. End of lines do notscape need to be enotscaped when using triple-quotes, butthey will be included in the string. ::另外,字串可以標識在一對兒三引號中: ``"""`` 或``'''`` 。三引號中,不需要行屬轉義,它們已經包含在字串中:: print """ Usage: thingy [OPTIONS] Display this usage message -H hostname Hostname to connect to """produces the following output:得到以下輸出::.. code-block:: text Display this usage message -H hostname Hostname to connect toIf we make the string literal a "raw" string, ``/n`` sequences are not conlineedline the sequences ar&line the arquences sft the arquence 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 texteveral lines stexteveral sir several sir sir” you would do in C." print hellowould print:會印製:.. code-block:: text This is a rathern is; as you would do in C.The interpreter prints the result of string operations in the same way as theyare typed for input: inside quotes, and with quotes and other funny characters tocunny charperise 筆. value. The string is enclosed indouble quotes if the string contains a single quote and no double quotes, elseit's enclosed in single quotes, elseit's enclosed in single quotes, elseit's enclosed in single quotes, elseit's enclosed in single quotes。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'
>>> ''
' 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' # 我 'string' >>> 'str'.strip() 'ing' # File " omitted. :: 索引切片可以忽略索引值,切片切片的話,預設為0,忽略第二個 索引,預設為字串的長度。 (其實還有第三個參數,表示切片步長,它預設為 1,完整的切片操作是word[2:4:1] -譯者) :: >>> word[:2 ] # The first two characters 'He' >>> word[2:] # Everything except the first two characters
. 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:]
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. :: the lower bound returns
an empty string. :: the lower bound returns
an empty string。為文字長度,上界小於下界則回傳空
字串。 ::
>>> word[1:100]
'elpA'
>>> word[10:]
may be negative numbers, to start counting from the right. For example::
索引可以是負數,此時從右端開始計量。例如::
>>> word[-1] # The last character
'A'
>>> word[-2] word[-2:] # The last two characters
'pA'
>>> word[:-2] # Everything except一天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, butdon-t of-range -slice) indices::
負索引切片越界會被截斷,不要嘗試將它用於單元素(非切片)檢索::
>>> word[-100:]
'HelpA'
>> word[-10] # error Traceback (most recent call last): File ". es 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 charThen n*, for example::
有個辦法可以很容易的記住切片的工作方式:切片時的索引是在兩個字符
*之間* 。左邊第一個字元的索引為0,,而長度為 *n* 的字串其最後一個字
符的右界索引為 *n* 。例如::
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+ ---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1115 the 000ooo nwion 0oo連表. 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 *jjj文本中的第一行數字給出字串中的索引點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
對於非負索引,如果上下都在邊界內,切片長度與索引不同。例如,``word[1:3]`` 是 2 。 The built-in function :func:`len` returns the length of a string::內建函數:func:`len` 回傳字串長度:: >> >> len(s) 34.. seealso:: :ref:`typesseq` Strings, and the Unicode Strings, and the Unicode Strings, and the Unicode str. quence types*, and support the common operations supported by such types. :ref:`string-methods` ic transformations and searching.:ref:`new-string-formatting`
Information about string formatting with :meth:`str.format` is described
. The old formatting operations invoked when strings and Unicode strings are
the left operand of the ``%`` operator are described in more detail here.
.. _t -------------------
.. 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 propervidingd 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
, seas ageage arage ar.page which mapped the ordinals to script characters. This lead to very much
confusion especially with respect to internationalization (usually written as
``i18n`` --- ``'i'``acters'i'``acters' ``) of software. Unicode solves
these problems by defining one code page for all scripts.
Unicode 的先進之處在於為每一種現代或古代使用的文字系統中出現的每一個字符都
Unicode 的先進之處在於為每一種現代或古代使用的文字系統中出現的每一個字符都了統一的序號。之前,文字系統中的字元只能有 256 種可能的順序。透過代碼頁分界映射。文字綁定到映射文字系統的代碼頁。這在軟體國際化的時候尤其麻煩 (通常寫作 ``i18n`` —— ``'i'`` + 18 個字符 + ``'n'`` )。 Unicode解決了為所有的文字系統設定一個獨立代碼頁的難題。 Creating Unicode strings in Python is just as simple as creating normalstrings::在Python 中建立Unicode 字串和建立普通的字串一樣簡單::收到can do so by using the Python *Unicode-Escape* encoding. The followingexample shows how::引號前的``'u'`` 表示這會建立一個Unicode 字串。如果想要在字串中包含特殊字符,可以使用 Python 的 *Unicode-Escape* (Unicode 轉義——譯者)。 請看下面的範例:: >>> u'Hello/u0020World !' u'Hello World !'For experts, there is alal a raw mode justike the al.
have to prefix the opening quote with 'ur' to have unevenPython use the
*Raw-Unicode-Escape* encoding. It will only apply the above ``/uXXXX``
reion in front of the small'u'. ::特別的,和普通字串一樣, Unicode 字串也有原始模式。引號前可以加“ur”,Python 會採用 *Raw-Unicode-Escape* 編碼(原始 Unicode 轉義-譯者)。如果有前綴為 '/u' 的數值,它也只會顯示為 ``/uXXXX`` 。 :: >>> ur'Hello/u0020World !' u'Hello World !' >>> ur'Hello//u0020World !'>>> ur'Hello//u0020World !'
>>> ur'Hello//u0020World !'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 waysof creating Unicode strings on the basis of a known encoding.所為這些程式碼字元串的整套方法。 。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 moretes . 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 :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")
xf6/xfc'
>>> str(u"ü")
Traceback (most recent call last):
File "
To convert a Unicode string into an 8-bit string using a specific encoding,
methodcode objects provide an that: that: method argument, the
name of the encoding. Lowercase names for encodings are preferred. ::
為了將一個Unicode 字串寫為一個使用特定編碼的8 位元字串, Unicode 物件
:func ` 方法,它接受編碼名作為參數。編碼名應該小寫。 :: >>> u"ü".encode('utf-8') '/xc3/xa4/xc3/xb6/xc3/xbc'If you have data in auce encoding a correspondingUnicode string from it, you can use the :func:`unicode` function with theencoding name as the second argument. ::如果有一個其它編碼串,你可以使用:func:`unicode`函數,它接受編碼名作為第二參數。 :: >>> unicode('/xc3/xa4/xc3/xb6/xc3/xbc', 'utf-8') u'/xe4/xf6/xfc' u'/xe4/xf6/xfc' _Lists 列表
----------
Python knows a number of *compound* data types, used to group together other
values. The most versatile is thelist
values. The most versatile is thelist
values. The most versatile is thelist* writich can list* as a list of
comma-separated values (items) between square brackets. List items need not all
have the same type. ::
Pyt
have the same type.::Pyt 資料有幾個。最通用的是 *list* (列表) ,它可以寫作中括號之間的一列逗號分隔的值。列表的元素不必是同一類型。 :: >>> a = ['spam', 'eggs', 100, 1234] >>> a ['spam', 'eggs', 100, 1234]indices start at 0, and lists can be sliced,
concatenated and so on::
就像字串索引,列表從0 開始檢索。清單可以切片和連接::
>>> a[0]
'spam'
>>> a[3]
> >> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', ' bacon', 4]
>>> 3*a[:3] + ['Boo!']
>>> 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. Thismeans that the following slice returns a shallow means that the following slice returns a shallow copy of the list copy of the list切片操作都會傳回新的列表,包含求得的元素。這意味著以下的切片操作返回清單 *a* 的一個淺複製副本 ::>>> a[:]
['spam', 'eggs', 100, 1234]
Unlike strings, which are *immutable*, it is possible to list不像*不可變的* 字串,列表允許修改元素::
>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[22 ] + 23
>>> a
['spam', 'eggs', 123, 1234]
Assignment to slices is also possible, and this can list even sizement to slices is also possible, and this can list even size list :
也可以對切片賦值,此操作可以改變列表的尺寸,或清空它::
>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = [emove some:
1234] >>> # Insert some: ... a[1:1] = ['bletch', 'xyzzy'] >>> a ' , 1234] >>> # Insert (a copy of) itself at the beginning >>> a[:0] = a >>> able,xyŜ
1234, 123, 'bletch', 'xyzzy', 1234] >>> # Clear the list: replace all items with an empty list[]The built-in function :func:`len` also applies to lists::內建函數:func:`len` 也可以用在列表中::
>>> a >> , 'b', 'c', 'd']
>>> len(a)
4
It is possible to nest lists (create lists containing other lists), for for嵌套清單(建立一個包含其它清單的清單),例如::
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p )
3
>>> p[1]
[2, 3]
>>> p[1][0]
) # See section 5.1
>>> p
[1, [2, 3, 'xtra'], 4]
[that” 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
... print b
... a, b
1
2
3
5
8
* The first line contains a *multiple assignment*: the variables ``a`` and ``b``
ultaneously get the new values 0 and 1. On thesimultaneously get the new values 0 and 1. On the last aneously get the new values 0 and 1。 the expressions on the right-hand side are all evaluated
first before any of the assignments take place. The right-hand side expressions
rightare evaluated * :變數``a`` 和``b`` 同時得到了新的值0和 1 。最後一行又使用了一次。在這個示範中,變數賦值前,右邊先完成
計算。右邊的表達式從左到右計算。
* The :keyword:`while` loop executes as long as the condition (here: ``b
remains true. In Python, like in C, any non-zero int value is
false. The condition may also be a string or list value, in fact any sequence;
anything with a non-zero length is true, $ a simple comparison . The standard comparison operators
are written the same as in C: ```` (greater than), ``==``
(` qu =`` (greater than or equal to)
and ``!=`` (not equal to).
條件(這裡是``b
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 intellis input put 完成space(s) for each indented line. In
practice you will prepare more complicated input for Python with a text editor;
most text editors have editor;
most. , 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 aame in blockby mobobe the motbe sbebeof fame line within aamebe 完成* m.是*縮排* 的:縮排是Python 是Python 組織語句的方法。
Python (還) 不提供整合的行編輯功能,所以你要為每一個縮進行輸入 TAB
或空格。實務上建議你找個文字編輯來錄入複雜的 Python 程序,大多數文字
編輯器提供自動縮排。互動式輸入複合語句時,必須在最後輸入一個空白行來標
識結束(因為解釋器沒辦法猜測你輸入的哪一行是最後一行),需要注意的是
同一個語句區塊中的語句區塊必須縮排同樣數量的空白。
* The :keyword:`print` statement writes the value of the expression(s) it is
given. It differs from just widron the expression you want to (a the way it handles multiple expressions
and strings。給定表達式的值。它控制多個表達式和字
符串輸出為你想要字串(就像我們在前面計算器的例子中)。字串打
印時不用引號包圍,每兩個子項之間插入空間,所以你可以把格式弄得很漂
亮,像這樣::
>>> i = 256*256
>>> 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
... print 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 ifthe not f 注意,在這裡,如果最後一行沒有輸出完全,解釋器在它打印下一個提示符前
會插入一個換行。
以上就是Python 2.7基礎教學之:概要介紹的內容,更多相關內容請關注PHP中文網(www.php.cn)!