3. Python 速覽?
下面的例子以是否顯示提示符(>>> 與 ...)區分輸入與輸出:輸入例子中的代碼時(shí),要鍵入以提示符開(kāi)頭的行中提示符后的所有內容;未以提示符開(kāi)頭的行是解釋器的輸出。注意,例子中的某行出現的第二個(gè)提示符是用來(lái)結束多行命令的,此時(shí),要鍵入一個(gè)空白行。
You can toggle the display of prompts and output by clicking on >>>
in the upper-right corner of an example box. If you hide the prompts
and output for an example, then you can easily copy and paste the input
lines into your interpreter.
本手冊中的許多例子,甚至交互式命令都包含注釋。Python 注釋以 #
開(kāi)頭,直到該物理行結束。注釋可以在行開(kāi)頭,或空白符與代碼之后,但不能在字符串里面。字符串中的 # 號就是 # 號。注釋用于闡明代碼,Python 不解釋注釋?zhuān)I入例子時(shí),可以不輸入注釋。
示例如下:
# 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 用作計算器?
現在,嘗試一些簡(jiǎn)單的 Python 命令。啟動(dòng)解釋器,等待主提示符(>>>
)出現。
3.1.1. 數字?
解釋器像一個(gè)簡(jiǎn)單的計算器:輸入表達式,就會(huì )給出答案。表達式的語(yǔ)法很直接:運算符 +
、-
、*
、/
的用法和其他大部分語(yǔ)言一樣(比如,Pascal 或 C);括號 (()
) 用來(lái)分組。例如:
>>> 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
)的類(lèi)型是 int
,帶小數(如,5.0
、1.6
)的類(lèi)型是 float
。本教程后半部分將介紹更多數字類(lèi)型。
除法運算(/
)返回浮點(diǎn)數。用 //
運算符執行 floor division 的結果是整數(忽略小數);計算余數用 %
:
>>> 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
等號(=
)用于給變量賦值。賦值后,下一個(gè)交互提示符的位置不顯示任何結果:
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
如果變量未定義(即,未賦值),使用該變量會(huì )提示錯誤:
>>> n # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
Python 全面支持浮點(diǎn)數;混合類(lèi)型運算數的運算會(huì )把整數轉換為浮點(diǎn)數:
>>> 4 * 3.75 - 1
14.0
交互模式下,上次輸出的表達式會(huì )賦給變量 _
。把 Python 當作計算器時(shí),用該變量實(shí)現下一步計算更簡(jiǎn)單,例如:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
最好把該變量當作只讀類(lèi)型。不要為它顯式賦值,否則會(huì )創(chuàng )建一個(gè)同名獨立局部變量,該變量會(huì )用它的魔法行為屏蔽內置變量。
除了 int
和 float
,Python 還支持其他數字類(lèi)型,例如 Decimal
或 Fraction
。Python 還內置支持 復數,后綴 j
或 J
用于表示虛數(例如 3+5j
)。
3.1.2. 字符串?
除了數字,Python 還可以操作字符串。字符串有多種表現形式,用單引號('……'
)或雙引號("……"
)標注的結果相同 2。反斜杠 \
用于轉義:
>>> 'spam eggs' # single quotes
'spam eggs'
>>> '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.'
交互式解釋器會(huì )為輸出的字符串加注引號,特殊字符使用反斜杠轉義。雖然,有時(shí)輸出的字符串看起來(lái)與輸入的字符串不一樣(外加的引號可能會(huì )改變),但兩個(gè)字符串是相同的。如果字符串中有單引號而沒(méi)有雙引號,該字符串外將加注雙引號,反之,則加注單引號。print()
函數輸出的內容更簡(jiǎn)潔易讀,它會(huì )省略?xún)蛇叺囊?,并輸出轉義后的特殊字符:
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a 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
字符串字面值可以包含多行。 一種實(shí)現方式是使用三重引號:"""..."""
或 '''...'''
。 字符串中將自動(dòng)包括行結束符,但也可以在換行的地方添加一個(gè) \
來(lái)避免此情況。 參見(jiàn)以下示例:
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
輸出如下(請注意開(kāi)始的換行符沒(méi)有被包括在內):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
字符串可以用 +
合并(粘到一起),也可以用 *
重復:
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
相鄰的兩個(gè)或多個(gè) 字符串字面值 (引號標注的字符)會(huì )自動(dòng)合并:
>>> 'Py' 'thon'
'Python'
拆分長(cháng)字符串時(shí),這個(gè)功能特別實(shí)用:
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
這項功能只能用于兩個(gè)字面值,不能用于變量或表達式:
>>> 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
合并多個(gè)變量,或合并變量與字面值,要用 +
:
>>> prefix + 'thon'
'Python'
字符串支持 索引 (下標訪(fǎng)問(wèn)),第一個(gè)字符的索引是 0。單字符沒(méi)有專(zhuān)用的類(lèi)型,就是長(cháng)度為一的字符串:
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
索引還支持負數,用負數索引時(shí),從右邊開(kāi)始計數:
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
注意,-0 和 0 一樣,因此,負數索引從 -1 開(kāi)始。
除了索引,字符串還支持 切片。索引可以提取單個(gè)字符,切片 則提取子字符串:
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
切片索引的默認值很有用;省略開(kāi)始索引時(shí),默認值為 0,省略結束索引時(shí),默認為到字符串的結尾:
>>> 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'
注意,輸出結果包含切片開(kāi)始,但不包含切片結束。因此,s[:i] + s[i:]
總是等于 s
:
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
還可以這樣理解切片,索引指向的是字符 之間 ,第一個(gè)字符的左側標為 0,最后一個(gè)字符的右側標為 n ,n 是字符串長(cháng)度。例如:
+---+---+---+---+---+---+
| 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 之間所有對應的字符組成。
對于使用非負索引的切片,如果兩個(gè)索引都不越界,切片長(cháng)度就是起止索引之差。例如, word[1:3]
的長(cháng)度是 2。
索引越界會(huì )報錯:
>>> 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
但是,切片會(huì )自動(dòng)處理越界索引:
>>> word[4:42]
'on'
>>> word[42:]
''
Python 字符串不能修改,是 immutable 的。因此,為字符串中某個(gè)索引位置賦值會(huì )報錯:
>>> 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
要生成不同的字符串,應新建一個(gè)字符串:
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
內置函數 len()
返回字符串的長(cháng)度:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
參見(jiàn)
- 文本序列類(lèi)型 --- str
字符串是 序列類(lèi)型 ,支持序列類(lèi)型的各種操作。
- 字符串的方法
字符串支持很多變形與查找方法。
- 格式字符串字面值
內嵌表達式的字符串字面值。
- 格式字符串語(yǔ)法
使用
str.format()
格式化字符串。- printf 風(fēng)格的字符串格式化
這里詳述了用
%
運算符格式化字符串的操作。
3.1.3. 列表?
Python 支持多種 復合 數據類(lèi)型,可將不同值組合在一起。最常用的 列表 ,是用方括號標注,逗號分隔的一組值。列表 可以包含不同類(lèi)型的元素,但一般情況下,各個(gè)元素的類(lèi)型相同:
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
和字符串(及其他內置 sequence 類(lèi)型)一樣,列表也支持索引和切片:
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
切片操作返回包含請求元素的新列表。以下切片操作會(huì )返回列表的 淺拷貝:
>>> squares[:]
[1, 4, 9, 16, 25]
列表還支持合并操作:
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
與 immutable 字符串不同, 列表是 mutable 類(lèi)型,其內容可以改變:
>>> 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]
append()
方法 可以在列表結尾添加新元素(詳見(jiàn)后文):
>>> 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]
為切片賦值可以改變列表大小,甚至清空整個(gè)列表:
>>> 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
還可以嵌套列表(創(chuàng )建包含其他列表的列表),例如:
>>> 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 還可以完成比二加二更復雜的任務(wù)。 例如,可以編寫(xiě) 斐波那契數列 的初始子序列,如下所示:
>>> # 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
本例引入了幾個(gè)新功能。
第一行中的 多重賦值:變量
a
和b
同時(shí)獲得新值 0 和 1。最后一行又用了一次多重賦值,這體現在右表達式在賦值前就已經(jīng)求值了。右表達式求值順序為從左到右。while
循環(huán)只要條件(這里指:a < 10
)保持為真就會(huì )一直執行。Python 和 C 一樣,任何非零整數都為真,零為假。這個(gè)條件也可以是字符串或列表的值,事實(shí)上,任何序列都可以;長(cháng)度非零就為真,空序列則為假。示例中的判斷只是最簡(jiǎn)單的比較。比較操作符的標準寫(xiě)法和 C 語(yǔ)言一樣:<
(小于)、>
(大于)、==
(等于)、<=
(小于等于)、>=
(大于等于)及!=
(不等于)。循環(huán)體 是 縮進(jìn)的 :縮進(jìn)是 Python 組織語(yǔ)句的方式。在交互式命令行里,得為每個(gè)縮輸入制表符或空格。使用文本編輯器可以實(shí)現更復雜的輸入方式;所有像樣的文本編輯器都支持自動(dòng)縮進(jìn)。交互式輸入復合語(yǔ)句時(shí), 要在最后輸入空白行表示結束(因為解析器不知道哪一行代碼是最后一行)。注意,同一塊語(yǔ)句的每一行的縮進(jìn)相同。
print()
函數輸出給定參數的值。與表達式不同(比如,之前計算器的例子),它能處理多個(gè)參數,包括浮點(diǎn)數與字符串。它輸出的字符串不帶引號,且各參數項之間會(huì )插入一個(gè)空格,這樣可以實(shí)現更好的格式化操作:>>> i = 256*256 >>> print('The value of i is', i) The value of i is 65536
關(guān)鍵字參數 end 可以取消輸出后面的換行, 或用另一個(gè)字符串結尾:
>>> 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,
備注