3. Python 速覽?

下面的例子以是否顯示提示符(>>>...)區(qū)分輸入與輸出:輸入例子中的代碼時(shí),要鍵入以提示符開頭的行中提示符后的所有內(nèi)容;未以提示符開頭的行是解釋器的輸出。注意,例子中的某行出現(xiàn)的第二個(gè)提示符是用來結(jié)束多行命令的,此時(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.

本手冊(cè)中的許多例子,甚至交互式命令都包含注釋。Python 注釋以 # 開頭,直到該物理行結(jié)束。注釋可以在行開頭,或空白符與代碼之后,但不能在字符串里面。字符串中的 # 號(hào)就是 # 號(hào)。注釋用于闡明代碼,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. Python 用作計(jì)算器?

現(xiàn)在,嘗試一些簡(jiǎn)單的 Python 命令。啟動(dòng)解釋器,等待主提示符(>>> )出現(xiàn)。

3.1.1. 數(shù)字?

解釋器像一個(gè)簡(jiǎn)單的計(jì)算器:輸入表達(dá)式,就會(huì)給出答案。表達(dá)式的語(yǔ)法很直接:運(yùn)算符 +、-*、/ 的用法和其他大部分語(yǔ)言一樣(比如,Pascal 或 C);括號(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ù)(如,5.0、1.6 )的類型是 float。本教程后半部分將介紹更多數(shù)字類型。

除法運(yùn)算(/)返回浮點(diǎn)數(shù)。用 // 運(yùn)算符執(zhí)行 floor division 的結(jié)果是整數(shù)(忽略小數(shù));計(jì)算余數(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  # floored quotient * divisor + remainder
17

Python 用 ** 運(yùn)算符計(jì)算乘方 1

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

等號(hào)(=)用于給變量賦值。賦值后,下一個(gè)交互提示符的位置不顯示任何結(jié)果:

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

如果變量未定義(即,未賦值),使用該變量會(huì)提示錯(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ù);混合類型運(yùn)算數(shù)的運(yùn)算會(huì)把整數(shù)轉(zhuǎn)換為浮點(diǎn)數(shù):

>>>
>>> 4 * 3.75 - 1
14.0

交互模式下,上次輸出的表達(dá)式會(huì)賦給變量 _。把 Python 當(dāng)作計(jì)算器時(shí),用該變量實(shí)現(xiàn)下一步計(jì)算更簡(jiǎn)單,例如:

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

最好把該變量當(dāng)作只讀類型。不要為它顯式賦值,否則會(huì)創(chuàng)建一個(gè)同名獨(dú)立局部變量,該變量會(huì)用它的魔法行為屏蔽內(nèi)置變量。

除了 intfloat,Python 還支持其他數(shù)字類型,例如 DecimalFraction。Python 還內(nèi)置支持 復(fù)數(shù),后綴 jJ 用于表示虛數(shù)(例如 3+5j )。

3.1.2. 字符串?

除了數(shù)字,Python 還可以操作字符串。字符串有多種表現(xiàn)形式,用單引號(hào)('……')或雙引號(hào)("……")標(biāo)注的結(jié)果相同 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," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

交互式解釋器會(huì)為輸出的字符串加注引號(hào),特殊字符使用反斜杠轉(zhuǎn)義。雖然,有時(shí)輸出的字符串看起來與輸入的字符串不一樣(外加的引號(hào)可能會(huì)改變),但兩個(gè)字符串是相同的。如果字符串中有單引號(hào)而沒有雙引號(hào),該字符串外將加注雙引號(hào),反之,則加注單引號(hào)。print() 函數(shù)輸出的內(nèi)容更簡(jiǎn)潔易讀,它會(huì)省略兩邊的引號(hào),并輸出轉(zhuǎ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.

如果不希望前置 \ 的字符轉(zhuǎn)義成特殊字符,可以使用 原始字符串,在引號(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

字符串字面值可以包含多行。 一種實(shí)現(xiàn)方式是使用三重引號(hào):"""..."""'''...'''。 字符串中將自動(dòng)包括行結(jié)束符,但也可以在換行的地方添加一個(gè) \ 來避免此情況。 參見以下示例:

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

輸出如下(請(qǐng)注意開始的換行符沒有被包括在內(nèi)):

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

字符串可以用 + 合并(粘到一起),也可以用 * 重復(fù):

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

相鄰的兩個(gè)或多個(gè) 字符串字面值 (引號(hào)標(biāo)注的字符)會(huì)自動(dòng)合并:

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

拆分長(zhǎ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.'

這項(xiàng)功能只能用于兩個(gè)字面值,不能用于變量或表達(dá)式:

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

字符串支持 索引 (下標(biāo)訪問),第一個(gè)字符的索引是 0。單字符沒有專用的類型,就是長(zhǎng)度為一的字符串:

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

索引還支持負(fù)數(shù),用負(fù)數(shù)索引時(shí),從右邊開始計(jì)數(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'

切片索引的默認(rèn)值很有用;省略開始索引時(shí),默認(rèn)值為 0,省略結(jié)束索引時(shí),默認(rèn)為到字符串的結(jié)尾:

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

注意,輸出結(jié)果包含切片開始,但不包含切片結(jié)束。因此,s[:i] + s[i:] 總是等于 s

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

還可以這樣理解切片,索引指向的是字符 之間 ,第一個(gè)字符的左側(cè)標(biāo)為 0,最后一個(gè)字符的右側(cè)標(biāo)為 nn 是字符串長(zhǎng)度。例如:

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

第一行數(shù)字是字符串中索引 0...6 的位置,第二行數(shù)字是對(duì)應(yīng)的負(fù)數(shù)索引位置。ij 的切片由 ij 之間所有對(duì)應(yīng)的字符組成。

對(duì)于使用非負(fù)索引的切片,如果兩個(gè)索引都不越界,切片長(zhǎng)度就是起止索引之差。例如, word[1:3] 的長(zhǎng)度是 2。

索引越界會(huì)報(bào)錯(cuò):

>>>
>>> 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ì)報(bào)錯(cuò):

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

要生成不同的字符串,應(yīng)新建一個(gè)字符串:

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

內(nèi)置函數(shù) len() 返回字符串的長(zhǎng)度:

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

參見

文本序列類型 --- str

字符串是 序列類型 ,支持序列類型的各種操作。

字符串的方法

字符串支持很多變形與查找方法。

格式字符串字面值

內(nèi)嵌表達(dá)式的字符串字面值。

格式字符串語(yǔ)法

使用 str.format() 格式化字符串。

printf 風(fēng)格的字符串格式化

這里詳述了用 % 運(yùn)算符格式化字符串的操作。

3.1.3. 列表?

Python 支持多種 復(fù)合 數(shù)據(jù)類型,可將不同值組合在一起。最常用的 列表 ,是用方括號(hào)標(biāo)注,逗號(hào)分隔的一組值。列表 可以包含不同類型的元素,但一般情況下,各個(gè)元素的類型相同:

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

和字符串(及其他內(nèi)置 sequence 類型)一樣,列表也支持索引和切片:

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

切片操作返回包含請(qǐng)求元素的新列表。以下切片操作會(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 類型,其內(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() 方法 可以在列表結(jié)尾添加新元素(詳見后文):

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

內(nèi)置函數(shù) 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. 走向編程的第一步?

當(dāng)然,Python 還可以完成比二加二更復(fù)雜的任務(wù)。 例如,可以編寫 斐波那契數(shù)列 的初始子序列,如下所示:

>>>
>>> # 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è)新功能。

  • 第一行中的 多重賦值:變量 ab 同時(shí)獲得新值 0 和 1。最后一行又用了一次多重賦值,這體現(xiàn)在右表達(dá)式在賦值前就已經(jīng)求值了。右表達(dá)式求值順序?yàn)閺淖蟮接摇?/p>

  • while 循環(huán)只要條件(這里指:a < 10)保持為真就會(huì)一直執(zhí)行。Python 和 C 一樣,任何非零整數(shù)都為真,零為假。這個(gè)條件也可以是字符串或列表的值,事實(shí)上,任何序列都可以;長(zhǎng)度非零就為真,空序列則為假。示例中的判斷只是最簡(jiǎn)單的比較。比較操作符的標(biāo)準(zhǔn)寫法和 C 語(yǔ)言一樣: < (小于)、 > (大于)、 == (等于)、 <= (小于等于)、 >= (大于等于)及 != (不等于)。

  • 循環(huán)體縮進(jìn)的 :縮進(jìn)是 Python 組織語(yǔ)句的方式。在交互式命令行里,得為每個(gè)縮輸入制表符或空格。使用文本編輯器可以實(shí)現(xiàn)更復(fù)雜的輸入方式;所有像樣的文本編輯器都支持自動(dòng)縮進(jìn)。交互式輸入復(fù)合語(yǔ)句時(shí), 要在最后輸入空白行表示結(jié)束(因?yàn)榻馕銎鞑恢滥囊恍写a是最后一行)。注意,同一塊語(yǔ)句的每一行的縮進(jìn)相同。

  • print() 函數(shù)輸出給定參數(shù)的值。與表達(dá)式不同(比如,之前計(jì)算器的例子),它能處理多個(gè)參數(shù),包括浮點(diǎn)數(shù)與字符串。它輸出的字符串不帶引號(hào),且各參數(shù)項(xiàng)之間會(huì)插入一個(gè)空格,這樣可以實(shí)現(xiàn)更好的格式化操作:

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

    關(guān)鍵字參數(shù) end 可以取消輸出后面的換行, 或用另一個(gè)字符串結(jié)尾:

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

備注

1

**- 的優(yōu)先級(jí)更高, 所以 -3**2 會(huì)被解釋成 -(3**2) ,因此,結(jié)果是 -9。要避免這個(gè)問題,并且得到 9, 可以用 (-3)**2。

2

和其他語(yǔ)言不一樣,特殊字符如 \n 在單引號(hào)('...')和雙引號(hào)("...")里的意義一樣。這兩種引號(hào)唯一的區(qū)別是,不需要在單引號(hào)里轉(zhuǎn)義雙引號(hào) ",但必須把單引號(hào)轉(zhuǎn)義成 \',反之亦然。