新聞中心
3. python 速覽
下面的例子以是否顯示提示符(>>> 與 …)區(qū)分輸入與輸出:輸入例子中的代碼時,要鍵入以提示符開頭的行中提示符后的所有內(nèi)容;未以提示符開頭的行是解釋器的輸出。注意,例子中的某行出現(xiàn)的第二個提示符是用來結(jié)束多行命令的,此時,要鍵入一個空白行。

目前創(chuàng)新互聯(lián)已為1000多家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬空間、網(wǎng)站改版維護、企業(yè)網(wǎng)站設(shè)計、平邑網(wǎng)站維護等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。
你可以通過在示例方塊右上角的 >>> 上點擊來切換顯示提示符和輸出。 如果你隱藏了一個示例的提示符和輸出,那么你可以方便地將輸入行復(fù)制并粘貼到你的解釋器中。
本手冊中的許多例子,甚至交互式命令都包含注釋。Python 注釋以 # 開頭,直到該物理行結(jié)束。注釋可以在行開頭,或空白符與代碼之后,但不能在字符串里面。字符串中的 # 號就是 # 號。注釋用于闡明代碼,Python 不解釋注釋,鍵入例子時,可以不輸入注釋。
示例如下:
# this is the first commentspam = 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 用作計算器
現(xiàn)在,嘗試一些簡單的 Python 命令。啟動解釋器,等待主提示符(>>> )出現(xiàn)。
3.1.1. 數(shù)字
解釋器像一個簡單的計算器:輸入表達式,就會給出答案。表達式的語法很直接:運算符 +、-、*、/ 的用法和其他大部分語言一樣(比如,Pascal 或 C);括號 (()) 用來分組。例如:
>>> 2 + 24>>> 50 - 5*620>>> (50 - 5*6) / 45.0>>> 8 / 5 # division always returns a floating point number1.6
整數(shù)(如,2、4、20 )的類型是 int,帶小數(shù)(如,5.0、1.6 )的類型是 float。本教程后半部分將介紹更多數(shù)字類型。
Division (/) always returns a float. To do floor division and get an integer result you can use the // operator; to calculate the remainder you can use %:
>>> 17 / 3 # classic division returns a float5.666666666666667>>>>>> 17 // 3 # floor division discards the fractional part5>>> 17 % 3 # the % operator returns the remainder of the division2>>> 5 * 3 + 2 # floored quotient * divisor + remainder17
Python 用 ** 運算符計算乘方 1:
>>> 5 ** 2 # 5 squared25>>> 2 ** 7 # 2 to the power of 7128
等號(=)用于給變量賦值。賦值后,下一個交互提示符的位置不顯示任何結(jié)果:
>>> width = 20>>> height = 5 * 9>>> width * height900
如果變量未定義(即,未賦值),使用該變量會提示錯誤:
>>> n # try to access an undefined variableTraceback (most recent call last):File "", line 1, in NameError: name 'n' is not defined
Python 全面支持浮點數(shù);混合類型運算數(shù)的運算會把整數(shù)轉(zhuǎn)換為浮點數(shù):
>>> 4 * 3.75 - 114.0
交互模式下,上次輸出的表達式會賦給變量 _。把 Python 當作計算器時,用該變量實現(xiàn)下一步計算更簡單,例如:
>>> tax = 12.5 / 100>>> price = 100.50>>> price * tax12.5625>>> price + _113.0625>>> round(_, 2)113.06
最好把該變量當作只讀類型。不要為它顯式賦值,否則會創(chuàng)建一個同名獨立局部變量,該變量會用它的魔法行為屏蔽內(nèi)置變量。
除了 int 和 float,Python 還支持其他數(shù)字類型,例如 Decimal 或 Fraction。Python 還內(nèi)置支持 復(fù)數(shù),后綴 j 或 J 用于表示虛數(shù)(例如 3+5j )。
3.1.2. 字符串
除了數(shù)字,Python 還可以操作字符串。字符串有多種表現(xiàn)形式,用單引號('……')或雙引號("……")標注的結(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.'
交互式解釋器會為輸出的字符串加注引號,特殊字符使用反斜杠轉(zhuǎn)義。雖然,有時輸出的字符串看起來與輸入的字符串不一樣(外加的引號可能會改變),但兩個字符串是相同的。如果字符串中有單引號而沒有雙引號,該字符串外將加注雙引號,反之,則加注單引號。print() 函數(shù)輸出的內(nèi)容更簡潔易讀,它會省略兩邊的引號,并輸出轉(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 lineFirst line.Second line.
如果不希望前置 \ 的字符轉(zhuǎn)義成特殊字符,可以使用 原始字符串,在引號前添加 r 即可:
>>> print('C:\some\name') # here \n means newline!C:\someame>>> print(r'C:\some\name') # note the r before the quoteC:\some\name
字符串字面值可以包含多行。 一種實現(xiàn)方式是使用三重引號:"""...""" 或 '''...'''。 字符串中將自動包括行結(jié)束符,但也可以在換行的地方添加一個 \ 來避免此情況。 參見以下示例:
print("""\Usage: thingy [OPTIONS]-h Display this usage message-H hostname Hostname to connect to""")
輸出如下(請注意開始的換行符沒有被包括在內(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'
相鄰的兩個或多個 字符串字面值 (引號標注的字符)會自動合并:
>>> '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 literalFile "", line 1 prefix 'thon'^^^^^^SyntaxError: invalid syntax>>> ('un' * 3) 'ium'File "", 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'
索引還支持負數(shù),用負數(shù)索引時,從右邊開始計數(shù):
>>> word[-1] # last character'n'>>> word[-2] # second-last character'o'>>> word[-6]'P'
注意,-0 和 0 一樣,因此,負數(shù)索引從 -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'
切片索引的默認值很有用;省略開始索引時,默認值為 0,省略結(jié)束索引時,默認為到字符串的結(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'
還可以這樣理解切片,索引指向的是字符 之間 ,第一個字符的左側(cè)標為 0,最后一個字符的右側(cè)標為 n ,n 是字符串長度。例如:
+---+---+---+---+---+---+| P | y | t | h | o | n |+---+---+---+---+---+---+0 1 2 3 4 5 6-6 -5 -4 -3 -2 -1
第一行數(shù)字是字符串中索引 0…6 的位置,第二行數(shù)字是對應(yīng)的負數(shù)索引位置。i 到 j 的切片由 i 和 j 之間所有對應(yīng)的字符組成。
對于使用非負索引的切片,如果兩個索引都不越界,切片長度就是起止索引之差。例如, word[1:3] 的長度是 2。
索引越界會報錯:
>>> word[42] # the word only has 6 charactersTraceback (most recent call last):File "", line 1, in IndexError: string index out of range
但是,切片會自動處理越界索引:
>>> word[4:42]'on'>>> word[42:]''
Python 字符串不能修改,是 immutable 的。因此,為字符串中某個索引位置賦值會報錯:
>>> word[0] = 'J'Traceback (most recent call last):File "", line 1, in TypeError: 'str' object does not support item assignment>>> word[2:] = 'py'Traceback (most recent call last):File "", line 1, in TypeError: 'str' object does not support item assignment
要生成不同的字符串,應(yīng)新建一個字符串:
>>> 'J' + word[1:]'Jython'>>> word[:2] + 'py''Pypy'
內(nèi)置函數(shù) len() 返回字符串的長度:
>>> s = 'supercalifragilisticexpialidocious'>>> len(s)34
參見
文本序列類型 —- str
字符串是 序列類型 ,支持序列類型的各種操作。
字符串的方法
字符串支持很多變形與查找方法。
格式字符串字面值
內(nèi)嵌表達式的字符串字面值。
格式字符串語法
使用 str.format() 格式化字符串。
printf 風格的字符串格式化
這里詳述了用 % 運算符格式化字符串的操作。
3.1.3. 列表
Python 支持多種 復(fù)合 數(shù)據(jù)類型,可將不同值組合在一起。最常用的 列表 ,是用方括號標注,逗號分隔的一組值。列表 可以包含不同類型的元素,但一般情況下,各個元素的類型相同:
>>> squares = [1, 4, 9, 16, 25]>>> squares[1, 4, 9, 16, 25]
和字符串(及其他內(nèi)置 sequence 類型)一樣,列表也支持索引和切片:
>>> squares[0] # indexing returns the item1>>> squares[-1]25>>> squares[-3:] # slicing returns a new list[9, 16, 25]
切片操作返回包含請求元素的新列表。以下切片操作會返回列表的 淺拷貝:
>>> 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]
為切片賦值可以改變列表大小,甚至清空整個列表:
>>> 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. 走向編程的第一步
當然,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...0112358
本例引入了幾個新功能。
第一行中的 多重賦值:變量
a和b同時獲得新值 0 和 1。最后一行又用了一次多重賦值,這體現(xiàn)在右表達式在賦值前就已經(jīng)求值了。右表達式求值順序為從左到右。while 循環(huán)只要條件(這里指:
a < 10)保持為真就會一直執(zhí)行。Python 和 C 一樣,任何非零整數(shù)都為真,零為假。這個條件也可以是字符串或列表的值,事實上,任何序列都可以;長度非零就為真,空序列則為假。示例中的判斷只是最簡單的比較。比較操作符的標準寫法和 C 語言一樣:<(小于)、>(大于)、==(等于)、<=(小于等于)、>=(大于等于)及!=(不等于)。循環(huán)體 是 縮進的 :縮進是 Python 組織語句的方式。在交互式命令行里,得為每個縮輸入制表符或空格。使用文本編輯器可以實現(xiàn)更復(fù)雜的輸入方式;所有像樣的文本編輯器都支持自動縮進。交互式輸入復(fù)合語句時, 要在最后輸入空白行表示結(jié)束(因為解析器不知道哪一行代碼是最后一行)。注意,同一塊語句的每一行的縮進相同。
print() 函數(shù)輸出給定參數(shù)的值。與表達式不同(比如,之前計算器的例子),它能處理多個參數(shù),包括浮點數(shù)與字符串。它輸出的字符串不帶引號,且各參數(shù)項之間會插入一個空格,這樣可以實現(xiàn)更好的格式化操作:
>>> i = 256*256>>> print('The value of i is', i)The value of i is 65536
關(guān)鍵字參數(shù) end 可以取消輸出后面的換行, 或用另一個字符串結(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)先級更高, 所以 -3**2 會被解釋成 -(3**2) ,因此,結(jié)果是 -9。要避免這個問題,并且得到 9, 可以用 (-3)**2。
2
和其他語言不一樣,特殊字符如 \n 在單引號('...')和雙引號("...")里的意義一樣。這兩種引號唯一的區(qū)別是,不需要在單引號里轉(zhuǎn)義雙引號 ",但必須把單引號轉(zhuǎn)義成 \',反之亦然。
文章名稱:創(chuàng)新互聯(lián)Python教程:3. Python 速覽
鏈接URL:http://fisionsoft.com.cn/article/dhcisis.html


咨詢
建站咨詢
