3. Python 簡介

在下面的示例中,輸入和輸出透過提示符的存在或不存在來區分(>>>):要重複該示例,您必須在提示符出現時鍵入提示符之後的所有內容;不以提示符開頭的行是直譯器的輸出。請注意,示例中單獨一行的輔助提示符表示您必須鍵入一個空行;這用於結束多行命令。

您可以透過單擊示例框右上角的 >>> 來切換提示符和輸出的顯示。如果您隱藏示例的提示符和輸出,則可以輕鬆地將輸入行復制並貼上到您的直譯器中。

本手冊中的許多示例,即使是在互動式提示符下輸入的示例,也包含註釋。Python 中的註釋以井號字元 # 開頭,並延伸到物理行的末尾。註釋可以出現在一行的開頭或空格或程式碼之後,但不能出現在字串文字中。字串文字中的井號字元只是一個井號字元。由於註釋是為了澄清程式碼,並且不會被 Python 解釋,因此在鍵入示例時可以省略它們。

一些例子

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."

3.1. 將 Python 用作計算器

讓我們嘗試一些簡單的 Python 命令。啟動直譯器並等待主提示符 >>>。(應該不會花很長時間。)

3.1.1. 數字

直譯器充當一個簡單的計算器:您可以在其中鍵入一個表示式,它將寫入該值。表示式語法很簡單:運算子 +-*/ 可用於執行算術運算;括號 (()) 可用於分組。例如

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating-point number
1.6

整數(例如 2420)的型別為 int,帶有小數部分的(例如 5.01.6)的型別為 float。我們將在本教程的後面部分看到更多關於數字型別的資訊。

除法 (/) 總是返回一個浮點數。要進行 向下取整除法 並獲得整數結果,您可以使用 // 運算子;要計算餘數,您可以使用 %

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17

在 Python 中,可以使用 ** 運算子來計算冪 [1]

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

等號 (=) 用於為變數賦值。之後,在下一個互動式提示符之前不會顯示任何結果

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

如果變數未“定義”(賦值),則嘗試使用它會報錯

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

完全支援浮點數;具有混合型別運算元的運算子會將整數運算元轉換為浮點數

>>> 4 * 3.75 - 1
14.0

在互動模式下,最後列印的表示式被賦值給變數 _。這意味著當您將 Python 用作桌面計算器時,繼續計算會更容易一些,例如

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

使用者應將此變數視為只讀。不要顯式地為其賦值 — 您將建立一個具有相同名稱的獨立區域性變數,從而遮蔽具有其神奇行為的內建變數。

除了 intfloat 之外,Python 還支援其他型別的數字,例如 DecimalFraction。Python 還內建支援 複數,並使用 jJ 字尾來表示虛部(例如 3+5j)。

3.1.2. 文字

Python 可以操作文字(由型別 str 表示,即所謂的“字串”)以及數字。這包括字元“!”、單詞“rabbit”、名稱“Paris”、句子“Got your back.”等。“Yay! :)”。它們可以用單引號 ('...') 或雙引號 ("...") 括起來,結果相同 [2]

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> "Paris rabbit got your back :)! Yay!"  # double quotes
'Paris rabbit got your back :)! Yay!'
>>> '1975'  # digits and numerals enclosed in quotes are also strings
'1975'

要引用引號,我們需要用 \ 對其進行“轉義”。或者,我們可以使用另一種型別的引號

>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

在 Python shell 中,字串定義和輸出字串可能看起來不同。print() 函式透過省略封閉引號並列印跳脫字元和特殊字元來生成更易讀的輸出

>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), special characters are included in the string
'First line.\nSecond line.'
>>> print(s)  # with print(), special characters are interpreted, so \n produces new line
First line.
Second line.

如果您不希望 \ 開頭的字元被解釋為特殊字元,您可以透過在第一個引號之前新增 r 來使用 *原始字串*

>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\name

原始字串有一個微妙之處:原始字串不能以奇數個 \ 字元結尾;有關詳細資訊和解決方法,請參閱 FAQ 條目

字串文字可以跨越多行。一種方法是使用三引號:"""..."""'''...'''。行尾會自動包含在字串中,但是可以透過在行尾新增 \ 來防止這種情況。在下面的示例中,不包括初始換行符

>>> print("""\
... Usage: thingy [OPTIONS]
...      -h                        Display this usage message
...      -H hostname               Hostname to connect to
... """)
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

>>>

字串可以使用 + 運算子連線(粘合在一起),並使用 * 重複

>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'

兩個或多個彼此相鄰的 *字串文字*(即用引號括起來的字串文字)會自動連線。

>>> 'Py' 'thon'
'Python'

當您想要斷開長字串時,此功能特別有用

>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

但這隻適用於兩個文字,不適用於變數或表示式

>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  File "<stdin>", line 1
    prefix 'thon'
           ^^^^^^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  File "<stdin>", line 1
    ('un' * 3) 'ium'
               ^^^^^
SyntaxError: invalid syntax

如果要連線變數或變數和文字,請使用 +

>>> prefix + 'thon'
'Python'

字串可以被 *索引*(下標),第一個字元的索引為 0。沒有單獨的字元型別;字元只是大小為 1 的字串

>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'

索引也可以是負數,從右側開始計數

>>> word[-1]  # last character
'n'
>>> word[-2]  # second-last character
'o'
>>> word[-6]
'P'

請注意,由於 -0 與 0 相同,因此負索引從 -1 開始。

除了索引之外,還支援 *切片*。索引用於獲取單個字元,而 *切片* 允許您獲取子字串

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'

切片索引具有有用的預設值;省略的第一個索引預設為零,省略的第二個索引預設為被切片的字串的大小。

>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'

請注意,起始索引始終包含在切片內,而結束索引始終排除在外。這確保了 s[:i] + s[i:] 始終等於 s

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

記住切片工作方式的一種方法是將索引視為指向字元之間的位置,第一個字元的左邊緣編號為 0。那麼,長度為n個字元的字串的最後一個字元的右邊緣的索引為n,例如

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

第一行數字給出了字串中索引 0...6 的位置;第二行給出了對應的負索引。從ij的切片由標記為ij的邊緣之間的所有字元組成。

對於非負索引,如果兩個索引都在範圍內,則切片的長度是索引之差。例如,word[1:3] 的長度為 2。

嘗試使用過大的索引將導致錯誤

>>> 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

但是,當用於切片時,超出範圍的切片索引會被優雅地處理

>>> word[4:42]
'on'
>>> word[42:]
''

Python 字串不能被更改 — 它們是 不可變的。因此,為字串中的索引位置賦值會導致錯誤

>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

如果你需要不同的字串,你應該建立一個新的字串

>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'

內建函式 len() 返回字串的長度

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

另請參閱

文字序列型別 — str

字串是序列型別的示例,並支援此類型別支援的常見操作。

字串方法

字串支援大量用於基本轉換和搜尋的方法。

f-字串

具有嵌入表示式的字串字面量。

格式化字串語法

有關使用 str.format() 進行字串格式化的資訊。

printf 樣式的字串格式化

當字串是 % 運算子的左運算元時呼叫的舊式格式化操作在此處進行了更詳細的描述。

3.1.3. 列表

Python 知道許多複合資料型別,用於將其他值分組在一起。 最通用的型別是列表,它可以寫成方括號之間用逗號分隔的值(項)列表。 列表可能包含不同型別的項,但通常這些項都具有相同的型別。

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

像字串(和所有其他內建的序列型別)一樣,列表可以進行索引和切片

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]

列表還支援諸如連線之類的操作

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

不可變的字串不同,列表是可變的型別,也就是說,可以更改其內容

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

你還可以透過使用 list.append()方法(我們稍後會看到更多關於方法的知識)在列表末尾新增新項

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

Python 中的簡單賦值永遠不會複製資料。當你將列表分配給變數時,該變數會引用現有列表。 你透過一個變數對列表所做的任何更改,都將透過引用該列表的所有其他變數可見。

>>> rgb = ["Red", "Green", "Blue"]
>>> rgba = rgb
>>> id(rgb) == id(rgba)  # they reference the same object
True
>>> rgba.append("Alph")
>>> rgb
["Red", "Green", "Blue", "Alph"]

所有切片操作都返回一個包含所請求元素的新列表。這意味著以下切片返回列表的淺複製

>>> correct_rgba = rgba[:]
>>> correct_rgba[-1] = "Alpha"
>>> correct_rgba
["Red", "Green", "Blue", "Alpha"]
>>> rgba
["Red", "Green", "Blue", "Alph"]

也可以對切片進行賦值,這甚至可以更改列表的大小或完全清除列表

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

內建函式 len() 也適用於列表

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

可以巢狀列表(建立包含其他列表的列表),例如

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

3.2. 邁向程式設計的第一步

當然,我們可以使用 Python 執行比將二和二相加更復雜的任務。例如,我們可以編寫 斐波那契數列的初始子序列,如下所示

>>> # Fibonacci series:
>>> # the sum of two elements defines the next
>>> a, b = 0, 1
>>> while a < 10:
...     print(a)
...     a, b = b, a+b
...
0
1
1
2
3
5
8

此示例引入了幾個新功能。

  • 第一行包含多重賦值:變數 ab 同時獲得新值 0 和 1。在最後一行,再次使用了多重賦值,這表明在執行任何賦值之前,會首先對右側的表示式求值。 右側的表示式從左到右進行求值。

  • while 迴圈只要條件(此處為:a < 10)保持為真就執行。在 Python 中,就像在 C 中一樣,任何非零整數值都為真;零為假。該條件也可以是字串或列表值,實際上可以是任何序列;任何具有非零長度的值都為真,空序列為假。示例中使用的測試是一個簡單的比較。標準比較運算子的寫法與 C 中相同:<(小於)、>(大於)、==(等於)、<=(小於或等於)、>=(大於或等於)和 !=(不等於)。

  • 迴圈的主體縮排的:縮排是 Python 對語句進行分組的方式。在互動式提示符下,你必須為每個縮排行鍵入製表符或空格。實際上,你將使用文字編輯器為 Python 準備更復雜的輸入;所有像樣的文字編輯器都有自動縮排功能。當互動式輸入複合語句時,其後必須跟一個空行,以表示完成(因為解析器無法猜測你何時輸入最後一行)。請注意,基本塊中的每一行都必須縮排相同的數量。

  • print() 函式寫入它所給出的引數的值。它與僅寫入要寫入的表示式(就像我們在計算器示例中所做的那樣)的不同之處在於它處理多個引數、浮點數和字串的方式。字串在列印時不帶引號,並在專案之間插入空格,因此你可以很好地格式化內容,例如這樣

    >>> i = 256*256
    >>> print('The value of i is', i)
    The value of i is 65536
    

    可以使用關鍵字引數 end 來避免在輸出後換行,或者使用不同的字串結束輸出

    >>> a, b = 0, 1
    >>> while a < 1000:
    ...     print(a, end=',')
    ...     a, b = b, a+b
    ...
    0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
    

腳註