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
整數(例如 2
、4
、20
)的型別是 int
,帶有小數部分(例如 5.0
、1.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
這個變數應該被使用者視為只讀。不要明確地給它賦值——您會建立一個同名的獨立區域性變數,從而遮蔽掉具有神奇行為的內建變數。
除了 int
和 float
之外,Python 還支援其他型別的數字,例如 Decimal
和 Fraction
。Python 還內建支援複數,並使用 j
或 J
字尾表示虛部(例如 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
原始字串有一個微妙的方面:原始字串不能以奇數個 \
字元結尾;有關更多資訊和解決方法,請參閱常見問題解答條目。
字串字面量可以跨越多行。一種方法是使用三引號:"""..."""
或 '''...'''
。行尾字元會自動包含在字串中,但可以透過在行尾新增 \
來防止這種情況。在以下示例中,初始換行符不包含在內
>>> 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。沒有單獨的字元型別;字元只是大小為一的字串
>>> 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 的位置;第二行給出相應的負索引。從 i 到 j 的切片由分別位於標記為 i 和 j 的邊緣之間的所有字元組成。
對於非負索引,如果兩個索引都在範圍內,則切片的長度是索引之差。例如,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
這個例子引入了幾個新特性。
第一行包含一個 多重賦值:變數
a
和b
同時獲得新值 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,
腳註