python更多文法
一、if 語句
python支援 if 語句。例:
>>> x = int(raw_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'
...
More
elif 語句可以是零個、一個或多個;也可沒有else 部分。elif 是 else if 的縮寫。另外,條件後面的語句要注意使用縮進。否則會出現縮進錯誤。
![]() | 正 |
| 誤 |
二、for 語句
python 中的for 語句與 C 和 Pascal 的風格不一樣。例:
>>> # 聲明字元串數組:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print w, len(w)
...
cat 3
window 6
defenestrate 12
>>> for w in words[:]:
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
三、range() 函數
range() 函數用于産生一定範圍的數。例:
>>> range(10) # 一個參數,0-10的數,公差是1.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10) # 兩個參數,5-10的數,公差是1.
[5, 6, 7, 8, 9]
>>> range(0, 10, 3) # 三個參數,0-10的數,公差是3.
[0, 3, 6, 9]
>>> range(-10, -100, -30) #三個參數,-10 ~ -100,公差是-30.
[-10, -40, -70]
>>> 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
四、break、continue語句
二者都用于跳出循環。break 在某次跳出循環後便不再繼續後面的循環;continue在某次跳出循環後仍繼續後面的循環。例:
>>> 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
>>> 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語句
pass 語句表示什麼都不做。相當于空。例:
>>> while True: # 空循環
... pass
...
>>> class MyEmptyClass: # 空類
... pass
...
>>> def initlog(*args): # 空方法
... pass
...
六、聲明(定義)函數(方法)
如此定義使用函數:
# 例一
>>> def fib(n): # 定義 fib 函數,此函數有一個參數 n.def 是 define的縮寫。
... a, b = 0, 1 # 函數體必須縮進,不然會出現縮進錯誤。
... while a < n:
... print a,
... a, b = b, a+b
...
>>> # 調用函數 fib(n)
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
#例二
>>> def fib2(n):
... result = []
... a, b = 0, 1
... while a < n:
... result.append(a)
... a, b = b, a+b
... return result # 傳回 result 的值
...
>>> f100 = fib2(100)
>>> f100 # 輸出結果
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#例三
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
# 參數有預設值
while True:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): # in 檢測 ok 是否是()中備選值之一。
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise IOError('refusenik user')
print complaint
可以這樣調用例三中的方法:
- ask_ok(‘Do you reallywant to quit?’)
- ask_ok(‘OK to overwritethe file?’, 2)
- ask_ok(‘OK to overwrite thefile?’, 2, ‘Come on, only yes or no!’)
再看幾個例子:
>>>i = 5
>>>def f(arg=i):
... print arg
>>>i = 6
>>>f()
5 # 結果是 5 而不是 6.
>>>def f(a, L=[]):
... L.append(a) # 每次調用此方法都會在 L 中追加 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
... L.append(a)
... return L
>>>print f(1)
>>>print f(2)
>>>print f(3)
[1]
[2]
[3]
七、關鍵參數
可以通過設定關鍵參數的方法調用函數。例:
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 plumage, the", type
print "-- It's", state, "!"
此函數含有一個必要參數(voltage)和三個可選參數(state,action,type)。
可以這樣調用此函數:
parrot(1000)
parrot(voltage=1000)
parrot(voltage=1000000, action='VOOOOOM')
parrot(action='VOOOOOM', voltage=1000000)
parrot('a million', 'bereft of life', 'jump')
parrot('a thousand', state='pushing up the daisies')
但不可以這樣調用:
parrot()
parrot(voltage=5.0, 'dead')
parrot(110, voltage=220)
parrot(actor='John Cleese')
再看一個錯誤的調用:
>>> def function(a):
... pass
...
>>> function(0, a=0) # 給 a 賦了多個值,當然會出錯。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for keyword argument 'a'
再看一個例子:
>>>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
調用時傳遞了 6 個參數。其中Limburger是 參數kind的值; shopkeeper ,client,sketch 都未在cheeseshop 函數中定義。是以這三個參數将被存在 **keywords 中。其餘兩個字元串将被存在 *arguments 中。
八、解析清單或元組中的參數。
假如某個函數需要傳多個參數。可以将需要傳遞的各個參數定義在一個清單中。而後使用 * 得到各個參數。例:
>>> range(3, 6) # 此方法需要兩個參數
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # 用 * 取得清單中的各個元素值
[3, 4, 5]
也可以将參數定義在元組中。而後使用 ** 得到各個參數。例:
>>> def parrot(voltage, state='a stiff', action='voom'):
... print "-- This parrot wouldn't", action,
... print "if you put", voltage, "volts through it.",
... 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 !
九、Lambda 表達式
用關鍵字 lambda 指定一個匿名函數。例:
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
make_incrementor 函數傳回的結果是個匿名函數。該函數需要一個參數 x 。是以可以用 f(0) 的形式繼續計算。
另一種用法是将函數當參數傳遞。例:
>>> 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')]
十、大文本字元串
如此用:
>>> 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.