More Control Flow Tools
深入流程控制
以下及以后的內容來自Python用戶手冊2.5&&2.6,為學習時的摘抄筆記。
3 深入流程控制
3.1 if語句
if elif
縮進,冒號
3.2 for x in a:
a鏈表
在迭代過程中修改迭代序列不安全,要想修改迭代序列,可以迭代它的復本 for x in a[:]:
3.3 使用range()函數生成等差級數鏈表
>>> a = ['Mary','had','a','little','lamb']
>>> for i in range(len(a)):
... print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb
>>>
3.4 break、continue、else
break、continue和C語言中的類似。循環(huán)可以有一個else子句;它在循環(huán)迭代完整個列表(對于for)或執(zhí)行條件為false(對于while)時執(zhí)行,但循環(huán)break中止的情況下不會執(zhí)行。例如
>>> for n in range(2,10):
... for x in range(2,n):
... if n % x == 0:
... print n, 'equals', x, '*',n/x
... break
... else:
... 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
3.5 pass語句
pass語句什么也不做。它用于那些語法上必須要有什么語句,但程序什么也不做的場合。例如:
3.6 定義函數
關鍵字def引入一個函數定義。在其后必須跟有函數名和包括形式參數的圓括號。函數體語句從下一行開始,必須是縮進的。函數體的第一行可以是一個字符串值,這個字符串是該函數的文檔字符串。
執(zhí)行函數時會為局部變量引入一個新的符號表。所有的局部變量都存儲在這個局部符號表。引用參數時,會先從局部符號表中查找,然后是全局符號表,然后是內置命名表。因此,全局參數雖然可以被引用,但它們不能再函數中直接賦值(除非它們用global語句命名)。
返回一個鏈表的函數
>>> def fib2(n):
... """Return a list containing the Fibonacci series up to n."""
... result = []
... a, b = 0, 1
... while b < n:
... result.append(b)
... a, b = b, a+b
... return result
...
>>> f100 = fib2(2000)
>>> f100
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]
return語句從函數中返回一個值,不帶表達式的return返回None。過程結束后也會返回None。
3.7 深入函數定義
定義參數可變的函數
3.7.1參數默認值
給一個或多個參數指定默認值
3.7.2 關鍵字參數
函數可以通過關鍵字參數的形式來調用,形如‘keyword=value’。例如,以下的函數:
>>> def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
... print "-- This parrot wouldn't", action,
... print "if you put", voltage, "volts through it."
... print "-- Lovely poumage, the", type
... print "-- It's", state, "!"
...
>>> parrot(1000)
-- This parrot wouldn't voom if you put 1000 volts through it.
-- Lovely poumage, the Norwegian Blue
-- It's a stiff !
>>> parrot(action='vooooom', voltage=1000000)
-- This parrot wouldn't vooooom if you put 1000000 volts through it.
-- Lovely poumage, the Norwegian Blue
-- It's a stiff !
參數列表中的每一個關鍵字都必須來自于形式參數,每個參數都有對應的關鍵字。形式參數有沒有默認值并不重要。實際參數不能一次賦多個值。形式參數不能在同一次調用中同時使用位置和關鍵字綁定值。
>>> def func(a):
... pass
...
>>> func(a=0)
>>>
>>> func(0, a=0)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: func() got multiple values for keyword argument 'a'
>>>
引入一個形如**name的參數時,它接收一個字典,該字典包含了所有未出現在形式參數列表中的關鍵字參數。這里可能還會組合使用一個形如*name的形式參數,它接收一個元組,包好了所有沒有出現在形式參數列表中的參數值。(*name必須在**name之前出現)
>>> 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=keywords.keys()
... keys.sort()
... for kw in keys: print kw, ':', keywords[kw]
...
>>> cheeseshop('Limburger',"It's very runny, sir.","It's really very, VERY runny, sir.", client='John Cleese',shopkeeper='Michael Palin',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
3.7.3 可變參數列表
函數可以調用可變個數的參數。這些參數被包裝進一個元組。在這些可變個數的參數之前,可以有零到多個普通的參數:
>>> def fprintf(file, format, *args):
... file.write(format % args)
...
3.7.4 參數列表的分解
當傳遞的參數已經是一個列表的時候,而要調用的函數卻接受分開一個個的參數值。這時要把已有的列表拆開。
>>> args = [3, 6]
>>> range(*args)
[3, 4, 5]
>>>
使用**操作符分拆關鍵字參數為字典
3.7.5 Lambda形式
通過lambad關鍵字,可以創(chuàng)建短小的匿名函數。這里有一個函數返回它的兩個參數的和:‘lambda a, b: a+b’。Lambda形式可以用于任何需要的函數對象。出于語法限制,它們只能有一個單獨的表達式。語義上講,它們只是普通函數定義中的一個語法技巧。類似于嵌套函數定義,lambda形式可以從包含范圍內引用變量:
>>> def make_incrementor(n):
... return lambda x: x+n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
3.7.6 文檔字符串
第一行介紹對象的用途。如果文檔字符串有多行,第二行應該空出來,與接下來的詳細描述明確分割。下面的文檔應該有一或多段描述對象的調用約定、邊界效應。
>>> def my_fun():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print my_fun.__doc__
Do nothing, but document it.
No, really, it doesn't do anything.
>>> print my_fun.func_doc
Do nothing, but document it.
No, really, it doesn't do anything.
>>>