3. An Informal Introduction to Python
在以下示例中,輸入和輸出以提示符(>>>
和...
)的出現(xiàn)和消失來(lái)標(biāo)注:如果想要重現(xiàn)示例,提示符出現(xiàn)時(shí),必須輸入提示符之后的所有內(nèi)容。不以提示符開頭的行是解釋器的輸出。需要注意的是示例中行內(nèi)從屬提示符意味著必須多輸入一個(gè)空行,用來(lái)終止多行命令。
手冊(cè)中的許多示例,包括以交互提示符輸入的,都包含注釋。Python的注釋以#
字符開頭,直至物理行尾結(jié)束。注釋可以出現(xiàn)在行首,或者跟在空白符或代碼后面,但是不能出現(xiàn)在字符串中。字符串中的#
字符僅僅是#
字符。由于注釋是用來(lái)闡述代碼的,并不被Python所解釋,重寫示例時(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 Using Python as a Calculator
嘗試一些簡(jiǎn)單的Python命令。啟動(dòng)解釋器并等待主提示符>>>
出現(xiàn)。(不會(huì)等待太久)
3.1.1 Numbers
解釋器可以作為簡(jiǎn)單計(jì)算器使用:在解釋器中輸入表達(dá)式,解釋器會(huì)輸出值。表達(dá)式語(yǔ)法很簡(jiǎn)單:操作符+, - * /
跟其他語(yǔ)言意義一樣(如C跟Pascal);括號(hào)(()
)用于分組。例如:
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6
整數(shù)(如2, 4, 20
)類型是int
,帶有小數(shù)的數(shù)(如5.0, 1.6
)類型是float。后面會(huì)有更多關(guān)于數(shù)字類型的介紹。
除(/
)總是返回浮點(diǎn)數(shù)。操作符//
是向下取整除法,返回一個(gè)整數(shù)結(jié)果(舍棄小數(shù)部分結(jié)果),操作符%
用于求余數(shù):
>>> 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 # result * divisor + remainder
17
Python中可以使用操作符**
計(jì)算冪[1]:
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
等號(hào)(=
)用于將值賦給變量。賦值操作之后,在下一個(gè)交互提示符之前不會(huì)有任何輸出:
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
如果變量沒(méi)有定義(沒(méi)有被賦值),嘗試使用會(huì)得到一個(gè)錯(cuò)誤:
>>> 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)數(shù)的完整支持;在復(fù)合類型操作中,整型會(huì)被提升為浮點(diǎn)型:
>>> 4 * 3.75 - 1
14.0
交互模式中,最后打印的表達(dá)式會(huì)被賦值給變量_
。意味著Python作為桌面計(jì)算器使用時(shí),易于連續(xù)計(jì)算。例如:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
該變量對(duì)于用戶應(yīng)該被當(dāng)做只讀的。不要對(duì)其顯式賦值——否則將會(huì)創(chuàng)建同名的獨(dú)立局部變量,該變量屏蔽內(nèi)建變量的魔法效果。
除int
和float
之外,Python也支持其他數(shù)字類型,比如Decimal
和Fraction
。Python也有對(duì)復(fù)數(shù)(complex numbers)的內(nèi)建支持,使用j
或者J
標(biāo)識(shí)復(fù)數(shù)的虛部(如3+5j
)。
3.1.2 Strings
除了數(shù)字,Python也提供了多種表示字符串的方式。字符串可以使用單引號(hào)('...'
)或者雙引號(hào)(“...”
)圍起來(lái),效果是一樣的[2]。\
用于轉(zhuǎn)義:
>>> '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," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
交互式解釋器中,輸出字符串被引號(hào)包圍,特俗字符使用反斜杠轉(zhuǎn)義。雖然字符串在輸入時(shí)可能看起來(lái)不一樣(包圍字符串的引號(hào)可以不同),但是兩種形式的字符串是相等的。當(dāng)字符串包含單引號(hào)并且不包含雙引號(hào)時(shí),可以使用雙引號(hào)包圍,反之則使用單引號(hào)。print()
函數(shù)會(huì)省略外圍引號(hào),打印轉(zhuǎn)義字符和特殊字符,使得輸出更加可讀:
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she 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.
如果不希望以\
開頭的字符被解釋為轉(zhuǎn)義字符,可以使用原生字符串,在第一個(gè)引號(hào)前加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
字符串字面常量可以跨越多行。方式之一是使用多行引用:"""..."""
或者'''...'''
。換行符會(huì)自動(dòng)包括到字符串中,但是可以在行末添加\
阻止其發(fā)生。如下示例:
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
產(chǎn)生如下輸出(注意首行并沒(méi)有包括在內(nèi)):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
字符串可以使用操作符+
串聯(lián)起來(lái),使用操作符*
使其重復(fù):
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
兩個(gè)或者更多相鄰的字符串字面常量會(huì)自動(dòng)拼接起來(lái):
>>> 'Py' 'thon'
'Python'
以上只對(duì)只有字符串字面常量有效,對(duì)變量或者表達(dá)式無(wú)效:
>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
...
SyntaxError: invalid syntax
如果希望拼接變量或者變量以及字面常量,使用+
:
>>> prefix + 'thon'
'Python'
如果希望分割長(zhǎng)字符串,這個(gè)功能特別有用:
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
字符串支持索引操作,第一個(gè)字符串索引為0。Python中沒(méi)有單獨(dú)的字符類型;一個(gè)字符僅僅是長(zhǎng)度為1的字符串:
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
從右計(jì)數(shù)時(shí),索引也可以是負(fù)數(shù):
>>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
注意由于-0與0相同,所以負(fù)數(shù)索引從-1開始。
除了索引,字符串也支持切片。使用索引獲得個(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'
注意切片操作的返回值包含起始索引,不包含結(jié)束索引。使得s[:i] + s[:i]
總是等于s
:
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
切片操作指定了非常有用的默認(rèn)值;省略第一個(gè)索引默認(rèn)為0,省略第二個(gè)索引默認(rèn)當(dāng)前切片字符串長(zhǎng)度。
>>> 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'
一種記住切片工作方式的方法是:把索引當(dāng)做字符之間的指向,左邊第一個(gè)字符的邊編號(hào)0。長(zhǎng)度為n的字符串最后一個(gè)字符的右邊索引為n:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
第一行數(shù)據(jù)給出了字符串索引0...6的位置;第二行數(shù)字給出了其對(duì)應(yīng)負(fù)索引。從i到j的切片包含邊i和邊j之間所有的字符。
對(duì)于非負(fù)索引,如果兩個(gè)索引都在界限內(nèi),切片長(zhǎng)度是索引之差。例如,word[1:3]
的長(zhǎng)度為2.
使用超過(guò)界限的索引會(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
然而,切片操作時(shí)超出界限的切片索引會(huì)被優(yōu)雅處理:
>>> word[4:42]
'on'
>>> word[42:]
''
Python字符串不能被改變——他們是不可變的。因此,企圖對(duì)字符串索引位置賦值會(huì)拋出異常:
>>> word[0] = 'J'
...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
...
TypeError: 'str' object does not support item assignment
如果需要不同的字符串,應(yīng)該新建一個(gè):
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'
built-in函數(shù)len()返回字符串長(zhǎng)度:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
參見:
Text Sequence Type — str
字符串是序列的一種,支持序列所支持的一般操作。
String Methods
字符串支持大量基礎(chǔ)轉(zhuǎn)換和搜索的方法
Formatted string literals
字符串字面常量擁有嵌入式表達(dá)式
Format String Syntax
使用str.format()格式化字符串的相關(guān)信息
printf-style String Formatting
詳細(xì)描述了使用%
格式化字符串的舊字符串格式化操作
3.1.3 Lists
Python支持許多用來(lái)組織其他值的復(fù)合數(shù)據(jù)類型。最通用的是列表,包含在中括號(hào)中,以逗號(hào)分隔的一列值(項(xiàng))就是列表。列表可以包含不同類型的數(shù)據(jù),但在使用時(shí)通常包含相同類型數(shù)據(jù)。
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]
與字符串相似(與其他所有buit-in序列類型相似),列表支持索引和切片操作:
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
所有的切片操作返回包含請(qǐng)求元素的新列表。這意味著下列切片操作返回對(duì)列表的淺復(fù)制:
>>> squares[:]
[1, 4, 9, 16, 25]
列表也支持拼接操作:
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
與字符串的不可變不同,列表是可變類型。支持改變列表內(nè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()
方法可以在列表末尾加入新項(xiàng)(后面會(huì)詳細(xì)討論):
>>> 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]
對(duì)切片賦值也是可行的,這種操作可以改變列表的大小或者完全清除列表:
>>> 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
[]
built-in函數(shù)len()也可以應(yīng)用于列表:
>>> 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 First Steps Towards Programming
當(dāng)然,可以使用Python完成比2+2更加復(fù)雜的任務(wù)。例如,可以寫一段生成斐波那契數(shù)列的代碼:
>>> # 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
以上示例介紹了幾個(gè)新特性:
- 第一行包含了多重賦值:變量
a
和b
同時(shí)得到值0和1。最后一行再次使用多重賦值,證明了在右邊的所有表達(dá)式在賦值操作發(fā)生之前首先計(jì)算值。右邊的表達(dá)式從左到右計(jì)算值。 - 只要條件(這里是
b < 10
)為true,while循環(huán)就會(huì)執(zhí)行。Python中,與C相似,任何非零整數(shù)值都是true;零是false。條件也可以是字符串或者列表,事實(shí)上可以是任何序列;非零長(zhǎng)度序列是true,空序列是false。示例中使用的測(cè)試是一個(gè)簡(jiǎn)單的比較。標(biāo)準(zhǔn)的比較操作符與C相同:< (小于),>(大于), ==(等于), <= (小于等于), >=(大于等于)以及 !=(不等于)。 - 縮進(jìn)了循環(huán)體:縮進(jìn)是Python聚合語(yǔ)句的方式。在交互模式中,必須輸入tab或者幾個(gè)空格來(lái)縮進(jìn)每一行。實(shí)踐中,可以使用文本編輯器來(lái)準(zhǔn)備更加復(fù)雜的輸入;所有好用的文本編輯器都提供了自動(dòng)縮進(jìn)功能。交互模式中輸入復(fù)雜語(yǔ)句后,必須輸入空行來(lái)指示輸入完成(因?yàn)榻忉屍鳠o(wú)法判斷輸入的最后一行)。記住在同一基礎(chǔ)塊中的每一行語(yǔ)句必須縮進(jìn)相同的數(shù)量。
- print()函數(shù)輸出參數(shù)的值。不同于輸出想要輸出的表達(dá)式(就像上述計(jì)算器示例中那樣),該函數(shù)可以處理多個(gè)參數(shù),浮點(diǎn)數(shù)以及字符串。輸出的字符串沒(méi)有引號(hào)包圍,多個(gè)參數(shù)之間會(huì)插入空格。因此可以使用其優(yōu)雅地格式化輸出,如下示例:
>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536
關(guān)鍵字參數(shù)end可以用來(lái)避免輸出中的換行,或者使用不同的字符串結(jié)束輸出:
>>> a, b = 0, 1
>>> while b < 1000:
... print(b, end=',')
... a, b = b, a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
Footnotes
<span id="jump1">[1] </span>由于**
比-
擁有更高的優(yōu)先級(jí),-3**2
會(huì)被解釋為-(3**2)
并且結(jié)果是-9
。如要避免優(yōu)先級(jí)問(wèn)題而得到結(jié)果9
,可以使用(-3) ** 2
<span id="jump2">[2] </span> 與其他語(yǔ)言不同,特殊字符如\n
在單引號(hào)('...'
)和雙引號(hào)("..."
)意義相同。不同之處在于在單引號(hào)之中不需要轉(zhuǎn)義雙引號(hào)"
,但是需要轉(zhuǎn)義單引號(hào)\'
,反之亦然。