<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](controlflow.xhtml "4. 其他流程控制工具") | - [上一頁](interpreter.xhtml "2. 使用 Python 解釋器") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 教程](index.xhtml) ? - $('.inline-search').show(0); | # 3. Python 的非正式介紹 在下面的例子中,通過提示符 ([>>>](../glossary.xhtml#term) 與 [...](../glossary.xhtml#term-1)) 的出現與否來區分輸入和輸出:如果你想復現這些例子,當提示符出現后,你必須在提示符后鍵入例子中的每一個詞;不以提示符開頭的那些行是解釋器的輸出。注意例子中某行中出現第二個提示符意味著你必須鍵入一個空白行;這是用來結束多行命令的。 這個手冊中的許多例子都包含注釋,甚至交互性命令中也有。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. 數字 解釋器就像一個簡單的計算器一樣:你可以在里面輸入一個表達式然后它會寫出答案。 表達式的語法很直接:運算符 `+`、`-`、`*`、`/` 的用法和其他大部分語言一樣(比如 Pascal 或者 C 語言);括號 (`()`) 用來分組。比如: ``` >>> 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`](../library/functions.xhtml#int "int") 類型,有小數部分的(比如 `5.0`、`1.6` )有 [`float`](../library/functions.xhtml#float "float") 類型。在這個手冊的后半部分我們會看到更多的數值類型。 除法運算 (`/`) 永遠返回浮點數類型。如果要做 [floor division](../glossary.xhtml#term-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 # result * divisor + remainder 17 ``` 在Python中,可以使用 `**` 運算符來計算乘方 [1](#id3) ``` >>> 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 ``` Python中提供浮點數的完整支持;包含多種混合類型運算數的運算會把整數轉換為浮點數: ``` >>> 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`](../library/functions.xhtml#int "int") 和 [`float`](../library/functions.xhtml#float "float"),Python也支持其他類型的數字,例如 [`Decimal`](../library/decimal.xhtml#decimal.Decimal "decimal.Decimal") 或者 [`Fraction`](../library/fractions.xhtml#fractions.Fraction "fractions.Fraction")。Python 也內置對 [復數](../library/stdtypes.xhtml#typesnumeric) 的支持,使用后綴 `j` 或者 `J` 就可以表示虛數部分(例如 `3+5j` )。 ### 3.1.2. 字符串 除了數字,Python 也可以操作字符串。字符串有多種形式,可以使用單引號(`'……'`),雙引號(`"……"`)都可以獲得同樣的結果 [2](#id4)。反斜杠 `\` 可以用來轉義: ``` >>> '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.' ``` 在交互式解釋器中,輸出的字符串外面會加上引號,特殊字符會使用反斜杠來轉義。 雖然有時這看起來會與輸入不一樣(外面所加的引號可能會改變),但兩個字符串是相同的。 如果字符串中有單引號而沒有雙引號,該字符串外將加雙引號來表示,否則就加單引號。 [`print()`](../library/functions.xhtml#print "print") 函數會生成可讀性更強的輸出,即略去兩邊的引號,并且打印出經過轉義的特殊字符: ``` >>> '"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 ``` 字符串字面值可以跨行連續輸入。一種方式是用三重引號:`"""..."""` 或 `'''...'''`。字符串中的回車換行會自動包含到字符串中,如果不想包含,在行尾添加一個 `\` 即可。如下例: ``` 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' ``` 注意切片的開始總是被包括在結果中,而結束不被包括。這使得 `s[:i] + s[i:]` 總是等于 `s` ``` >>> word[:2] + word[2:] 'Python' >>> word[:4] + word[4:] 'Python' ``` 切片的索引有默認值;省略開始索引時默認為0,省略結束索引時默認為到字符串的結束: ``` >>> 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' ``` 您也可以這么理解切片:將索引視作指向字符 *之間* ,第一個字符的左側標為0,最后一個字符的右側標為 *n* ,其中 *n* 是字符串長度。例如: ``` +---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 ``` 第一行數標注了字符串非負的索引的位置,第二行標注了對應的負的索引。那么從 *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 中的字符串不能被修改,它們是 [immutable](../glossary.xhtml#term-immutable) 的。因此,向字符串的某個索引位置賦值會產生一個錯誤: ``` >>> 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()`](../library/functions.xhtml#len "len") 返回一個字符串的長度: ``` >>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34 ``` 參見 [文本序列類型 --- str](../library/stdtypes.xhtml#textseq)字符串是一種 *序列類型* ,因此也支持序列類型的各種操作。 [字符串的方法](../library/stdtypes.xhtml#string-methods)字符串支持許多變換和查找的方法。 [格式化字符串字面值](../reference/lexical_analysis.xhtml#f-strings)內嵌表達式的字符串字面值。 [格式字符串語法](../library/string.xhtml#formatstrings)使用 [`str.format()`](../library/stdtypes.xhtml#str.format "str.format") 進行字符串格式化。 [printf 風格的字符串格式化](../library/stdtypes.xhtml#old-string-formatting)這里詳述了使用 `%` 運算符進行字符串格式化。 ### 3.1.3. 列表 Python 中可以通過組合一些值得到多種 *復合* 數據類型。其中最常用的 *列表* ,可以通過方括號括起、逗號分隔的一組值得到。一個 *列表* 可以包含不同類型的元素,但通常使用時各個元素類型相同: ``` >>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25] ``` 和字符串(以及各種內置的 [sequence](../glossary.xhtml#term-sequence) 類型)一樣,列表也支持索引和切片: ``` >>> squares[0] # indexing returns the item 1 >>> 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](../glossary.xhtml#term-immutable) 的字符串不同, 列表是一個 [mutable](../glossary.xhtml#term-mutable) 類型,就是說,它自己的內容可以改變: ``` >>> 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()` *方法* 添加新元素 (我們會在后面解釋更多關于方法的內容): ``` >>> 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 [] ``` 內置函數 [`len()`](../library/functions.xhtml#len "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 用于更復雜的任務,而不是僅僅兩個和兩個一起添加。 例如,我們可以編寫 [斐波那契數列](https://en.wikipedia.org/wiki/Fibonacci_number) \[https://en.wikipedia.org/wiki/Fibonacci\_number\] 的初始子序列,如下所示: ``` >>> # 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`](../reference/compound_stmts.xhtml#while) 循環只要它的條件(這里指: `a < 10`)保持為真就會一直執行。Python 和 C 一樣,任何非零整數都為真;零為假。這個條件也可以是字符串或是列表的值,事實上任何序列都可以;長度非零就為真,空序列就為假。在這個例子里,判斷條件是一個簡單的比較。標準的比較操作符的寫法和 C 語言里是一樣: `<` (小于)、 `>` (大于)、 `==` (等于)、 `<=` (小于或等于)、 `>=` (大于或等于)以及 `!=` (不等于)。 - *循環體* 是 *縮進的* :縮進是 Python 組織語句的方式。在交互式命令行里,你得給每個縮進的行敲下 Tab 鍵或者(多個)空格鍵。實際上用文本編輯器的話,你要準備更復雜的輸入方式;所有像樣的文本編輯器都有自動縮進的設置。交互式命令行里,當一個組合的語句輸入時, 需要在最后敲一個空白行表示完成(因為語法分析器猜不出來你什么時候打的是最后一行)。注意,在同一塊語句中的每一行,都要縮進相同的長度。 - [`print()`](../library/functions.xhtml#print "print") 函數將所有傳進來的參數值打印出來. 它和直接輸入你要顯示的表達式(比如我們之前在計算器的例子里做的)不一樣, 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, ``` 腳注 [1](#id1)因為 `**` 比 `-` 有更高的優先級, 所以 `-3**2` 會被解釋成 `-(3**2)` ,因此結果是 `-9`. 為了避免這個并且得到結果 `9`, 你可以用這個式子 `(-3)**2`. [2](#id2)和其他語言不一樣的是, 特殊字符比如說 `\n` 在單引號 (`'...'`) 和雙引號 (`"..."`) 里有一樣的意義. 這兩種引號唯一的區別是,你不需要在單引號里轉義雙引號 `"` (但是你必須把單引號轉義成 `\'`) , 反之亦然. ### 導航 - [索引](../genindex.xhtml "總目錄") - [模塊](../py-modindex.xhtml "Python 模塊索引") | - [下一頁](controlflow.xhtml "4. 其他流程控制工具") | - [上一頁](interpreter.xhtml "2. 使用 Python 解釋器") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) ? - zh\_CN 3.7.3 [文檔](../index.xhtml) ? - [Python 教程](index.xhtml) ? - $('.inline-search').show(0); | ? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看