More Control Flow Tools
深入流程控制
以下及以后的內(nèi)容來自Python用戶手冊2.5&&2.6,為學(xué)習(xí)時(shí)的摘抄筆記。
3 深入流程控制
3.1 if語句
if elif
縮進(jìn),冒號
3.2 for x in a:
a鏈表
在迭代過程中修改迭代序列不安全,要想修改迭代序列,可以迭代它的復(fù)本 for x in a[:]:
3.3 使用range()函數(shù)生成等差級數(shù)鏈表
>>> 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)可以有一個(gè)else子句;它在循環(huán)迭代完整個(gè)列表(對于for)或執(zhí)行條件為false(對于while)時(shí)執(zhí)行,但循環(huán)break中止的情況下不會(huì)執(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 定義函數(shù)
關(guān)鍵字def引入一個(gè)函數(shù)定義。在其后必須跟有函數(shù)名和包括形式參數(shù)的圓括號。函數(shù)體語句從下一行開始,必須是縮進(jìn)的。函數(shù)體的第一行可以是一個(gè)字符串值,這個(gè)字符串是該函數(shù)的文檔字符串。
執(zhí)行函數(shù)時(shí)會(huì)為局部變量引入一個(gè)新的符號表。所有的局部變量都存儲在這個(gè)局部符號表。引用參數(shù)時(shí),會(huì)先從局部符號表中查找,然后是全局符號表,然后是內(nèi)置命名表。因此,全局參數(shù)雖然可以被引用,但它們不能再函數(shù)中直接賦值(除非它們用global語句命名)。
返回一個(gè)鏈表的函數(shù)
>>> 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語句從函數(shù)中返回一個(gè)值,不帶表達(dá)式的return返回None。過程結(jié)束后也會(huì)返回None。
3.7 深入函數(shù)定義
定義參數(shù)可變的函數(shù)
3.7.1參數(shù)默認(rèn)值
給一個(gè)或多個(gè)參數(shù)指定默認(rèn)值
3.7.2 關(guān)鍵字參數(shù)
函數(shù)可以通過關(guān)鍵字參數(shù)的形式來調(diào)用,形如‘keyword=value’。例如,以下的函數(shù):
>>> 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 !
參數(shù)列表中的每一個(gè)關(guān)鍵字都必須來自于形式參數(shù),每個(gè)參數(shù)都有對應(yīng)的關(guān)鍵字。形式參數(shù)有沒有默認(rèn)值并不重要。實(shí)際參數(shù)不能一次賦多個(gè)值。形式參數(shù)不能在同一次調(diào)用中同時(shí)使用位置和關(guān)鍵字綁定值。
>>> 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'
>>>
引入一個(gè)形如**name的參數(shù)時(shí),它接收一個(gè)字典,該字典包含了所有未出現(xiàn)在形式參數(shù)列表中的關(guān)鍵字參數(shù)。這里可能還會(huì)組合使用一個(gè)形如*name的形式參數(shù),它接收一個(gè)元組,包好了所有沒有出現(xiàn)在形式參數(shù)列表中的參數(shù)值。(*name必須在**name之前出現(xiàn))
>>> 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 可變參數(shù)列表
函數(shù)可以調(diào)用可變個(gè)數(shù)的參數(shù)。這些參數(shù)被包裝進(jìn)一個(gè)元組。在這些可變個(gè)數(shù)的參數(shù)之前,可以有零到多個(gè)普通的參數(shù):
>>> def fprintf(file, format, *args):
... file.write(format % args)
...
3.7.4 參數(shù)列表的分解
當(dāng)傳遞的參數(shù)已經(jīng)是一個(gè)列表的時(shí)候,而要調(diào)用的函數(shù)卻接受分開一個(gè)個(gè)的參數(shù)值。這時(shí)要把已有的列表拆開。
>>> args = [3, 6]
>>> range(*args)
[3, 4, 5]
>>>
使用**操作符分拆關(guān)鍵字參數(shù)為字典
3.7.5 Lambda形式
通過lambad關(guān)鍵字,可以創(chuàng)建短小的匿名函數(shù)。這里有一個(gè)函數(shù)返回它的兩個(gè)參數(shù)的和:‘lambda a, b: a+b’。Lambda形式可以用于任何需要的函數(shù)對象。出于語法限制,它們只能有一個(gè)單獨(dú)的表達(dá)式。語義上講,它們只是普通函數(shù)定義中的一個(gè)語法技巧。類似于嵌套函數(shù)定義,lambda形式可以從包含范圍內(nèi)引用變量:
>>> def make_incrementor(n):
... return lambda x: x+n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
3.7.6 文檔字符串
第一行介紹對象的用途。如果文檔字符串有多行,第二行應(yīng)該空出來,與接下來的詳細(xì)描述明確分割。下面的文檔應(yīng)該有一或多段描述對象的調(diào)用約定、邊界效應(yīng)。
>>> 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.
>>>