3. 一個非正式的 Python 簡介

在下面的例子中,輸入與輸出的區別在於有無提示符(prompt,>>>):如果要重做範例,你必須在提示符出現的時候,輸入提示符後方的所有內容;那些非提示符開始的文字行是直譯器的輸出。注意到在範例中,若出現單行只有次提示符時,代表該行你必須直接換行;這被使用在多行指令結束輸入時。

在本手冊中的許多範例中,即便他們為互動式地輸入,仍然包含註解。Python 中的註解 (comments) 由 hash 字元 # 開始一直到該行結束。註解可以從該行之首、空白後、或程式碼之後開始,但不會出現在字串之中。hash 字元在字串之中時仍視為一 hash 字元。因為註解只是用來說明程式而不會被 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. 數字 (Number)

直譯器如同一台簡單的計算機:你可以輸入一個 expression(運算式),它會寫出該式的值。Expression 的語法很使用:運算子 +-*/ 的行為如同大多數的程式語言(例如: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

整數數字(即 2420)為 int 型態,數字有小數點部份的(即 5.01.6)為 float 型態。我們將在之後的教學中看到更多數字相關的型態。

除法 (/) 永遠回傳一個 float。如果要做 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 中,計算冪次 (powers) 可以使用 ** 運算子 [1]

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

等於符號 (=) 可以用於為變數賦值。賦值完之後,在下個指示符前並不會顯示任何結果:

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

如果一個變數未被「定義 (defined)」(即變數未被賦值),試著使用它時會出現一個錯誤:

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

浮點數的運算有完善的支援,運算子 (operator) 遇上混合的運算元 (operand) 時會把整數的運算元轉換為浮點數:

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

這個變數應該被使用者視為只能讀取。不應該明確地為它賦值 — 你可以創一個獨立但名稱相同的本地變數來覆蓋掉預設變數和它的神奇行為。

除了 intfloat,Python 還支援了其他的數字型態,包含 DecimalFraction。Python 亦內建支援複數 (complex numbers),並使用 jJ 後綴來指定虛數的部份(即 3+5j)。

3.1.2. 字串 (String)

除了數字之外,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.'

在互動式的直譯器中,輸出的字串會被引號包圍且特殊符號會使用反斜線 (\) 跳脫。雖然這有時會讓它看起來跟輸入的字串不相同(包圍用的引號可能會改變),輸入和輸出兩字串實為相同。一般來說,字串包含單引號而沒有雙引號時,會使用雙引號包圍字串。函式 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.

如果你不希望字元前出現 \ 就被當成特殊字元時,可以改使用 raw string,在第一個包圍引號前加上 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

字串可以使用 + 運算子連接 (concatenate),並用 * 重覆該字串的內容:

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

兩個以上相鄰的字串值(string literal,即被引號包圍的字串)會被自動連接起來:

>>> '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
  ...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  ...
SyntaxError: invalid syntax

如果要連接變數們或一個變數與一個字串值,使用 +

>>> prefix + 'thon'
'Python'

字串可以被「索引 indexed」(下標,即 subscripted),第一個字元的索引值為 0。沒有獨立表示字元的型別;一個字元就是一個大小為 1 的字串:

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