>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
可以有零個或多個 elif 段落,且 else 段落可有可無。關鍵字 elif 只是「else if」的縮寫,並且用來避免過多的縮排。一個 if … elif … elif … 序列可以用來替代其他語言中出現的 switch 或 case 陳述式。
4.2. for 陳述式
在 Python 中的 for 陳述式可能不同於在 C 或 Pascal 中所看到的使用方式。與其只能疊代 (iterate) 一個等差級數(如 Pascal),或給與使用者定義疊代步進方式與結束條件(如 C),Python 的 for 陳述疊代任何序列(list 或者字串)的元素,以他們出現在序列中的順序。例如(無意雙關):
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
cat 3
window 6
defenestrate 12
如果你在迴圈中需要修改一個你正在疊代的序列(例如重複一些選擇的元素),那麼會建議你先建立一個序列的拷貝。疊代序列並不暗示建立新的拷貝。此時 slice 語法就讓這件事十分容易完成:
>>> for w in words[:]: # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0, w)
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
給定的結束值永遠不會出現在生成的序列中;range(10) 生成的 10 個數值,即對應存取一個長度為 10 的序列內每一個元素的索引值。也可以讓 range 從其他數值計數,或者給定不同的級距(甚至為負;有時稱之為 step):
range(5, 10)
5 through 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70
欲疊代一個序列的索引值,你可以搭配使用 range() 和 len() 如下:
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
0 Mary
1 had
3 little
4 lamb
然而,在多數的情況,使用 enumerate() 函式將更為方便,詳見迴圈技巧。
如果直接印出一個 range 則會出現奇怪的輸出:
>>> print(range(10))
range(0, 10)
在很多情況下,由 range() 回傳的物件的行為如同一個 list,但實際上它並不是。它是一個物件在你疊代時會回傳想要的序列的連續元素,並不會真正建出這個序列的 list,以節省空間。
我們稱這樣的物件為 iterable(可疊代的),意即能作為函式、陳述式中能一直獲取連續元素直到用盡的部件。我們已經看過 for 陳述式可做為如此的 iterator(疊代器)。list() 函式為另一個例子,他可以自 iterable(可疊代物件)建立 list:
>>> list(range(5))
[0, 1, 2, 3, 4]
待會我們可以看到更多函式回傳 iterable 和接受 iterable 為引數。
break 陳述,如同 C 語言,終止包含其最內部的 for 或 while 迴圈。
迴圈可以帶有一個 else 段落。當迴圈歷遍疊代的 list (在 for 中)或條件為偽(在 while 中)時,這個段落會被執行;但迴圈被 break 陳述終止時則不會。底下尋找質數的迴圈即示範了這個行為:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
(沒錯,這是正確的程式碼。請看仔細:else 段落屬於 for 迴圈,並非 if 陳述。)
當 else 段落與迴圈使用時,相較於搭配 if 陳述使用,它的行為與搭配 try 陳述使用時更為相似:try 的 else 段落在沒有任何例外 (exception) 時執行,而迴圈的 else 段落在沒有任何 break 時執行。更多有關 try 陳述和例外的介紹,見處理例外。
continue 陳述,亦承襲於 C 語言,讓所屬的迴圈繼續執行下個疊代:
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
pass 陳述不執行任何動作。它用在語法上需要一個陳述但不需要執行任何動作的時候。例如:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
這經常用於定義一個最簡單的類別:
>>> class MyEmptyClass:
...
pass
pass 亦可作為一個函式或條件判斷主體的預留位置,它可幫助你以更宏觀的角度思考並撰寫新的程式碼。pass 可被忽略:
>>> def initlog(*args):
... pass # Remember to implement this!
4.6. 定義函式 (function)
我們可以建立一個函式來產生費式數列到任何一個上界:
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
關鍵字 def 帶入一個函式的定義。它之後必須連著該函式的名稱和置於括號之中的參數。自下一行起,所有縮排的陳述成為該函式的主體。
一個函式的第一個陳述可以是一個字串值;此情況該字串值被視為該函式的說明文件字串,即 docstring。(關於 docstring 的細節請參見說明文件字串段落。)有些工具可以使用 docstring 來自動產生線上或可列印的文件,或讓使用者能自由地自原始碼中瀏覽文件。在原始碼中加入 docstring 是個好慣例,應該養成這樣的習慣。
函式執行期間會建立一個新的符號表(symbol table)來儲存該函式內的區域變數。更精確地說,所有在函式內的變數賦值都會把該值儲存在一個區域符號表。然而,在讀取一個變數時,會先從區域符號表起搜尋,其次為所有包含其函式的區域符號表,其次為全域符號表,最後為所有內建的名稱。因此,在函式中,全域變數無法被直接賦值(除非該變數有被 global 陳述句提及),但它們可以被讀取。
在一個函式被呼叫的時候,實際傳入的參數(引數)會被加入至該函數的區域符號表。因此,引數傳入的方式為傳值呼叫 (call by value)(這裡傳遞的「值」永遠是一個物件的參照(reference),而不是該物件的值)。 當一個函式呼叫別的函式時,在被呼叫的函式中會建立一個新的區域符號表。
一個函式定義會把該函式名稱加入至當前的符號表。該函式名稱的值帶有一個型別,並被直譯器辨識為使用者自定函式(user-defined function)。該值可以被賦予給別的變數名,而該變數也可以被當作函式使用。這即是常見的重新命名方式:
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
如果你是來自別的語言,你可能不同意 fib 是個函式,而是個程序 (procedure),因為它並沒有回傳值。實際上,即使一個函式缺少一個 return 陳述,它亦有一個固定的回傳值。這個值為 None(它是一個內建名稱)。在直譯器中單獨使用 None 時,通常不會被顯示。你可以使用 print() 來看到它:
>>> fib(0)
>>> print(fib(0))
如果要寫一個函式回傳費式數列的 list 而不是直接印出它,這也很容易:
>>> def fib2(n): # return Fibonacci series up to n
... """Return a list containing the Fibonacci series up to n."""
... result = []
... a, b = 0, 1
... while a < n:
... result.append(a) # see below
... a, b = b, a+b
... return result
>>> f100 = fib2(100) # call it
>>> f100 # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
這個例子一樣示範了一些新的 Python 特性:
return 陳述會讓一個函式回傳一個值。單獨使用 return 不外加一個表達式作為引數會回傳 None。一個函式執行到結束也會回傳 None。
result.append(a) 陳述呼叫了一個 list 物件的 result method(方法)。method 為「屬於」一個物件的函式,命名規則為 obj.methodname,其中 obj 為某個物件(亦可為一表達式),而 methodname 為該 method 的名稱,並由該物件的型別所定義。不同的型別代表不同的 method。不同型別的 method 可以擁有一樣的名稱而不會讓 Python 混淆。(你可以使用 class 定義自己的物件型別和 method,見 类)這裡 append() method 定義在 list 物件中;它會加入一個新的元素在該 list 的末端。這個例子等同於 result = result + [a],但更有效率。
4.7. 函数定义的更多形式
给函数定义有可变数目的参数也是可行的。这里有三种形式,可以组合使用。
4.7.1. 参数默认值
最有用的形式是对一个或多个参数指定一个默认值。这样创建的函数,可以用比定义时允许的更少的参数调用,比如:
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
这个函数可以通过几种方式调用:
只给出必需的参数:ask_ok('Do you really want to quit?')
给出一个可选的参数:ask_ok('OK to overwrite the file?', 2)
或者给出所有的参数:ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
这个示例还介绍了 in 关键字。它可以测试一个序列是否包含某个值。
默认值是在 定义过程 中在函数定义处计算的,所以
i = 5
def f(arg=i):
print(arg)
i = 6
会打印 5。
重要警告: 默认值只会执行一次。这条规则在默认值为可变对象(列表、字典以及大多数类实例)时很重要。比如,下面的函数会存储在后续调用中传递给它的参数:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
这将打印出
[1]
[1, 2]
[1, 2, 3]
如果你不想要在后续调用之间共享默认值,你可以这样写这个函数:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
4.7.2. 关键字参数
也可以使用形如 kwarg=value 的 关键字参数 来调用函数。例如下面的函数:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
接受一个必需的参数(voltage)和三个可选的参数(state, action,和 type)。这个函数可以通过下面的任何一种方式调用:
parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=
1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
但下面的函数调用都是无效的:
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor='John Cleese') # unknown keyword argument
在函数调用中,关键字参数必须跟随在位置参数的后面。传递的所有关键字参数必须与函数接受的其中一个参数匹配(比如 actor 不是函数 parrot 的有效参数),它们的顺序并不重要。这也包括非可选参数,(比如 parrot(voltage=1000) 也是有效的)。不能对同一个参数多次赋值。下面是一个因为此限制而失败的例子:
>>> def function(a):
... pass
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for keyword argument 'a'
When a final formal parameter of the form **name is present, it receives a
dictionary (see 映射类型 — dict) containing all keyword arguments except for
those corresponding to a formal parameter. This may be combined with a formal
parameter of the form *name (described in the next subsection) which
receives a tuple containing the positional arguments beyond the formal parameter
list. (*name must occur before **name.) For example, if we define a
function like this:
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
keys = sorted(keywords.keys())
for kw in keys:
print(kw, ":", keywords[kw])
它可以像这样调用:
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
当然它会打印:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
Note that the list of keyword argument names is created by sorting the result
of the keywords dictionary’s keys() method before printing its contents;
if this is not done, the order in which the arguments are printed is undefined.
4.7.3. 任意的参数列表
最后,最不常用的选项是可以使用任意数量的参数调用函数。这些参数会被包含在一个元组里(参见 Tuples 和序列 (Sequences) )。在可变数量的参数之前,可能会出现零个或多个普通参数。:
def write_multiple_items(file, separator, *args):
file.write(separator.join(args))
一般来说,这些 可变参数 将在形式参数列表的末尾,因为它们收集传递给函数的所有剩余输入参数。出现在 *args 参数之后的任何形式参数都是 ‘仅关键字参数’,也就是说它们只能作为关键字参数而不能是位置参数。:
>>> def concat(*args, sep="/"):
... return sep.join(args)
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'
4.7.4. 解包参数列表
The reverse situation occurs when the arguments are already in a list or tuple
but need to be unpacked for a function call requiring separate positional
arguments. For instance, the built-in range() function expects separate
start and stop arguments. If they are not available separately, write the
function call with the *-operator to unpack the arguments out of a list
or tuple:
>>> list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
In the same fashion, dictionaries can deliver keyword arguments with the **-operator:
>>> def parrot(voltage, state='a stiff', action='voom'):
... print("-- This parrot wouldn't", action, end=' ')
... print("if you put", voltage, "volts through it.", end=' ')
... print("E's", state, "!")
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
4.7.5. Lambda 表达式
可以用 lambda 关键字来创建一个小的匿名函数。这个函数返回两个参数的和: lambda a, b: a+b 。Lambda函数可以在需要函数对象的任何地方使用。它们在语法上限于单个表达式。从语义上来说,它们只是正常函数定义的语法糖。与嵌套函数定义一样,lambda函数可以引用所包含域的变量:
>>> def make_incrementor(n):
... return lambda x: x + n
>>> f = make_incrementor(42)
>>> f(0)
>>> f(1)
上面的例子使用一个lambda表达式来返回一个函数。另一个用法是传递一个小函数作为参数:
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
4.7.6. 說明文件字串
以下是有关文档字符串的内容和格式的一些约定。
第一行应该是对象目的的简要概述。为简洁起见,它不应显式声明对象的名称或类型,因为这些可通过其他方式获得(除非名称恰好是描述函数操作的动词)。这一行应以大写字母开头,以句点结尾。
如果文档字符串中有更多行,则第二行应为空白,从而在视觉上将摘要与其余描述分开。后面几行应该是一个或多个段落,描述对象的调用约定,它的副作用等。
Python 解析器不会从 Python 中删除多行字符串文字的缩进,因此处理文档的工具必须在需要时删除缩进。 这是使用以下约定完成的。 文档字符串第一行 之后 的第一个非空行确定整个文档字符串的缩进量。(我们不能使用第一行,因为它通常与字符串的开头引号相邻,因此它的缩进在字符串文字中不明显。)然后从字符串的所有行的开头剥离与该缩进 「等效」 的空格。 缩进更少的行不应该出现,但是如果它们出现,则应该剥离它们的所有前导空格。 应在转化制表符为空格后测试空格的等效性(通常转化为8个空格)。
下面是一个多行文档字符串的例子:
>>> def my_function():
... """Do nothing, but document it.
... No, really, it doesn't do anything.
... """
... pass
>>> print(my_function.__doc__)
Do nothing, but document it.
No, really, it doesn't do anything.
4.7.7. 函数标注
Function annotations are completely optional metadata
information about the types used by user-defined functions (see PEP 484
for more information).
Annotations are stored in the __annotations__ attribute of the function
as a dictionary and have no effect on any other part of the function. Parameter
annotations are defined by a colon after the parameter name, followed by an
expression evaluating to the value of the annotation. Return annotations are
defined by a literal ->, followed by an expression, between the parameter
list and the colon denoting the end of the def statement. The
following example has a positional argument, a keyword argument, and the return
value annotated:
>>> def f(ham: str, eggs: str = 'eggs') -> str:
... print("Annotations:", f.__annotations__)
... print("Arguments:", ham, eggs)
... return ham + ' and ' + eggs
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'
4.8. 小插曲:编码风格
现在你将要写更长,更复杂的 Python 代码,是时候讨论一下 代码风格 了。 大多数语言都能以不同的风格被编写(或更准确地说,被格式化);有些比其他的更具有可读性。 能让其他人轻松阅读你的代码总是一个好主意,采用一种好的编码风格对此有很大帮助。
对于Python,PEP 8 已经成为大多数项目所遵循的风格指南;它促进了一种非常易读且令人赏心悦目的编码风格。每个Python开发人员都应该在某个时候阅读它;以下是为你提取的最重要的几个要点:
使用4个空格缩进,不要使用制表符。
4个空格是一个在小缩进(允许更大的嵌套深度)和大缩进(更容易阅读)的一种很好的折中方案。制表符会引入混乱,最好不要使用它。
换行,使一行不超过79个字符。
这有助于使用小型显示器的用户,并且可以在较大的显示器上并排放置多个代码文件。
使用空行分隔函数和类,以及函数内的较大的代码块。
如果可能,把注释放到单独的一行。
使用文档字符串。
在运算符前后和逗号后使用空格,但不能直接在括号内使用: a = f(1, 2) + g(3, 4)。
Name your classes and functions consistently; the convention is to use
CamelCase for classes and lower_case_with_underscores for functions
and methods. Always use self as the name for the first method argument
(see 初探类 for more on classes and methods).
如果你的代码旨在用于国际环境,请不要使用花哨的编码。Python 默认的 UTF-8 或者纯 ASCII 在任何情况下都能有最好的表现。
同样,哪怕只有很小的可能,遇到说不同语言的人阅读或维护代码,也不要在标识符中使用非ASCII字符。
[1]实际上,通过对象引用调用 会是一个更好的表述,因为如果传递的是可变对象,则调用者将看到被调用者对其做出的任何更改(插入到列表中的元素)。